### Phase 5: Report

> **TLDR**  -  Two halves. **External delivery** goes to `/multi-agent:channels`, the single source of truth for Jira, Confluence, wiki and PR-description delivery (channel and content multi-select; always pauses in autopilot, a 30-minute timeout ends the session; contract in `commands/multi-agent/channels/SKILL.md`). **Internal capture** stays inline: `agent-log.md`, telemetry, knowledge base and memory.

<!-- progress-contract: applied -->
Progress per `$HOME/.claude/multi-agent-refs/progress-contract.md`: channels dispatch, each adapter's result, agent-log, telemetry, knowledge and memory.

## Sub-step Tracking (required)

Phase 5 has **3 ordered sub-steps** (external delivery lives under channels), registered by `add` from `schemas/phases.json`.

```bash
bash ~/.claude/scripts/phase-tracker.sh update 5 in_progress
```

On entry: `phase-tracker.sh sub 5 <N> "<name>" in_progress`. On exit: `completed` / `failed` / `skipped` / `timeout`.

---

## Autopilot pause contract

Phase 5 is the single exception to the autopilot zero-interaction rule: every mode, attended or autopilot, pauses at the channels multi-select menu. Full contract in `$HOME/.claude/multi-agent-refs/phases/modes.md`:

- **30-min timeout**  -  if user does not respond, session ends cleanly. External delivery is aborted (no silent apply of defaults  -  prevents accidental Jira comments / Confluence pages). Internal capture (Steps 2 + 3 below) STILL runs so `agent-log.md` + knowledge base are persisted.
- **Resumable**  -  state written as `{status: "awaiting_input", currentPhase: 5, waitingFor: "user-channels-choice"}`. User can `/multi-agent:resume <task-id>` any time later; the channels menu re-opens from the run's own state.
- **Timeout log line:** `Phase 5: channels menu timeout (30 min)  -  session ended, resume with /multi-agent:resume {taskId}`.

---

## Step 1  -  External Delivery (delegated to channels)

Phase 5 builds a state bundle and invokes `/multi-agent:channels` (Claude Code) or `multi-agent-channels` (Copilot CLI). This is the ONLY external-delivery step: no Jira/Confluence/Wiki/PR-description logic lives in Phase 5.

> **Local-only short-circuit**: when `state.offlineOnly == true` (all repos
> are local  -  see Phase 0), Step 1 is **skipped entirely**. No channels menu,
> no Jira/Wiki/Confluence/PR adapters, no autopilot pause. The tracker
> records `step1.status = "file-only"`, channels runs once with `--file-only`,
> and the internal capture sub-steps continue. Reports: `agent-log.md` and
> `task-report.md` on disk (`channels/report-file.md`).

> **Unattended** (`MULTI_AGENT_UNATTENDED=1`): external delivery is
> `deferred-to-runner` (`features/unattended-security.md`); channels still runs
> with `--file-only`, so the report lands under `LOGS_ROOT`.

> **If the access check stops channels** (`ACCESS_RC` 3), Phase 5 records
> `report file not written` and continues its internal capture; it never halts.

### State bundle passed to channels

```json
{
  "jiraId": "PROJ-12345",
  "prUrl": "https://.../pull/42",
  "prNumber": 42,
  "remoteType": "github" | "bitbucket",
  "taskType": "component" | "bugfix" | "feature" | "refactor",
  "figmaConfig": { /* from project figma-config.json, or null */ },
  "agentState": { /* agent-state.json contents */ },
  "pipelineLogPath": "$HOME/.claude/logs/multi-agent/<project>/<task-id>/agent-log.md",
  "flowRuns": ["<runId>"],
  "invokedFrom": "phase-5"
}
```

Channels reads this bundle, skips target resolution and opens the menu.

### Figma evidence embedding (when `state.evidence.figma[]` is non-empty)

For every UI atom touched by the diff, the PR description, Jira comment, and Confluence page body MUST embed the Figma frame reference and screenshot URL. Channels adapters read `state.evidence.figma[]` and render a `## Figma reference` block per channel:

