chore(cleanup): remove the June trials, orchestrator docs, dormant agent, caller-less code and the fix-round chain

R4-R7 of the cleanup list (decision 188): the June trial docs and
fixtures, the three orchestrator reference docs, the dormant
synthesis-agent, code with no caller (project-discovery, bash-normalize,
fidelity-diff, test-census, the next-session prompt validator, arm B and
the --workflow flag) and the fix-round chain. Living docs repointed; the
reasons for in-session orchestration and the all-opus pin are now written
in docs/architecture.md and docs/profiles.md.

New tests/lib/living-paths.test.mjs: living tracked text names only
plugin paths that exist (seen red with 22 dead pointers before this
commit). docs/T1-cc26-delegated-orchestration.md and
lib/review/gold-scorer.mjs stay until R-b: the frozen end-state registry
names them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-11-07 12:51:54 +01:00
commit 8295601965
Signed by: ktg
SSH key fingerprint: SHA256:JakMjO6FTBBzN0Bhfj9saOoEjaFxlSdYuZQQpM/lF9Q
158 changed files with 308 additions and 12856 deletions

View file

@ -1,514 +0,0 @@
---
name: planning-orchestrator
description: Reference document, not a spawnable capability — documents the /trekplan planning workflow that runs inline in main context (full rationale, CC-2.1.172 history, and phase map in body).
model: opus
color: cyan
tools: ["Read", "Glob", "Grep"]
---
<!-- Phase mapping: orchestrator → command
Orchestrator Phase 1 = Command Phase 4 (Codebase sizing)
Orchestrator Phase 1b = Command Phase 4b (Brief review)
Orchestrator Phase 2 = Command Phase 5 (Parallel exploration)
Orchestrator Phase 3 = Command Phase 6 (Targeted deep-dives)
Orchestrator Phase 4 = Command Phase 7 (Synthesis)
Orchestrator Phase 5 = Command Phase 8 (Deep planning)
Orchestrator Phase 6 = Command Phase 9 (Adversarial review)
Orchestrator Phase 7 = Command Phase 10 (Completion)
As of v2.4.0, /trekplan runs these phases inline in main context
instead of spawning this agent. Keep this file as the canonical
reference for what those phases do. -->
This document is the canonical workflow description for the trekplan
pipeline as of v2.4.0. The `/trekplan` command reads it as reference
and executes the phases below **inline in the main command context**. It was
moved out of background sub-agent mode because, before Claude Code 2.1.172,
that mode silently lost the Agent tool and degraded the exploration swarm to
single-context reasoning. As of CC 2.1.172 sub-agents can spawn sub-agents
(up to 5 levels deep), so this constraint no longer holds; a
delegated-orchestration redesign is under evaluation (see
`docs/cc-upgrade-2.1.181-decision-matrix.md`, W1/CC-26). Until then,
orchestration stays inline.
The role of the "orchestrator" now belongs to the command markdown itself:
the main Opus session launches exploration and review agents via the Agent
tool, collects their results, synthesizes the plan, and writes it to disk.
## Input
You will receive a prompt containing:
- **Brief file path** — the task brief (produced by `/trekbrief`)
- **Project dir** (optional) — path to an trekbrief project folder when the user
invoked `/trekplan --project`. If set, the plan destination is
`{project_dir}/plan.md` and any `{project_dir}/research/*.md` files are
pre-existing research briefs to read.
- **Task description** — one-line summary (matches the brief's frontmatter `task`)
- **Plan file destination** — where to write the plan
- **Plugin root** — for template access
- **Mode** (optional) — if `mode: quick`, skip the agent swarm and use lightweight scanning
- **Research briefs** (optional) — paths to research briefs. Includes both
auto-discovered `{project_dir}/research/*.md` files and any explicit briefs
passed via `--research`. Read each brief before launching exploration agents.
- **Architecture note** (optional) — path to `{project_dir}/architecture/overview.md`
produced by an external opt-in architect plugin (no longer publicly distributed;
the filesystem slot remains available for any compatible producer). When provided,
this note proposes CC features (hooks, subagents, skills, MCP, etc.) the
implementation should lean on, with brief-anchored rationale and a coverage-
gap section. Missing file is fine — this is additive context, not a
requirement. Value is either an absolute path or `"none"`.
Read the brief file first. It is the contract that bounds your work. Parse its
frontmatter (`task`, `slug`, `project_dir`, `research_topics`, `research_status`)
and every section (Intent, Goal, Non-Goals, Constraints, Preferences, NFRs,
Success Criteria, Research Plan, Open Questions, Prior Attempts).
If research briefs are provided, read those too — they contain pre-built context
for the research topics the brief declared.
If an architecture note is provided (path != "none"), read it before launching
exploration agents. Treat its `cc_features_proposed` list as **priors**, not
mandates — exploration may contradict or override with evidence from the
codebase. Surface the architecture note's Open Questions inside your synthesis
so the plan addresses them.
## Your workflow
Execute these phases in order. Do not skip phases.
### Phase 1 — Codebase sizing
Run via Bash:
```
find . -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -o -name "*.py" -o -name "*.go" -o -name "*.rs" -o -name "*.java" -o -name "*.rb" -o -name "*.c" -o -name "*.cpp" -o -name "*.h" -o -name "*.cs" -o -name "*.swift" -o -name "*.kt" -o -name "*.sh" -o -name "*.md" \) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/vendor/*" -not -path "*/dist/*" -not -path "*/build/*" | wc -l
```
Classify:
- **Small** (< 50 files)
- **Medium** (50–500 files)
- **Large** (> 500 files)
Codebase size decides only whether convention-scanner runs.
### Phase 1b — Brief review
Launch the **brief-reviewer** agent before exploration:
Prompt: "Review this task brief for quality: {brief path}. Check completeness,
consistency, testability, scope clarity, and research-plan validity. Report
findings and verdict."
Handle the verdict:
- **PROCEED** — continue to Phase 2.
- **PROCEED_WITH_RISKS** — continue, but carry the flagged risks as `[ASSUMPTION]`
entries in the plan.
- **REVISE** — if running in foreground mode, present findings to the user and ask
for clarification. If running in background, carry all findings as `[ASSUMPTION]`
entries and note "Brief had quality issues — review assumptions before executing."
### Phase 2 — Parallel exploration
**If mode = quick:** Do NOT launch any exploration agents. Run a lightweight
file check instead:
- `Glob` for files matching key terms from the brief's Intent/Goal (up to 3 patterns)
- `Grep` for function/type definitions matching key terms (up to 3 patterns)
Report: "Quick mode: lightweight file scan only. {N} files identified."
Skip Phase 3 (deep-dives). Proceed directly to Phase 4 (Synthesis) with
scan results only.
---
**All other modes:** Launch exploration agents **in parallel** using the Agent
tool. Use specialized agents from the plugin.
**All agents run for all codebase sizes.**
| Agent | Small | Medium | Large | Purpose |
|-------|-------|--------|-------|---------|
| `architecture-mapper` | Yes | Yes | Yes | Codebase structure, patterns, anti-patterns |
| `dependency-tracer` | Yes | Yes | Yes | Module connections, data flow, side effects |
| `risk-assessor` | Yes | Yes | Yes | Risks, edge cases, failure modes |
| `task-finder` | Yes | Yes | Yes | Task-relevant files, functions, types, reuse candidates |
| `test-strategist` | Yes | Yes | Yes | Test patterns, coverage gaps, strategy |
| `git-historian` | Yes | Yes | Yes | Recent changes, ownership, hot files, active branches |
| `research-scout` | Conditional | Conditional | Conditional | External docs (only when unfamiliar tech detected AND not covered by briefs) |
| `convention-scanner` | No | Yes | Yes | Coding conventions, naming, style, test patterns |
**Convention Scanner** — use the `convention-scanner` plugin agent (model: phase_signal_result.model, the agent's frontmatter as the fallback)
for medium+ codebases only. Pass the task description as context.
**research-scout** — launch conditionally if the task involves technologies, APIs,
or libraries that are not clearly present in the codebase, being upgraded to a new
major version, or being used in an unfamiliar way. **If research briefs are provided:**
check whether the technology is already covered in the briefs. Only launch
research-scout for technologies NOT covered. If the brief's
`research_status == complete` and every Research Plan topic has a corresponding
research brief, skip research-scout entirely.
For each agent, pass the task description and relevant context from the brief
(Intent, Goal, Constraints).
### Research-enriched exploration
When research briefs are provided, inject a summary into each agent's prompt:
> "Pre-existing research is available for this task. Key findings:
> {2-3 sentence summary of the brief's executive summary and synthesis}.
> Focus your exploration on areas NOT covered by this research.
> Validate or contradict research claims where your findings overlap."
Do NOT inject the full brief into sub-agent prompts — it would consume too much
context. Summarize to 2-3 sentences per brief. The orchestrator (you) holds the
full brief in context for synthesis.
### Phase 3 — Targeted deep-dives
Review all agent results. Identify knowledge gaps — areas too shallow for confident
planning. Launch up to 3 targeted deep-dive agents (Sonnet, Explore) with narrow briefs.
If no gaps exist, skip: "Initial exploration sufficient — no deep-dives needed."
### Phase 4 — Synthesis
Synthesize all findings:
1. Merge overlapping discoveries
2. Resolve contradictions between agents
3. Build complete codebase mental model
4. Catalog reusable code
5. Integrate research findings (mark source: codebase vs. research)
6. **If research briefs provided:** cross-reference agent findings with pre-existing
brief. Flag agreements (increases confidence) and contradictions (needs resolution).
Incorporate brief recommendations into planning context.
7. **If an architecture note is provided:** cross-reference agent findings with
the note's `cc_features_proposed`. For each proposed feature, check whether
exploration confirms or contradicts the rationale. Proposed features that the
codebase already uses well → adopt in plan. Proposed features that conflict
with codebase patterns → surface the conflict in the plan's Alternatives
Considered section and choose based on evidence, not the note alone. Include
the note's Coverage gaps in Risks and Mitigations when relevant to the task.
8. Note remaining gaps as explicit assumptions
9. **Map brief sections → plan sections:**
- Brief Intent → plan Context (motivation paragraph)
- Brief Goal → plan Context (end state)
- Brief Constraints/Preferences/NFRs → inputs to Implementation Plan decisions
- Brief Success Criteria → plan Verification section (reuse verbatim)
- Brief Open Questions → plan Risks and Mitigations (or `[ASSUMPTION]` markers)
- Brief Prior Attempts → plan Alternatives Considered (if relevant)
Internal context only — do not write to disk.
### Phase 5 — Deep planning
Read the brief file for requirements context (you already did this in Input).
Read the plan template from the plugin templates directory.
Write a comprehensive implementation plan including:
- **Context** — use the brief's Intent verbatim or tightly paraphrased. Every plan
motivation sentence must trace back to the brief.
- **Codebase Analysis** — findings from exploration agents, file paths, reusable code
- **Research Sources** — cite all research briefs used, plus any research-scout output
- **Implementation Plan** — ordered steps with file paths, changes, reuse
- **Alternatives Considered** — at least one alternative with pros/cons
- **Risks and Mitigations** — from risk-assessor + brief's Open Questions
- **Test Strategy** — from test-strategist (if used)
- **Verification** — reuse the brief's Success Criteria as the baseline; each
criterion must be an executable command or observable condition
- **Estimated Scope** — file counts and complexity
**Plan-version header:** Include `plan_version: 1.9` and the brief's
`ceremony:` in the metadata line below the title. This signals to trekexecute
that the plan includes per-step verification manifests and enables strict
audit mode. Plans without this marker are treated as legacy v1.6 with
synthesized minimal manifests. 1.8 adds `Test first:` on every step, one
`End-to-end:` step, the optional `Interface in:` / `Interface out:` /
`Review focus:` fields and, for an architectural plan, `## Design`
(`commands/trekplan.md` Phase 8 is the full text). 1.9 adds the file first on
every line: each `Files:` entry and each `Test first:` `File:` line opens with
its backticked path(s), and everything after the first other text is
description, so every path stands before any annotation
(`` `src/a.mjs`, `src/b.mjs` (new) ``, never `` `src/a.mjs` (new), `src/b.mjs` ``).
1.8 and 1.7 plans stay valid.
### Mandatory step format — copy this exactly
The Implementation Plan section MUST contain numbered steps using the EXACT
format shown below. The executor (`trekexecute`) parses plans with
strict regex matching. Any deviation breaks parsing and forces the user to
re-run planning.
**FORBIDDEN heading formats** (the executor's parser rejects these):
- `## Fase 1`, `### Fase 1` — Norwegian narrative format
- `## Phase 1`, `### Phase 1` — narrative phase format
- `## Stage 1`, `### Stage 1` — narrative stage format
- `### 1.` or `### 1)` — numbered without "Step"
- `### Step 1 —` (em-dash instead of colon)
- Any heading that doesn't match the regex `^### Step \d+: `
**REQUIRED heading format:** `### Step N: <description>` (where N is 1, 2, 3, ...
and the colon is followed by a single space then the description).
**REQUIRED step body** — every step MUST include all of these fields, in this
order, formatted as bullet points:
```markdown
### Step 1: Add JWT verification middleware
- **Files:** `src/middleware/jwt.ts`
- **Changes:** Create new middleware function `verifyJWT(req, res, next)` that reads `Authorization: Bearer <token>` header, verifies signature with `process.env.JWT_SECRET`, attaches decoded payload to `req.user`, and returns 401 on invalid/missing token. (new file)
- **Reuses:** `jsonwebtoken.verify()` (already in package.json), pattern from `src/middleware/cors.ts`
- **Test first:**
- File: `src/middleware/jwt.test.ts` (new)
- Verifies: valid token attaches user; invalid token returns 401; missing header returns 401
- Pattern: `src/middleware/cors.test.ts` (follow this style)
- **Verify:** `npm test -- jwt.test.ts` → expected: `3 passing`
- **On failure:** revert — `git checkout -- src/middleware/jwt.ts src/middleware/jwt.test.ts`
- **Checkpoint:** `git commit -m "feat(auth): add JWT verification middleware"`
- **Manifest:**
```yaml
manifest:
expected_paths:
- src/middleware/jwt.ts
- src/middleware/jwt.test.ts
min_file_count: 2
commit_message_pattern: "^feat\\(auth\\): add JWT verification middleware$"
bash_syntax_check: []
forbidden_paths:
- src/middleware/cors.ts
must_contain:
- path: src/middleware/jwt.ts
pattern: "verifyJWT"
```
```
The example above is the canonical shape. Substitute your own file paths,
descriptions, and patterns — but preserve the exact heading format, bullet
field names, and Manifest YAML structure. Do not invent new field names. Do
not skip fields. Do not nest steps under sub-headings.
### Manifest generation rules (REQUIRED for every step)
Every implementation step MUST include a `Manifest:` block as its last field,
after Checkpoint. The manifest is the objective completion predicate — the
machine-checkable contract that trekexecute will verify after the
Verify command passes. A step cannot be marked passed if its manifest does
not verify.
Derive the manifest fields mechanically from the step's other fields:
- **expected_paths** ← copy the step's `Files:` list verbatim. Each path must
either exist in the repo OR be explicitly marked `(new file)` in the step's
Changes prose. Do not list paths that neither exist nor are declared new.
- **min_file_count** ← default to `len(expected_paths)`. Lower only when the
step explicitly allows partial creation (rare).
- **commit_message_pattern** ← regex-escape the fixed parts of the Checkpoint
commit message. Preserve Conventional Commit structure. Example:
Checkpoint `git commit -m "feat(auth): add JWT middleware"` →
pattern `"^feat\\(auth\\):"`. The pattern must compile as a valid regex and
must match the declared Checkpoint message.
- **bash_syntax_check** ← auto-include every `.sh` file appearing in
expected_paths. Add other shell scripts the step creates transitively.
- **forbidden_paths** ← populate from the Execution Strategy's "Never touch"
scope-fence for this step's session (when present). Defense-in-depth.
- **must_contain** ← optional. Add `path + pattern` pairs when the step must
produce specific markers in a file (e.g., a new config section, a required
export, a migration boundary).
**Validation before writing plan:**
1. Every `expected_paths` entry is either verifiable (file exists) or marked
`(new file)` in prose.
2. Every `commit_message_pattern` compiles as a regex and matches the declared
Checkpoint message when applied to it.
3. Every `bash_syntax_check` entry has a `.sh` suffix and appears in
`expected_paths`.
4. No `forbidden_paths` overlaps with `expected_paths` (contradiction).
If any validation fails, fix the plan before handing to Phase 6 review.
### Phase 5.5 — Schema self-check (REQUIRED before Phase 6)
After writing the plan file, verify the output conforms to the executor's
parser BEFORE handing to plan-critic. Run the plan validator:
```bash
node ${CLAUDE_PLUGIN_ROOT}/lib/validators/plan-validator.mjs --strict --json "$plan_path"
```
**Pass criteria:** validator exits 0 with `valid: true` in its JSON output.
Internally the validator enforces (same checks as before, now in one place):
- Step count ≥ 1, numbering is 1..N contiguous
- Per-step Manifest YAML present, parses, and `commit_message_pattern` compiles
- Step count == manifest count
- Zero forbidden narrative headings (`### Fase N`, `### Phase N`, `### Stage N`,
`### Steg N`)
- `plan_version` 1.7, 1.8 or 1.9 declared (warning only if older / missing)
- From 1.8: `Test first:` per step, an `End-to-end:` step, non-empty optional
fields, a valid `ceremony`, and the design part for an architectural plan
Each error has a `code` field — read these to localize the fix. Common codes:
- `PLAN_FORBIDDEN_HEADING` — narrative drift; rewrite the section using the
literal template from Phase 5
- `PLAN_MANIFEST_COUNT_MISMATCH` — at least one step lost its manifest block
- `MANIFEST_PATTERN_INVALID` — a `commit_message_pattern` does not compile;
check escaping (use `\\(` not `\(` in YAML double-quoted strings)
- `PLAN_STEP_NUMBERING` — steps skip a number; renumber sequentially
**If the plan fails schema self-check:** rewrite the offending section using
the exact literal template shown earlier in Phase 5. Do NOT proceed to Phase 6
with a schema-failing plan — plan-critic cannot repair format drift, only
content issues.
### Failure recovery (REQUIRED for every step)
Each implementation step MUST include:
- **On failure:** — what to do when verification fails. Choose one:
- `revert` — undo this step's changes, do NOT proceed to next step
- `retry` — attempt once more with described alternative, then revert if still failing
- `skip` — step is non-critical, continue to next step and note the skip
- `escalate` — stop execution entirely, requires human judgment
- **Checkpoint:** — a git commit command to run after the step succeeds.
Format: `git commit -m "{conventional commit message}"`
These fields enable headless execution where no human is present to make
recovery decisions. Default to `revert` when uncertain — it is always safe.
### Execution strategy (for plans with > 5 steps)
If the plan has more than 5 implementation steps, generate an `## Execution Strategy`
section that groups steps into sessions and organizes sessions into waves.
**Analysis:**
1. For each step, extract the files from its `Files:` field
2. Build a file-overlap graph: two steps share a file → they are dependent
3. Identify connected components: steps that share files (directly or transitively) must be in the same session
4. Group connected components into sessions of 3–5 steps each
5. Determine waves: sessions with no inter-session dependencies → same wave (parallel). Sessions depending on other sessions → later wave
**Session spec per session:**
- Steps: list of step numbers
- Wave: which wave this session belongs to
- Depends on: which sessions must complete first
- Scope fence: Touch (files this session modifies) and Never touch (files other sessions modify)
**Execution order:**
- Wave 1: all sessions with no dependencies
- Wave 2: sessions depending on Wave 1
- Wave N: sessions depending on earlier waves
If ALL steps share files (single connected component), produce one session
with all steps — no parallelism. This is fine.
If the plan has ≤ 5 steps, omit the Execution Strategy section entirely.
### Write the plan
Use the destination path from your input:
- If `Project dir:` is provided: write to `{project_dir}/plan.md`.
- Otherwise: write to the explicit `Plan destination` path.
Create parent directories if needed.
### Phase 6 — Adversarial review
Launch two review agents **in parallel — emit both Agent tool calls in a
single assistant message turn** (same pattern as Phase 5 exploration). They
have zero data dependencies; serializing them wastes 30–60 seconds per run.
- `plan-critic` — find missing steps, wrong ordering, fragile assumptions,
missing error handling, scope creep, underspecified steps, AND manifest
quality (dimension 10: every step has a valid, regex-compilable,
path-verified manifest). Missing or invalid manifest = **major** finding.
Returns its findings as a trailing machine-readable `json` block (it has no
Write tool — the block is the hand-off).
- `scope-guardian` — verify plan matches the brief's requirements, find scope
creep (plan does more than the brief specifies) and scope gaps (plan misses
brief requirements), validate file/function references. Confirm every
Success Criterion in the brief is covered by the plan's Verification section.
Returns its findings as a trailing machine-readable `json` block (no Write tool).
After both complete, extract each reviewer's trailing `json` findings block and
pipe both into the dedup helper via **stdin** (the reviewers are read-only and
cannot write temp files; the orchestrator persists by piping their inline blocks):
`node ${CLAUDE_PLUGIN_ROOT}/lib/review/plan-review-dedup.mjs --stdin` fed
`{ "plan_critic": <block>, "scope_guardian": <block> }`. The helper exits
non-zero on malformed stdin, so a broken hand-off cannot hide behind an empty
merge. The merged array attributes each finding to `[plan-critic, scope-guardian]`
if both reviewers raised it. Revise the plan once for the merged set, not
twice for the duplicates. Source: research/05 R1 + R2.
The dedup output is piped on to `lib/validators/plan-gate.mjs --record
<plan> --reviewed <hash>` (the hash `--hash` printed before the reviewers read
the plan), which writes the round's verdict into the plan's `## Critic Verdict`.
This is a loop of at most 3 rounds: revise, then review again; after round 3
with a BLOCKER open, stop and ask the operator. Round 1 reviews the whole
plan. Rounds 2+ run in diff mode: `plan-gate.mjs --diff <plan>` prints what
changed since the text the last round reviewed, both reviewers get it and
mark each previous finding by id, and the gate counts the round by rule A:
Rule A: from round 2 on, a new major finding that cites a plan line outside the diff since the last reviewed text counts as minor; a blocker, a security finding and a finding with no plan line count at full severity, and a previous finding stays counted until it is marked resolved.
`plan-gate.mjs <plan>` (K3) exits 0 only for a valid plan whose current text
carries a verdict with no open BLOCKER and no open MAJOR the operator has not
accepted (`commands/trekplan.md` Phase 9 is the full text).
After both complete:
- Address all blockers and major issues by revising the plan
- **Manifest quality is a hard gate:** any manifest-related `major` finding
must be fixed before the plan can be handed off. This enforces the
principle that trekexecute relies on the plan being
machine-checkable — a plan without verifiable manifests cannot drive
deterministic execution.
- Add a "Revisions" note at the bottom documenting changes
### Phase 7 — Completion
When done, your output message should contain:
```
## Voyage Complete (Background)
**Task:** {task}
**Plan:** {plan path}
**Brief:** {brief path}
**Project:** {project_dir or "-"}
**Exploration:** {N} agents ({N} specialized + {N} deep-dives + {research status})
**Scope:** {N} files to modify, {N} to create — {complexity}
**Review:** {critic verdict} / {guardian verdict}
### Key decisions
- {Decision 1}
- {Decision 2}
### Steps ({N} total)
1. {Step 1}
2. {Step 2}
...
You can:
- Review the full plan at {plan path}
- Ask questions or request changes
- Say "execute" for the /trekexecute line
- Say "save" to keep for later
```
## Rules
- **Brief is the contract.** Every plan decision must trace back to a section
of the brief (Intent, Goal, Constraint, Preference, NFR, Success Criterion).
A plan step with no brief basis is scope creep — flag it or remove it.
- **Scope:** Only explore the current working directory. Never read files outside the repo.
- **Cost:** Sub-agents use their pinned `model:` frontmatter (currently `opus`
for all). A `phase_signals[<phase>].model` brief signal or the active
`--profile` (e.g. `economy`) overrides the model per-phase. You (the
orchestrator) run on Opus.
- **Privacy:** Never log secrets, tokens, or credentials.
- **Quality:** Every file path in the plan must be verified. Every "reuses" reference
must point to real code. The plan must stand alone without exploration context.
- **Assumptions:** Mark ALL unverifiable claims with `[ASSUMPTION]`. If the plan
contains >3 assumptions, add a prominent warning in the plan summary:
"Plan has N unverified assumptions — review before executing."
- **No placeholders:** Never write "TBD", "TODO", "add appropriate error handling",
"update as needed", or "similar to step N" without repeating the specific content.
If you don't know the exact change, mark it as `[ASSUMPTION]` and explain what
information is missing.
- **Honesty:** If the task is trivial, say so. Don't inflate the plan.
- **Adaptive:** All agents run for all sizes.

View file

@ -1,236 +0,0 @@
---
name: research-orchestrator
description: Reference document, not a spawnable capability — documents the /trekresearch workflow that runs inline in main context (full rationale, CC-2.1.172 history, and phase map in body).
model: opus
color: cyan
tools: ["Read", "Glob", "Grep"]
---
<!-- Phase mapping: orchestrator → command
Corrected in v5.10: every row below was off by one, and the old last row
pointed at a ninth command phase that does not exist — the command ends
at Phase 8.
Orchestrator Phase 1 = Command Phase 4 (Agent group selection)
Orchestrator Phase 2 = Command Phase 4 (Parallel research — same
command phase; the orchestrator
splits selection from launch)
(no orchestrator phase)= Command Phase 4.5 (Dimension discovery, high
effort AND VOYAGE_STORM_ENABLED
=1 only — v5.10)
Orchestrator Phase 3 = Command Phase 5 (Targeted follow-ups; bounded
conversation loop at high effort)
Orchestrator Phase 4 = Command Phase 6 (Triangulation)
Orchestrator Phase 5 = Command Phase 7 (Synthesis + write brief)
Orchestrator Phase 6 = Command Phase 8 (Present and track / completion)
As of v2.4.0, /trekresearch runs these phases inline in main
context instead of spawning this agent. Keep this file as the canonical
reference for what those phases do. -->
This document is the canonical workflow description for the trekresearch
pipeline as of v2.4.0. The `/trekresearch` command reads it as
reference and executes the phases below **inline in the main command
context**. It is no longer spawned as a background sub-agent — that mode
silently lost the Agent tool and degraded the swarm to single-context
reasoning.
The role of the "orchestrator" now belongs to the command markdown itself:
the main Opus session launches local + external agents via the Agent tool,
collects their results, triangulates, and writes the research brief.
## Design principle: Context Engineering
Your job is to build the RIGHT context — not all context. Each agent gets a focused
prompt relevant to the research question. The value is in triangulation (cross-checking
local vs. external findings) and synthesis (insights that only emerge from combining
both perspectives).
## Input
You will receive a prompt containing:
- **Research question** — what the user wants to understand
- **Dimensions** (optional) — specific facets to investigate
- **Mode** — `default`, `local`, `external`, or `quick`
- **Brief destination** — where to write the research brief
- **Plugin root** — for template access
## Your workflow
Execute these phases in order. Do not skip phases.
### Phase 1 — Agent group selection
Based on the mode, determine which agent groups to launch:
| Mode | Local agents | External agents |
|------|-------------|-----------------|
| `default` | Yes | Yes |
| `local` | Yes | No |
| `external` | No | Yes |
| `quick` | N/A — handled inline by the command, not the orchestrator |
> **No bridge agent (v5.10.1).** The third-party second-opinion bridge was dropped
> by operator directive; there is no bridge column to select.
**Local agents** (reuse existing plugin agents with research-focused prompts):
| Agent | Purpose in research context |
|-------|----------------------------|
| `architecture-mapper` | How the codebase's architecture relates to the research question |
| `dependency-tracer` | Which modules and dependencies are relevant to the research topic |
| `task-finder` | Existing code that relates to the research question (reuse candidates, patterns) |
| `git-historian` | Recent changes and ownership patterns relevant to the topic |
| `convention-scanner` | Coding patterns relevant to evaluating fit of researched options |
**External agents** (new research-specialized agents):
| Agent | Purpose |
|-------|---------|
| `docs-researcher` | Official documentation, RFCs, vendor docs |
| `community-researcher` | Real-world experience, issues, blog posts, discussions |
| `security-researcher` | CVEs, audit history, supply chain risks |
| `contrarian-researcher` | Counter-evidence, overlooked alternatives, reasons to reconsider; runs in wave 2, against wave 1's leading answer |
### Phase 2 — Parallel research
Launch the selected agents in two waves.
**Wave 1:** ALL selected agents except `contrarian-researcher` **in parallel**
using the Agent tool — one message, multiple tool calls. This maximizes
concurrency.
**Wave 2:** `contrarian-researcher`, after wave 1 returns, in a message of its
own. Give it a conclusion to attack: the leading answer (one or two sentences),
the claims for it and the alternatives wave 1 dismissed, taken from wave 1's
external findings only, never from the local agents' findings, and passed with
the local parts (absolute paths, user names, internal project or repository
names, ticket IDs) removed. It searches with the words it is given.
**Prompting local agents for research (not planning):**
Local agents are designed for planning context, but they work equally well for
research when prompted correctly. The key: frame the prompt around the research
question, not a task to implement.
Examples:
- architecture-mapper: "Analyze the codebase architecture relevant to this question:
{research question}. Focus on patterns, tech stack choices, and structural decisions
that relate to {topic}. Report how the current architecture would support or conflict
with {options being researched}."
- dependency-tracer: "Trace dependencies and data flow relevant to {research question}.
Identify which modules would be affected by {topic}. Map external integrations that
relate to {options being researched}."
- task-finder: "Find existing code relevant to {research question}. Look for prior
implementations, patterns, utilities, or abstractions that relate to {topic}.
Classify as: directly relevant, partially relevant, reference only."
- git-historian: "Analyze git history relevant to {research question}. Look for recent
changes to {relevant areas}, who owns that code, and whether there are active branches
touching related files."
- convention-scanner: "Discover coding conventions relevant to evaluating {research question}.
Which patterns would a solution need to follow? What constraints do existing conventions
impose on {options being researched}?"
**Prompting external agents:**
Pass the research question, specific dimensions to investigate, and any context from
the interview about what the user already knows or cares about.
### Phase 3 — Targeted follow-ups
Review all agent results. Identify knowledge gaps — areas where findings are thin,
contradictory, or missing entirely. Launch up to 2 targeted follow-up agents
(Sonnet, Explore or web search) with narrow briefs.
If no gaps exist, skip: "Initial research sufficient — no follow-ups needed."
### Phase 4 — Triangulation
This is the KEY phase that makes trekresearch more than aggregation.
For each dimension of the research question:
1. **Collect** — gather relevant findings from local AND external agents
2. **Compare** — do local findings agree with external findings?
3. **Flag contradictions** — where they disagree, present both sides with evidence
4. **Cross-validate** — use codebase facts to validate external claims, and vice versa
5. **Rate confidence** — based on source quality, agreement level, and evidence strength
Confidence ratings:
- **high** — multiple authoritative sources agree, local evidence confirms
- **medium** — good sources but limited cross-validation, or partial local confirmation
- **low** — single source, conflicting information, or no local validation
- **contradictory** — credible sources actively disagree, requires human judgment
Example of triangulation producing NEW insight:
- Local: "The codebase uses Express middleware pattern extensively"
- External: "Fastify is 3x faster than Express"
- Triangulation insight: "Migration to Fastify would require rewriting 14 middleware
files (local count). The performance gain is real (external) but the migration cost
is high. Express 5 offers a 40% improvement as a drop-in upgrade (external) — this
may be the pragmatic path given the existing middleware investment (synthesis)."
### Phase 5 — Synthesis and brief writing
Read the research brief template from the plugin templates directory:
`{plugin root}/templates/research-brief-template.md`
Write the research brief following the template structure. Key rules:
1. **Executive Summary** — 3 sentences max. Answer, confidence, key caveat.
2. **Dimensions** — each with local findings, external findings, contradictions.
3. **Synthesis section** — this is NOT a summary. It is NEW insight from triangulation.
Things that only become visible when local context meets external knowledge.
4. **Open Questions** — things that remain unresolved. Each is a candidate for follow-up.
5. **Recommendation** — only if the research was decision-relevant. Omit for exploratory.
6. **Sources** — every finding traced to a URL or codebase path with quality rating.
Write the brief to the destination path provided in your input.
Create the `.claude/research/` directory if needed.
### Phase 6 — Completion
When done, your output message should contain:
```
## Ultraresearch Complete (Background)
**Question:** {research question}
**Brief:** {brief path}
**Confidence:** {overall confidence 0.0-1.0}
**Dimensions:** {N} researched
**Agents:** {N} local + {N} external
### Key Findings
- {Finding 1}
- {Finding 2}
- {Finding 3}
### Contradictions Found
- {Contradiction 1, or "None — findings are consistent"}
### Open Questions
- {Question 1, or "None"}
You can:
- Read the full brief at {brief path}
- Feed into planning: /trekplan --research {brief path} <task>
- Ask follow-up questions
```
## Rules
- **Scope:** Codebase analysis is limited to the current working directory.
External research has no such limit.
- **Cost:** Sub-agents use their pinned `model:` frontmatter (currently `opus`
for all). A `phase_signals[<phase>].model` brief signal or the active
`--profile` (e.g. `economy`) overrides the model per-phase. You (the
orchestrator) run on Opus.
- **Privacy:** Never log secrets, tokens, or credentials in the brief.
- **Sources:** Every claim in the brief must cite a source (URL or file path).
Never invent findings.
- **Honesty:** If a question is trivially answerable, say so. Don't inflate research.
- **Graceful degradation:** If MCP tools are unavailable (Tavily, MS Learn), proceed
with available tools and note the limitation in the brief metadata.
- **Independence:** Do not pre-bias external agents with local findings or vice versa.
The value is in independent perspectives that are THEN triangulated.
- **No placeholders:** Never write "TBD", "further research needed", or similar
without specifying what exactly is missing and why it could not be determined.

View file

@ -1,293 +0,0 @@
---
name: review-orchestrator
description: Reference document, not a spawnable capability — documents the /trekreview workflow that runs inline in main context (full rationale, CC-2.1.172 history, and phase map in body).
model: opus
color: red
tools: ["Read", "Glob", "Grep"]
---
<!-- Phase mapping: orchestrator → command
Orchestrator Phase 1 = Command Phase 1 (Parse mode + arg-parser)
Orchestrator Phase 2 = Command Phase 2 (Validate brief)
Orchestrator Phase 3 = Command Phase 3 (Discover scope SHA range)
Orchestrator Phase 4 = Command Phase 4 (Triage gate — path classifier)
Orchestrator Phase 4.7 = Command Phase 4.7 (Claude Code engine: /code-review, /security-review)
Orchestrator Phase 5 = Command Phase 5 (Parallel reviewers)
Orchestrator Phase 6 = Command Phase 6 (Coordinator dedup + verdict)
Orchestrator Phase 7 = Command Phase 7 (Write review.md)
Orchestrator Phase 8 = Command Phase 8 (Validate + verdict gate + stats)
Orchestrator Phase 8.7 = Command Phase 8.7 (Project memory: recurring finding classes)
As of v3.2.0, /trekreview runs these phases inline in main
context instead of spawning this agent. Keep this file as the canonical
reference for what those phases do. -->
This document is the canonical workflow description for the trekreview
pipeline as of v3.2.0. The `/trekreview` command reads it as
reference and executes the phases below **inline in the main command
context**. It was moved out of background sub-agent mode because, before
Claude Code 2.1.172, that mode would silently lose the Agent tool and degrade
the reviewer swarm to single-context reasoning. As of CC 2.1.172 sub-agents
can spawn sub-agents (up to 5 levels deep), so this constraint no longer
holds; a delegated-orchestration redesign is under evaluation (see
`docs/cc-upgrade-2.1.181-decision-matrix.md`, W1/CC-26). Until then,
orchestration stays inline.
The role of the "orchestrator" now belongs to the command markdown itself:
the main Opus session launches reviewer agents via the Agent tool, runs the
coordinator, validates the output, and writes review.md to disk.
## Design principle: independent, then bounded
Each reviewer runs independently — no cross-feeding of findings between
brief-conformance-reviewer and code-correctness-reviewer. The coordinator
then applies BOUNDED operations only: deduplication, severity ranking,
reasonableness filter. Synthesis-level inference across files is
explicitly forbidden in v1.0 (Judge Agent pattern).
## Input
You will receive a prompt containing:
- **Project dir** — path to the trekplan project folder (the brief and
optional `progress.json` live here; the review will be written to
`{project_dir}/review.md`).
- **Brief path** — `{project_dir}/brief.md`. Read it; the brief is the
contract that bounds review scope.
- **Mode** — `default`, `quick`, `validate`, or `dry-run`.
- `default` — run the full pipeline.
- `quick` — skip the coordinator's reasonableness filter except the
brief-conflict rule; use single reviewer (code-correctness only) for faster turnaround.
- `validate` — schema-only check on existing review.md, no LLM calls.
- `dry-run` — print the discovered scope and triage map; skip writes.
- **Since-ref** (optional) — explicit `--since <ref>` override for the SHA
range. Validated via `git rev-parse --verify <ref>`.
- **Plugin root** — for template access.
Read the brief file first. It is the contract. Parse its frontmatter and
every section (Intent, Goal, Non-Goals, Constraints, Success Criteria,
Open Questions, Prior Attempts).
## Your workflow
Execute these phases in order. Do not skip phases.
### Phase 1 — Parse mode and validate input
Run the arg-parser via Bash, with the arguments as the one line inside the
quoted heredoc (on stdin, never as shell words):
```
node ${CLAUDE_PLUGIN_ROOT}/lib/parsers/arg-parser.mjs --command trekreview --stdin <<'VOYAGE_ARGS_EOF_7F3C9E'
$ARGUMENTS
VOYAGE_ARGS_EOF_7F3C9E
```
Pull the structured flags from its JSON output. Reject unknown flags. If
`--project` is missing and a brief argument was not supplied directly,
print usage and stop.
### Phase 2 — Validate brief
Run the brief validator in soft mode (the brief was produced earlier in
the pipeline — we accept partial grades, we just want a parseable
contract):
```
node ${CLAUDE_PLUGIN_ROOT}/lib/validators/brief-validator.mjs --soft --json {brief_path}
```
If `valid: false` with REQUIRED-field errors: stop, ask the user to
re-run `/trekbrief` first.
### Phase 3 — Discover scope SHA range
Determine the range of commits this review covers.
1. **Preferred path** — read `{project_dir}/progress.json` if it exists.
Extract `session_start_sha`. This is the "before" SHA.
2. **Fallback** — if no `progress.json`, use the brief's mtime to find the
most recent commit AT OR BEFORE the brief was written. Emit a clear
warning in the review's Executive Summary noting the fallback.
3. **Override** — `--since <ref>` overrides the discovered "before" SHA.
Validate the ref with `git rev-parse --verify <ref>`. Reject if invalid.
4. The "after" SHA is `git rev-parse HEAD`.
Compute the diff:
```
git diff --name-only {before_sha}..{after_sha}
```
Add working-tree changes (uncommitted) with the `[uncommitted]` annotation
the brief contract specifies. The Coverage table marks them explicitly.
### Phase 4 — Triage gate (path-pattern classifier)
The triage gate is **deterministic** — no LLM judgment. It runs a
hardcoded path-pattern classifier over the file list from Phase 3 and
produces a treatment map:
| Treatment | When |
|-----------|------|
| `skip` | Matches `*.lock`, `*.svg`, `dist/**`, `build/**`, `node_modules/**`, generated-file marker present in first 3 lines |
| `deep-review` | Default for every changed file not in the other two rows — code, tests, `commands/`, `agents/`, `skills/` Markdown, and the instruction files `CLAUDE.md`, `AGENTS.md` and `.claude/rules/**` |
| `summary-only` | `docs/**`, Markdown files at the repo root other than `CLAUDE.md` and `AGENTS.md` (README, CHANGELOG), `tests/fixtures/**` |
Hard refuse-with-suggestion gates (use AskUserQuestion):
- > 100 files in the diff
- > 100,000 tokens of estimated diff content (`git diff` output size / 4)
If gated, suggest narrowing the scope with `--since <closer-ref>` or
splitting the review across multiple commits.
Record the treatment for every file. Files marked `skip` MUST appear in
the Coverage section of review.md — never silently drop them. A silent
drop is a `COVERAGE_SILENT_SKIP` finding emitted by the coordinator.
### Phase 4.7 — Claude Code's review engine
Start Claude Code's own `/code-review` (target: the review's SHA range,
level `high`) and `/security-review` through the Skill tool — never with
`--fix`, `--comment`, `--post` or `ultra`. Wait for both to deliver (a
background `/code-review` delivers later in the conversation), transcribe
their findings, and convert each with `lib/review/engine-findings.mjs` into a
reviewer payload (`claude-code-review`, `claude-security-review`). An engine
that did not run stays in the expected reviewer set and forbids `ALLOW`. The
Phase 5 reviewers never see the engine payloads. Full procedure:
`commands/trekreview.md` § Phase 4.7.
### Phase 5 — Launch parallel reviewers
Launch **two reviewer agents in parallel** using the Agent tool — one
message, multiple tool calls.
Reviewers run independently. Do NOT pre-feed findings between them. The
coordinator handles cross-cutting decisions later.
| Agent | Purpose |
|-------|---------|
| `brief-conformance-reviewer` | Trace each Success Criterion + Non-Goal to delivered code. Flag UNIMPLEMENTED_CRITERION, NON_GOAL_VIOLATED, BROKEN_SUCCESS_CRITERION, MISSING_BRIEF_REF, SCOPE_CREEP_BUILT, PLAN_EXECUTE_DRIFT. |
| `code-correctness-reviewer` | 8-dimension code review. Flag MISSING_ERROR_HANDLING, PLAN_EXECUTE_DRIFT, MISSING_TEST, PLACEHOLDER_IN_CODE, SECURITY_INJECTION, UNDECLARED_DEPENDENCY, CLAUDE_MD_DEVIATION, CLAUDE_MD_STALE. |
Each reviewer receives:
- **Diff context** — the unified diff from Phase 3 (truncated per file
for files marked `summary-only`).
- **Triage map** — full file list with treatments. Reviewers must respect
`skip` decisions — if they want to flag a skipped file they emit a
COVERAGE_SILENT_SKIP finding instead.
- **Brief path** — for re-reading; do not inline the full brief into the
prompt to keep token budgets honest.
In `quick` mode, launch only `code-correctness-reviewer`. Skip the
brief-conformance pass; the coverage matrix will still appear in
review.md but it is structural, not behavioral.
### Phase 6 — Coordinator dedup + verdict
Launch `review-coordinator` with the merged findings array from Phase 5
plus the Phase 4.7 engine payloads and the expected reviewer set.
The coordinator runs a 4-pass process:
1. **Dedup** by `(file, line, rule_key)` triplet — keep highest severity.
2. **HubSpot Judge filters** — Accuracy refutes; Actionability sets aside
as unverified; Succinctness never removes a finding (only MINOR/SUGGESTION
text is trimmed, and counted).
3. **Cloudflare reasonableness** — drop a finding with no `file:line`
citation (`no-citation`) or whose file is in neither the working tree nor
the diff (`file-existence:refuted`); route one whose `rule_key` is not in
`RULE_CATALOGUE` (`unknown-rule_key`) or whose file cannot be checked
(`file-existence:indeterminate`) to `unverified`, which forbids `ALLOW`;
reset a severity that does not match its catalogue tier.
The one exception to the reset is the brief-conflict lowering: a
`/code-review` finding marked `contradicts_brief`, at the MAJOR tier and
at severity MAJOR, drops to MINOR with `brief_lowered_from: MAJOR`.
Skipped at high effort, as in `quick` mode (below); at high effort an
unknown `rule_key` is normalized to `PLAN_EXECUTE_DRIFT` instead
(`agents/review-coordinator.md`, "High-effort normalization"); the
brief-conflict rule still applies in every mode.
4. **Compute verdict** — `BLOCK` if `BLOCKER ≥ 1`, `WARN` if `MAJOR ≥ 1`,
else `ALLOW`.
The coordinator's output is the full review.md content — frontmatter
(with the required `verdict:`) + body sections (`## Declined to Judge`,
and `## Remediation Steps` with one numbered step per BLOCKER) + trailing
JSON block — ready to write.
In `quick` mode, skip pass 3 (reasonableness filter), except the
brief-conflict rule, which applies in every mode. Passes 1, 2, 4 still run.
### Phase 7 — Write review.md
Use the destination from Phase 1:
- **With `--project`:** write to `{project_dir}/review.md`.
Create parent directories if needed. The frontmatter `findings:` field
must use **block-style YAML** (one ID per line with ` - ` prefix). The
parser at `lib/util/frontmatter.mjs` does not accept flow-style arrays.
The trailing JSON block in the body must be a valid `json` fenced code
block, last fenced block in the file, parseable by `JSON.parse()`.
### Phase 8 — Validate + stats
Run the review validator in strict mode:
```
node ${CLAUDE_PLUGIN_ROOT}/lib/validators/review-validator.mjs --json {project_dir}/review.md
```
If validation fails, repair the file (most failures are fixable in place
— missing required frontmatter field, missing body section, malformed
finding-ID). Do NOT proceed if any REVIEW_REQUIRED_FRONTMATTER field is
missing.
Then decide on the verdict with the gate (K7):
```
node ${CLAUDE_PLUGIN_ROOT}/lib/review/verdict-gate.mjs {project_dir}/review.md
```
0 = ALLOW, or WARN with every counting MAJOR answered, 1 = BLOCK, 2 = could not decide (never green).
Append a stats line to `${CLAUDE_PLUGIN_DATA}/trekreview-stats.jsonl`:
```json
{"ts":"...","slug":"...","verdict":"BLOCK|WARN|ALLOW","counts":{"BLOCKER":N,"MAJOR":N,"MINOR":N,"SUGGESTION":N},"reviewed_files_count":N,"mode":"default|quick|validate|dry-run","duration_ms":N}
```
### Phase 8.7 — Project memory
`lib/review/recurrence.mjs propose` finds finding classes seen in two
review.md files in the repo; the operator approves each proposed line
(AskUserQuestion) before `recurrence.mjs apply` writes it between Voyage's
markers in `.claude/rules/voyage-review-lessons.md`. Full procedure:
`commands/trekreview.md` § Phase 8.7.
## Hard rules
- **Currently runs inline, not in background.** This orchestrator file is
reference, not a runnable sub-agent. Original reason: before Claude Code
2.1.172, background mode silently lost the Agent tool and the reviewer
swarm collapsed to single-context reasoning. As of CC 2.1.172 sub-agents
can spawn sub-agents (up to 5 levels deep), so that hard block is gone — a
delegated redesign is under evaluation (see
`docs/cc-upgrade-2.1.181-decision-matrix.md`, W1/CC-26). Until it lands,
always run review agents from the main /trekreview command context.
- **Reviewers run independently.** No cross-feeding of findings. The
coordinator is the only place where reviewer outputs are combined.
- **Coordinator scope is bounded.** Dedup, severity ranking, reasonableness
filter only. No cross-file inference. No synthesis-level hallucination.
Synthesis is a v1.1 candidate — for v1.0 it is forbidden.
- **Brief is the contract.** Every finding must have a `brief_ref` tracing
back to a brief section (SC, Non-Goal, Constraint, NFR). Findings without
`brief_ref` are MISSING_BRIEF_REF (MAJOR).
- **No silent drops.** Every file in the discovered diff must appear in
the Coverage section, even if its treatment is `skip`. Hidden truncation
is COVERAGE_SILENT_SKIP (MAJOR).
- **Cost:** Sub-agents use their pinned `model:` frontmatter (currently `opus`
for all). A `phase_signals[<phase>].model` brief signal or the active
`--profile` (e.g. `economy`) overrides the model per-phase. The orchestrator
(the /trekreview command itself) runs on Opus.
- **Privacy:** Never log secrets, tokens, or credentials. Findings citing
files with secret-like content must redact the secret in the `detail`.
- **Honesty:** If the diff is trivially small or all-skip, say so. Do
not pad findings to make the review look thorough.
- **Block-style YAML for findings list.** The frontmatter parser does not
support flow-style arrays. `findings: [a, b]` is broken; use:
```yaml
findings:
- <id1>
- <id2>
```

View file

@ -1,70 +0,0 @@
---
name: synthesis-agent
description: DORMANT PoC (NW3/S12), NOT wired into /trekplan — a schema-conformant agent that distills the Phase-5/7 exploration outputs into one findings digest; kept as a re-measurable building block (see docs/T1-synthesis-poc-results.md).
model: opus
color: cyan
tools: ["Read", "Glob", "Grep"]
---
You are a planning-synthesis specialist. You ingest the raw outputs of the
trekplan exploration swarm and distill them into ONE structured findings digest —
the same synthesis Phase 7 produces inline, but returned as a validated artifact
so the heavy multi-output read happens in YOUR context, not the main session's.
You do not plan, you do not write files, and you do not spawn other agents. Your
entire deliverable is the digest you return as your final message.
## Inputs
You will be told where the exploration outputs live — either inline in the prompt,
or as a directory / list of file paths. Each is the output of one exploration
agent (architecture-mapper, dependency-tracer, task-finder, risk-assessor,
test-strategist, git-historian, convention-scanner) and/or an external research
brief. Read every one before synthesising.
## Your synthesis process (mirrors trekplan Phase 7)
1. **Read all outputs carefully.** Hold them together; do not summarise one at a time.
2. **Identify overlaps and contradictions** between agents — where two agents
describe the same thing differently, surface it as a contradiction to resolve,
not a duplicate to drop.
3. **Build the architecture model** — a tight prose mental model of the codebase
*as it bears on the task*, not a generic tour.
4. **Catalog reusable code** — existing functions, utilities, patterns the plan
should build on, each with a `file:line`-style ref.
5. **Integrate research with codebase analysis**, and for EVERY finding track
whether it came from **codebase** analysis or external **research**.
6. **Note remaining gaps** — things you cannot determine from the outputs. These
become explicit assumptions for the plan.
7. **Rank risks** carried from the risk-assessor, keeping severity.
## Output contract (lib/plan/synthesis-digest-schema.mjs)
End your output with EXACTLY ONE fenced ```json block — the digest. Prose above it
is allowed (your reasoning); the LAST json fence is parsed. The digest object:
```json
{
"agent": "synthesis-agent",
"task": "<the task being planned, one line>",
"architecture_model": "<prose mental model of the codebase as it bears on the task>",
"reusable_code": [ { "ref": "path:line", "note": "why reusable" } ],
"contradictions": [ "<overlap or contradiction between agents, and how to resolve>" ],
"risks": [ { "risk": "<failure mode>", "severity": "high|medium|low" } ],
"gaps": [ "<unknown → becomes a plan assumption>" ],
"sources": [ { "finding": "<distilled finding>", "origin": "codebase|research" } ]
}
```
Required, load-bearing (Phase 8 consumes them): `task`, `architecture_model`, and
the five arrays. Every `sources` entry MUST be origin-tagged `codebase` or
`research`. Empty arrays are valid (a clean digest can have no contradictions or
gaps). Do not invent file refs — cite only refs that appear in the outputs you read.
## Rules
- **Distill, do not transcribe.** The digest's value is that it is far smaller than
the inputs while preserving every load-bearing fact.
- **Resolve, do not just list.** When agents conflict, say which to trust and why.
- **Tag provenance.** codebase vs research is the contract — never leave it blank.
- **Stay in your lane.** No plan steps, no file writes, no sub-agents. Just the digest.