## Log File Format (Detailed)

> **TLDR**  -  Canonical shape of `agent-log.md`: header block (task id, branch, status), Timeline table (phase by phase), Agent Activity Report (calls + duration per agent), ASCII phase-duration distribution, Review Iterations, Files Changed (`git diff --stat`), Review Consensus, Cost Breakdown, and Test Scenarios. Every pipeline run must produce this file at the global log path.

Create at `$HOME/.claude/logs/multi-agent/{project}/{task-id}/agent-log.md`:

```markdown
# {task-id}  -  {Task Title}

**Branch**: {branch-name}
**Project**: {project}
**Started**: {YYYY-MM-DD HH:mm}
**Finished**: {YYYY-MM-DD HH:mm}
**Total Duration**: {Xm Ys}
**Status**: In Progress | Complete | Paused | Failed

## Timeline

| #   | Phase | Agent | Model | Duration | Tokens (in/out) | Status | Detail |
| --- | ----- | ----- | ----- | -------- | --------------- | ------ | ------ |

> `Tokens (in/out)` is sourced from `phase-tracker.sh tokens` accumulators. Empty cell renders as ` - ` when no telemetry was captured for that row.

## Agent Activity Report

| Agent         | Calls  | Duration   | Model(s)     |
| ------------- | ------ | ---------- | ------------ |
| explore       | 3      | 12s        | haiku        |
| code-reviewer | 2      | 37s        | opus, sonnet |
| task (build)  | 4      | 2m 15s     | sonnet       |
| **TOTAL**     | **10** | **3m 04s** |              |

## Phase Duration Distribution

Phase 0: Init ████░░░░░░░░░░░░ 5s
Phase 1: Analysis ██████░░░░░░░░░░ 12s
Phase 2: Planning █████░░░░░░░░░░░ 8s
Phase 3: Dev ████████████████ 2m 35s
Phase 4: Review ████████░░░░░░░░ 37s
Phase 5: Test ██░░░░░░░░░░░░░░ (user wait)
Phase 6: Commit ██░░░░░░░░░░░░░░ 3s
Phase 7: Report █░░░░░░░░░░░░░░░ 2s

## Review Iterations

| Iteration | Blocking | Important | Suggestion | Decision |
| --------- | -------- | --------- | ---------- | -------- |

## Files Changed

(git diff --stat output)

## Review Consensus

(emit from the last iteration's `triage.consensus` block, schema v3.1.0. One line stating `verdict` + `reviewerCount`; when `verdict` is `split` or `unverified`, list each `disagreements[]` entry so a human can confirm what the reviewers did not independently agree on. Omit the section when triage produced no consensus block.)

```
Verdict: unverified (2 reviewers)
- Auth/KeychainStore.swift:40  -  token persisted without access-control flag
  (both approved a keychain change  -  agreement unverified, confirm manually)
```

## Cost Breakdown

(emit by Phase 7 via `$HOME/.claude/scripts/render-agent-log-cost.sh <task-id>`. Renders unconditionally on every run. If the renderer exits 2 (no tracker data + no OTel spans), Phase 7 omits this section without failing the run.)

| Phase | Model | Tokens in | Tokens out | Est. USD |
| ----- | ----- | --------- | ---------- | -------- |

(Below the Total row the renderer appends a `*Top cost driver: <phase>  -  $X (Y% of total).*` line so the reader sees WHERE the spend went, not just the sum. When the tracker recorded `tokens_cached` for any phase, a `*Cache reads: N tokens billed at the discounted cache-read rate.*` line follows  -  this makes resume / prompt-cache reuse visible instead of hidden in the input total.)

## Test Scenarios (Jira)

(User perspective: Precondition -> Steps -> Expected result)

## Handoff - end of Phase {N} ({name}) - {ISO timestamp}

(v10.8.0, appended chronologically by the phase-boundary checkpoint  -  one block per phase transition, the LATEST block is authoritative. Written by the orchestrator from state it already holds; no LLM call, ~15 lines max. `resume.md` Step 3 and post-`/compact` re-grounding read this block FIRST. Format spec: `$HOME/.claude/multi-agent-refs/phases/operations.md`.)

- Done: {up to 3 bullets of completed outcomes}
- Remaining: {ordered list of remaining phases / sub-steps}
- Decisions: {key decisions later phases depend on}
- Open findings: {accepted-but-unresolved review findings, or "none"}
- Next: Phase {N+1} {name}, subStep {token or "start"}
```

### Cost Breakdown  -  emission contract

Phase 7 MUST attempt to render the Cost Breakdown section as part of the agent-log compose step:

```bash
COST_BLOCK=$(bash $HOME/.claude/scripts/render-agent-log-cost.sh "$TASK_ID" 2>/dev/null) && \
  printf '%s\n' "$COST_BLOCK" >> "$AGENT_LOG"
```

Emission is best-effort  -  exit 2 (no data) is silently skipped. Never fail the pipeline on a missing cost block. The renderer reuses `cost-table.json` so any `cost-table` price update flows through to both PR-body and agent-log surfaces.

### Tokens telemetry  -  phase responsibility

Every phase that dispatches a billable LLM agent MUST forward its token totals to the tracker. The minimal contract (already enforced via `smoke-tracker-contract.sh` for Phase 4):

```bash
$HOME/.claude/scripts/log-metric.sh "$TASK_ID" <phase-id> <event> \
  model=<fable|opus|sonnet|haiku|gpt-5.4|gpt-5.6|gpt-5.6-terra> tokens_in=$IN tokens_out=$OUT tokens_cached=$CACHED duration_ms=$DUR
LOG_METRIC_FORWARD_TO_TRACKER=1 $HOME/.claude/scripts/log-metric.sh "$TASK_ID" <phase-id> tokens \
  model=<...> tokens_in=$IN tokens_out=$OUT tokens_cached=$CACHED
```

Setting `LOG_METRIC_FORWARD_TO_TRACKER=1` makes `log-metric.sh` mirror the same `tokens_in`/`tokens_out`/`tokens_cached` into the tracker  -  so JSONL metrics and tracker accumulators stay in sync from a single call site. Without this flag the JSONL line is written but the tracker is not updated; that mode is reserved for one-off analytics events that should not affect the cost block.

**Token-count contract (cache-exclusive).** The three counts are disjoint and map directly onto the host's usage report:

| Field | Host usage field | Meaning | Priced at |
|-------|------------------|---------|-----------|
| `tokens_in` | `input_tokens` | freshly-billed input, NOT including cache reads | `inPerMtok` |
| `tokens_cached` | `cache_read_input_tokens` | input served from the prompt cache | `cacheReadPerMtok` |
| `tokens_out` | `output_tokens` | generated output | `outPerMtok` |

Total input processed = `tokens_in + tokens_cached`. Never fold the cached count into `tokens_in`, and never subtract one from the other  -  both `render-agent-log-cost.sh` (pricing) and `aggregate-metrics.mjs` (cache-reuse ratio = `cached / (in + cached)`) assume this disjoint convention. `tokens_cached` is optional and defaults to 0: a phase whose host does not surface a cache-read count omits it and is priced exactly as before, so this stays backward-compatible with any tracker that predates the field.