- **PR description**  -  one row per frame: `<canonicalComponentName>  <fileKey>:<nodeId>  [screenshot](<screenshotUrl>)`.
- **Jira comment**  -  same row shape; image macros may be added when the Jira project allows direct image embedding (see `$HOME/.claude/multi-agent-refs/channels/jira.md`).
- **Confluence page**: frame screenshots are uploaded as page attachments (cache locally first because Tier 2 signed URLs expire after 30 days) and referenced inline via `<ac:image><ri:attachment ri:filename="frame-<nodeId>.png"/></ac:image>`.

Tier 3 rows append `(tier 3: pending design review)` after the canonical component name so reviewers know the choice is provisional. The block is suppressed when `state.evidence.figma[]` is empty (non-UI tasks).

### Menu (identical to post-hoc `/channels` call  -  single source of truth)

```
Kanallar: [x] PR  [x] Jira  [ ] Confluence  [ ] Wiki
İçerik:   [x] Normal analiz  [x] Test senaryoları  [ ] Auto-diff  [ ] Manuel not
```

Pre-ticks from `prefs.global.reportChannels` + `prefs.global.reportContent`. Greyed-out rules (pipeline context, PR linked, taskType=component, wiki.enabled) per `channels.md` Step 3.

**User selects → channels dispatches → returns per-adapter results. Phase 5 records outcomes into tracker + summary block.**

### Per-adapter outcomes (from channels return)

```json
{
  "pr":         { "status": "posted|skipped|failed", "url": "...", "version": "3→4" },
  "jira":       { "status": "posted|skipped|failed", "url": "...", "commentId": "2484780" },
  "confluence": { "status": "posted|skipped|failed", "url": "..." },
  "wiki":       { "status": "posted|skipped|failed", "paths": [...], "adapter": "github-wiki" }
}
```

Tracker: `phase-tracker.sh sub 5 1 "Channels dispatch" completed` (or `failed` if ALL adapters failed; `skipped` if user declined all).

For the office, record each adapter's `{status, url}` (https only) under `channelResults.<pr|jira|confluence|wiki|issue>`; `write-state.mjs` merges, Step 1.5 adds `issue`:

```bash
printf '%s' '{"channelResults":{"pr":{"status":"posted","url":"<url>"},"confluence":{"status":"skipped"}}}' | node $HOME/.claude/scripts/write-state.mjs "$STATE_FILE" >/dev/null
```
---

## Step 1.5  -  GitHub Issue channel (when tracker is a GitHub issue)

Runs only when `state.githubIssue` is set. The Issue adapter is required whenever the run was triggered from a GitHub issue  -  no exceptions, no "I'll just update the flags" shortcut. Full template + rules: `$HOME/.claude/multi-agent-refs/channels/issue-comment.md`.

**Approval gate:** interactive runs show the composed comment body (and the Progress-flag diff intent) through the same preview + approval gate as channels Step 6 (`channels.md`) before posting  -  Approve & post / Edit / Cancel. Autopilot posts directly.

Two paired actions, in order:

```bash
# 1. Post the canonical comment (template per refs/channels/issue-comment.md).
bash ~/.claude/scripts/phase-tracker.sh sub 5 1.5 "Issue comment" in_progress
# unattended: skipped - the runner posts (features/unattended-security.md)
gh issue comment "$ISSUE_NUMBER" --repo "$ORG/$REPO" --body-file /tmp/channels-${TASK_ID}-issue.md
bash ~/.claude/scripts/phase-tracker.sh sub 5 1.5 "Issue comment" completed
printf '%s' '{"channelResults":{"issue":{"status":"posted","url":"<url>"}}}' | node $HOME/.claude/scripts/write-state.mjs "$STATE_FILE" >/dev/null

# 2. Sync the Progress flag table from agent-state.json. Idempotent  -  the
#    script no-ops if the body already matches.
bash ~/.claude/scripts/phase-tracker.sh sub 5 1.6 "Progress flag sync" in_progress
# unattended: skipped - the runner syncs the flags (features/unattended-security.md)
bash ~/.claude/scripts/update-issue-progress.sh "$TASK_ID"
bash ~/.claude/scripts/phase-tracker.sh sub 5 1.6 "Progress flag sync" completed
```

Order matters: comment first (timestamp marks the run), flags second (one logical body diff). If the comment fails, do NOT update flags  -  the channel is incomplete and the user needs to retry.

The Progress flag values come from `state.flags`:

| state.flags key | Issue table label |
|---|---|
| `implementation` | Implementation |
| `testing`        | Testing        |
| `codeConnect`    | Code Connect   |
| `wiki`           | Wiki           |

Each value renders as `done` (`true`), `partial` (`"yellow"`), or `pending` (`false`/missing). Phase 2 / 5 / 6 are responsible for setting these honestly  -  Phase 5 only mirrors what's already in state.

**Hard rule (per `$HOME/.claude/multi-agent-refs/channels/issue-comment.md`):** never run only one of the two actions. The comment is the human-readable audit; flags are the machine-readable status. Either both or neither.

---

## Step 2  -  Finalize Report (internal)

Write `agent-log.md` with ALL sections:

```markdown
# {jiraId}  -  {Task Title}

**Branch**: {branch-name} | **Project**: {project}
**Started**: {datetime} | **Finished**: {datetime} | **Status**: Complete

## Plan Todo Rollup (when `prefs.global.planTodos.enabled`)

Rendered via `$HOME/.claude/lib/plan-todos.sh list "$TASK_ID"` and inlined verbatim: one line per todo with its marker ([x] / [~] / [/] / [!]), ID, text and notes, under the one-line summary from `plan-todos.sh status` ("4/6 done, 1 skipped, 1 failed").

Skipped sections: when `planTodos.enabled` is false or no `plan.todos[]` was emitted, the Plan Todo block is omitted (no empty header). Phase 2 task-by-task progress still appears in the Timeline section either way.

## Timeline

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

## Agent Activity Report

| Agent | Calls | Duration | Model |
| ----- | ----- | -------- | ----- |

## Review Iterations

| Iteration | Blocking | Important | Suggestion | Decision | Still present | Resolved | New |
| --------- | -------- | --------- | ---------- | -------- | ------------- | -------- | --- |

(the last three columns come from `reviewIterations[i].delta.counts` (Phase 3 Step 3.8) and read `-` on iteration 1 and on runs that predate the delta; a tripped circuit-breaker is one extra line under the table: `Circuit-breaker tripped: trigger {n}, {detail}`)

(autopilot: `decisions-log.mjs render --state "$STATE_FILE"` output verbatim; own heading, nothing when empty)

## Files Changed

(git diff --stat output)

## Skill Routing

(from `state.telemetry.skillRouting`: kept toolkits with version and role, each `excluded[]` and `unscoped[]` name with its reason, each `hints[]` message, and each `fallbacks[]` `reportLine` or `gap` verbatim. Omitted when the run has no `skillRouting`.)

## Repo Profile

(from `node $HOME/.claude/scripts/repo-profile.mjs report --repo "$PROJECT_ROOT" --state "$STATE_FILE"` and `state.repoProfile`: the `action`, whether it was confirmed, `derived` fields against `confirmed` or `manual` ones, and each `ignored[]` field with confidence and reason; omitted without a `repoProfile`.)

## Channels Summary

| Channel    | Status             | Link                                       |
| ---------- | ------------------ | ------------------------------------------ |
| PR         | posted \| skipped  | {prUrl} (reviewers preserved, v X→Y)       |
| Jira       | posted \| skipped  | {jiraUrl}?focusedCommentId={id}            |
| Confluence | created \| skipped | {confluenceUrl}                            |
| Wiki       | {N} files \| skip  | {wikiUrl} (adapter: {submodule\|...})      |

## Pipeline Metrics (last 30 days)

(embed `aggregate-metrics.mjs --since=<30 days ago> --json` output as collapsed JSON)
```

**Telemetry emission** (required): forward the phase's own LLM spend (humanizer + report compose calls) to the tracker, then emit the final event:

```bash
LOG_METRIC_FORWARD_TO_TRACKER=1 $HOME/.claude/scripts/log-metric.sh "$TASK_ID" 5 report.compose \
  model=$REPORT_MODEL tokens_in=$R_IN tokens_out=$R_OUT duration_ms=$R_DUR
$HOME/.claude/scripts/log-metric.sh "$TASK_ID" 5 task.completed \
  phases=$PHASE_COUNT review_cycles=$CYCLES lang=$PROMPT_LANG \
  channels_pr=$PR_STATUS channels_jira=$JIRA_STATUS \
  channels_confluence=$CONF_STATUS channels_wiki=$WIKI_STATUS \
  duration_ms=$TOTAL_DURATION
```

**Operational reporting** (`features/usage-reporting.md`): mark the run finished, then report it. Neither blocks:

```bash
STATE_FILE="${STATE_FILE:-$(node $HOME/.claude/scripts/usage-report.mjs --task-id "$TASK_ID" --print-state)}"
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)
WS_ERR=$(printf '{"status":"complete","currentPhase":5,"finishedAt":"%s"}' "$TS" \
  | node $HOME/.claude/scripts/write-state.mjs "$STATE_FILE" 2>&1 >/dev/null); WS_RC=$?
[ "$WS_RC" = 0 ] && node $HOME/.claude/scripts/usage-report.mjs --task-id "$TASK_ID" --event completed --detach >/dev/null 2>&1
```

Then add the reporting state to the final report when it needs the person (empty otherwise; never a question, also unattended):

```bash
USAGE_LINE=$(node $HOME/.claude/scripts/usage-register.mjs --status-line 2>/dev/null)
```

A non-empty `$USAGE_LINE` goes into the final report as written, in outputLanguage already.

`WS_RC` 6: `$WS_ERR` names what `complete` still lacks; record it (operations.md "Completion evidence") and write again, or halt. Parked on the channels choice instead: emit `--event parked` and leave `status` alone.

**Aggregate before reporting**: run `aggregate-metrics.mjs --since=$(date -u -v-30d +%Y-%m-%d)` and embed output in agent-log.md. Use `--json` for Jira; missing files are skipped.

**Per-run outcome metrics (evidence corpus):** also emit `run-metrics.mjs --state <agent-state.json>` and append/persist its JSON. It records review iterations, first-pass-clean, reviewer signal-to-noise, consensus verdict and build outcome.

**Routing outcomes:** with `modelRouting.learned.enabled`, run `route-learn.mjs ingest --state "$STATE_FILE"` (outcome rows only, `features/model-fallback.md`).

**Cost Breakdown emission (required):** as part of agent-log compose, append the per-task cost block produced by `render-agent-log-cost.sh`:

```bash
bash $HOME/.claude/scripts/render-agent-log-cost.sh "$TASK_ID" --append "$AGENT_LOG" 2>/dev/null
```

This is independent of the channels-side `reportContent.costSummary` (which gates the PR-body Cost Summary). agent-log always carries the breakdown when telemetry is present.

**Missing-telemetry disclosure (required).** Name untracked phase ids as cost-unavailable in the report and closing summary. Mechanic: `payload-contracts.md`.

**Final capture flush (required):** persist the triage findings and the durable learnings this run established.

```bash
bash $HOME/.claude/scripts/capture-flush.sh --state "$STATE_FILE"
```

Every phase boundary already made this call (`operations.md`), so here it usually writes 0 rows: Phase 5 is the last flush, not the only one, because it is the phase a run is least likely to reach.

What it does, so this doc stays inspectable:

- **Triage ingest** (`triage-memory.mjs ingest`): accepted, deferred and rejected rows into the per-repo `triage-corpus.jsonl` (never cross-repo) that Phase 1 and Phase 3 recall. Idempotent. It reads the salvaged copy under `artifactsPath` first (Phase 4 removes the worktree). Off when `prefs.global.priorArtEnrichment.ingestOnComplete = false`.
- **Ledger distill** (`learnings-ledger.mjs from-triage`): rejected findings become `rejected-preference` entries. Idempotent. A blocking rejection is never distilled; `forget` clears a stale entry. Replayed into Phase 1 and Phase 3; on via `prefs.global.learningsLedger.enabled`.
- **Debt list** (`debt.jsonl`): `debt-ledger.mjs from-run` (deferred, parked), `add --patch` (`shortcut:` markers).

No model runs in the flush (inputs: `triage-output.json`, `agent-state.json`, the run's diff), which is what lets a hook call it. The parts that need a model (Step 3 knowledge capture, memory synthesis) stay here.

A durable architectural fact or decision is a judgement call, so it stays here rather than in the flush. A decision (`--kind decision --rationale`) that replaces an earlier one adds `--supersedes <L:id>`:

```bash
# node $HOME/.claude/scripts/learnings-ledger.mjs add --kind fact \
#   --statement "<one-line fact>" --scope "<path-glob>" --task "$TASK_ID" >/dev/null 2>&1 || true
# node $HOME/.claude/scripts/learnings-ledger.mjs add --kind decision --statement "<decision>" \
#   --rationale "<why>" --scope "<path-glob>" --supersedes "<L:id>" --task "$TASK_ID" >/dev/null 2>&1 || true
# for each [L:id] in the Phase 1/3 memory blocks the run relied on (useful) or found wrong (dead_end|corrected):
# node $HOME/.claude/scripts/learnings-ledger.mjs feedback --id "<L:id>" --outcome useful --task "$TASK_ID"
```

Phase 5 never promotes a learning to the global ledger; that is `promote`, on request, one approval per candidate (`knowledge.md`).

Print the closing report to the terminal. Two blocks, in this order  -  what the pipeline spent, then what it changed:

```bash
bash $HOME/.claude/scripts/phase-tracker.sh report
bash $HOME/.claude/scripts/render-work-summary.sh "$TASK_ID" --format terminal --worktree "$WORKTREE_PATH"
```

`report` prices the run phase by phase; `render-work-summary.sh` says what changed on disk. Both land in tool output, which the host collapses, so **reprint them in your reply** followed by this line:

```
{jiraId} complete
Total: Xm Ys | Agents: N calls | Files: N changed
Channels: PR ✓ · Jira ✓ · Confluence - · Wiki ✓ (3 files)
Commit: abc1234 | PR: #87
Full report: $HOME/.claude/logs/multi-agent/{project}/{task-id}/agent-log.md
```

Plan row: `plan-attachment.mjs line --state "$STATE_FILE"`, omitted when it prints nothing.

Tracker: `phase-tracker.sh sub 5 2 "Log + telemetry" completed`.

## Step 3  -  Knowledge Capture (incremental learning)

Extract reusable knowledge from this task and **append** to `$HOME/.claude/knowledge/{project-name}/`:

| File              | What to Add                                     | Source                            |
| ----------------- | ----------------------------------------------- | --------------------------------- |
| `architecture.md` | Newly discovered modules, relationships, deps   | Phase 1 Explore                   |
| `patterns.md`     | Conventions, naming, recurring structures       | Phase 1 + Phase 3                 |
| `gotchas.md`      | Build errors/solutions, edge cases, workarounds | Phase 2 retries, Phase 3 blocking |
| `decisions.md`    | Architectural decisions + rationale             | Phase 1 plan + Phase 3            |

**Rules:** Only save reusable knowledge (task-specific details stay in agent-log). Read existing files before appending  -  no duplicates. Add date: `<!-- captured: {date}, task: {jiraId} -->`. Conflicting info → update old entry, don't delete.

**Entry format:**

```markdown
<!-- captured: {date}, task: {jiraId} -->

### {Topic Title}

{Concise, actionable description}
```

**First task** (no knowledge dir): `mkdir -p`, create initial architecture.md + patterns.md from Phase 1. Log: "Knowledge base initialized for {project}"

**Code graph refresh:** with `prefs.global.codeGraph.enabled` and `.autoRefresh` both true, rebuild the graph and `GRAPH_REPORT.md`, since the branch changed the code Phase 1 described. No API tokens, never fails the run; commands in `$HOME/.claude/multi-agent-refs/features/code-graph.md`.

**Save preferences**: Update prefs with Phase 5 selections (via channels return: `reportChannels`, `reportContent`, `confluenceUrls` per-project LRU).

**Per-repo memory synthesis (opt-in via `prefs.global.perRepoMemory`):**

After knowledge capture, a scoped synthesis subagent (sonnet, 10 turns max) reads this run's `agent-log.md` and the MEMORY.md index and returns 0-3 new entries as a JSON array of `{type: "user|feedback|project|reference", slug, title, description, body}`. The orchestrator saves them all, in order:

```bash
bash $HOME/.claude/scripts/memory-save.sh "$PROJECT_ROOT" --from-json memory-synthesis.json
```

**Synthesis prompt scope** (keep narrow):
- **feedback**: only if the user corrected a pipeline behavior during this run ("no, don't", "stop doing X", or explicit approval of an unusual choice)
- **project**: only if someone named a new deadline, constraint, or stakeholder that wasn't already in the task description
- **reference**: only if an external system URL / dashboard / channel was mentioned as the source of truth for some concern
- **user**: only if the user disclosed new context about their role, expertise, or team layout
- **Otherwise return `[]`**  -  blank is the correct default. Do not save derivable facts (code structure, git history, command outputs).

Tracker: `phase-tracker.sh sub 5 3 "Knowledge + memory" completed`.

Log: "Phase 5: Knowledge captured ({N} entries to {files})"

---

## Timeout behavior (30-min channels menu wait)

If user does not respond at the channels multi-select menu within 30 minutes (wall clock from menu render):

1. Channels command aborts its interactive prompt, returns `{status: "timeout"}`.
2. Phase 5 records `phase-tracker.sh sub 5 1 "Channels dispatch" timeout`.
3. **Internal capture still runs**  -  Steps 2 + 3 write `agent-log.md` (with `channels: timeout` in summary), emit telemetry, update knowledge base.
4. Session exits cleanly. State persisted: `state.currentPhase=5, state.waitingFor="user-channels-choice", state.channelsTimeout=true`.
5. Resume contract: `/multi-agent:resume <task-id>` re-opens the channels menu with the original state bundle (pipeline log, PR metadata, prefs pre-ticks).

Rationale: posting defaults after a timeout would publish text nobody approved.

---

#### Output Quality + Metrics Section

Append to every Phase 5 report (knowledge-capture pass) a **Quality & Metrics** block built from `metrics.jsonl` and the latest task's artifacts:

```
## Quality & Metrics

### Output Quality
- Commit message format: ✓ pass / ✗ fail
- PR body (real newlines, no HTML entities, sections present): ✓ / ✗
- Jira comment format: ✓ / ✗
- Reviewer JSON valid: N/N
- Triage JSON valid + no contradictions: ✓ / ✗
- Code review severity ratio (blocking : important : suggestion): X : Y : Z (target ≤ 1 : 2 : 4)

### Token & Cost
- Tokens in / out: <a> / <b>
- Premium calls (opus + gpt): <c>
- Estimated cost (USD): $<d.dd>
- Budget status: under | at | over

### Build / Push
- Build success rate this task: <pass>/<total>
- Push attempts (per repo): <n>
- Multi-repo: <repo count> repos, <skipped count> skipped
```

The block is generated by `output-quality-check.sh` + `token-budget-report.mjs --task $TASK_ID --json` and pasted verbatim. If either script is missing, that subsection is omitted (best-effort).

#### Final metrics report appended to PR body at release time

When the pipeline cuts a release, append the latest 30-day rollup to the release PR body:

```bash
node $HOME/.claude/scripts/token-budget-report.mjs --period monthly --append
printf '\n\n## Release-window metrics (last 30 days)\n\n' | cat existing-body.md - > release-body.md
tail -10 $HOME/.claude/logs/multi-agent/metrics-summary.md >> release-body.md
# unattended: skipped - a person edits a release PR
gh pr edit "$RELEASE_PR" --body-file release-body.md
```
