@bonesofspring/ai-rules 0.2.12 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +1 -1
  3. package/presets/_shared/core/agent-team/agent-artifact-contracts.md +114 -0
  4. package/presets/_shared/core/agent-team/agent-team-orchestrator.md +64 -5
  5. package/presets/claude/go/agents/build-verifier.md +9 -2
  6. package/presets/claude/go/agents/code-reviewer.md +8 -1
  7. package/presets/claude/go/agents/feature-developer.md +8 -1
  8. package/presets/claude/go/agents/task-analyst.md +8 -1
  9. package/presets/claude/go/agents/task-router.md +33 -5
  10. package/presets/claude/go/commands/task.md +8 -6
  11. package/presets/claude/go/hooks/chain-team-phases.sh +195 -53
  12. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +30 -5
  13. package/presets/claude/go/team/README.md +13 -2
  14. package/presets/claude/ios-swift/agents/build-verifier.md +8 -1
  15. package/presets/claude/ios-swift/agents/code-reviewer.md +9 -14
  16. package/presets/claude/ios-swift/agents/feature-developer.md +8 -1
  17. package/presets/claude/ios-swift/agents/task-analyst.md +8 -1
  18. package/presets/claude/ios-swift/agents/task-router.md +31 -3
  19. package/presets/claude/ios-swift/commands/task.md +8 -6
  20. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +177 -54
  21. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +33 -2
  22. package/presets/claude/ios-swift/team/README.md +13 -2
  23. package/presets/claude/java/agents/build-verifier.md +8 -1
  24. package/presets/claude/java/agents/code-reviewer.md +8 -1
  25. package/presets/claude/java/agents/feature-developer.md +8 -1
  26. package/presets/claude/java/agents/task-analyst.md +8 -1
  27. package/presets/claude/java/agents/task-router.md +31 -3
  28. package/presets/claude/java/commands/task.md +8 -6
  29. package/presets/claude/java/hooks/chain-team-phases.sh +195 -53
  30. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +30 -5
  31. package/presets/claude/java/team/README.md +13 -2
  32. package/presets/claude/mcp-ts/agents/build-verifier.md +9 -2
  33. package/presets/claude/mcp-ts/agents/feature-developer.md +7 -1
  34. package/presets/claude/mcp-ts/agents/task-analyst.md +8 -1
  35. package/presets/claude/mcp-ts/agents/task-router.md +33 -5
  36. package/presets/claude/mcp-ts/commands/task.md +8 -6
  37. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +181 -39
  38. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +30 -5
  39. package/presets/claude/mcp-ts/team/README.md +13 -2
  40. package/presets/claude/next/agents/accessibility-reviewer.md +6 -12
  41. package/presets/claude/next/agents/api-contract-reviewer.md +6 -12
  42. package/presets/claude/next/agents/build-verifier.md +8 -12
  43. package/presets/claude/next/agents/ci-investigator.md +7 -13
  44. package/presets/claude/next/agents/code-reviewer.md +9 -14
  45. package/presets/claude/next/agents/debugger.md +6 -12
  46. package/presets/claude/next/agents/feature-developer.md +8 -1
  47. package/presets/claude/next/agents/migration-specialist.md +6 -12
  48. package/presets/claude/next/agents/performance-auditor.md +5 -11
  49. package/presets/claude/next/agents/qa-tester.md +6 -12
  50. package/presets/claude/next/agents/security-reviewer.md +6 -12
  51. package/presets/claude/next/agents/solution-architect.md +6 -12
  52. package/presets/claude/next/agents/task-analyst.md +10 -16
  53. package/presets/claude/next/agents/task-router.md +31 -3
  54. package/presets/claude/next/agents/tech-writer.md +6 -13
  55. package/presets/claude/next/agents/unit-test-generator.md +6 -10
  56. package/presets/claude/next/agents/unit-test-healer.md +6 -10
  57. package/presets/claude/next/agents/unit-test-planner.md +5 -11
  58. package/presets/claude/next/commands/task.md +8 -6
  59. package/presets/claude/next/hooks/chain-team-phases.sh +197 -54
  60. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +29 -4
  61. package/presets/claude/next/team/README.md +15 -3
  62. package/presets/claude/next/team/fixtures/artifact-manifest.example.json +61 -0
  63. package/presets/claude/next/team/fixtures/bugfix-standard.json +10 -0
  64. package/presets/claude/next/team/fixtures/feature-full.json +10 -0
  65. package/presets/claude/next/team/fixtures/feature-light.json +10 -0
  66. package/presets/claude/php-hexagonal/agents/build-verifier.md +9 -2
  67. package/presets/claude/php-hexagonal/agents/code-reviewer.md +8 -1
  68. package/presets/claude/php-hexagonal/agents/feature-developer.md +8 -1
  69. package/presets/claude/php-hexagonal/agents/task-analyst.md +8 -1
  70. package/presets/claude/php-hexagonal/agents/task-router.md +31 -3
  71. package/presets/claude/php-hexagonal/commands/task.md +8 -6
  72. package/presets/claude/php-hexagonal/hooks/README.md +1 -1
  73. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +195 -53
  74. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +30 -5
  75. package/presets/claude/php-hexagonal/team/README.md +13 -2
  76. package/presets/claude/php-laravel/agents/build-verifier.md +9 -2
  77. package/presets/claude/php-laravel/agents/code-reviewer.md +8 -1
  78. package/presets/claude/php-laravel/agents/feature-developer.md +8 -1
  79. package/presets/claude/php-laravel/agents/task-analyst.md +8 -1
  80. package/presets/claude/php-laravel/agents/task-router.md +31 -3
  81. package/presets/claude/php-laravel/commands/task.md +8 -6
  82. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +195 -53
  83. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +30 -5
  84. package/presets/claude/php-laravel/team/README.md +13 -2
  85. package/presets/cursor/go/agents/build-verifier.md +8 -1
  86. package/presets/cursor/go/agents/code-reviewer.md +8 -1
  87. package/presets/cursor/go/agents/feature-developer.md +8 -1
  88. package/presets/cursor/go/agents/task-analyst.md +8 -1
  89. package/presets/cursor/go/agents/task-router.md +31 -3
  90. package/presets/cursor/go/commands/task.md +8 -6
  91. package/presets/cursor/go/hooks/chain-team-phases.sh +195 -53
  92. package/presets/cursor/go/rules/agent-team-orchestrator.mdc +30 -5
  93. package/presets/cursor/go/team/README.md +13 -2
  94. package/presets/cursor/ios-swift/agents/build-verifier.md +8 -1
  95. package/presets/cursor/ios-swift/agents/code-reviewer.md +9 -14
  96. package/presets/cursor/ios-swift/agents/feature-developer.md +8 -1
  97. package/presets/cursor/ios-swift/agents/task-analyst.md +8 -1
  98. package/presets/cursor/ios-swift/agents/task-router.md +31 -3
  99. package/presets/cursor/ios-swift/commands/task.md +8 -6
  100. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +195 -54
  101. package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +23 -2
  102. package/presets/cursor/ios-swift/team/README.md +13 -2
  103. package/presets/cursor/java/agents/build-verifier.md +8 -1
  104. package/presets/cursor/java/agents/code-reviewer.md +8 -1
  105. package/presets/cursor/java/agents/feature-developer.md +8 -1
  106. package/presets/cursor/java/agents/task-analyst.md +8 -1
  107. package/presets/cursor/java/agents/task-router.md +31 -3
  108. package/presets/cursor/java/commands/task.md +8 -6
  109. package/presets/cursor/java/hooks/chain-team-phases.sh +195 -53
  110. package/presets/cursor/java/rules/agent-team-orchestrator.mdc +30 -5
  111. package/presets/cursor/java/team/README.md +13 -2
  112. package/presets/cursor/mcp-ts/agents/build-verifier.md +8 -1
  113. package/presets/cursor/mcp-ts/agents/feature-developer.md +7 -1
  114. package/presets/cursor/mcp-ts/agents/task-analyst.md +8 -1
  115. package/presets/cursor/mcp-ts/agents/task-router.md +31 -3
  116. package/presets/cursor/mcp-ts/commands/task.md +8 -6
  117. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +181 -39
  118. package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +30 -5
  119. package/presets/cursor/mcp-ts/team/README.md +13 -2
  120. package/presets/cursor/next/agents/accessibility-reviewer.md +7 -14
  121. package/presets/cursor/next/agents/api-contract-reviewer.md +7 -14
  122. package/presets/cursor/next/agents/build-verifier.md +8 -13
  123. package/presets/cursor/next/agents/ci-investigator.md +7 -14
  124. package/presets/cursor/next/agents/code-reviewer.md +9 -14
  125. package/presets/cursor/next/agents/debugger.md +6 -12
  126. package/presets/cursor/next/agents/feature-developer.md +8 -1
  127. package/presets/cursor/next/agents/migration-specialist.md +7 -14
  128. package/presets/cursor/next/agents/performance-auditor.md +6 -13
  129. package/presets/cursor/next/agents/qa-tester.md +6 -13
  130. package/presets/cursor/next/agents/security-reviewer.md +7 -14
  131. package/presets/cursor/next/agents/solution-architect.md +6 -12
  132. package/presets/cursor/next/agents/task-analyst.md +10 -16
  133. package/presets/cursor/next/agents/task-router.md +31 -3
  134. package/presets/cursor/next/agents/tech-writer.md +6 -13
  135. package/presets/cursor/next/agents/unit-test-generator.md +6 -11
  136. package/presets/cursor/next/agents/unit-test-healer.md +6 -11
  137. package/presets/cursor/next/agents/unit-test-planner.md +6 -13
  138. package/presets/cursor/next/commands/task.md +8 -6
  139. package/presets/cursor/next/hooks/chain-team-phases.sh +197 -54
  140. package/presets/cursor/next/rules/agent-team-orchestrator.mdc +30 -5
  141. package/presets/cursor/next/team/README.md +16 -4
  142. package/presets/cursor/next/team/fixtures/artifact-manifest.example.json +61 -0
  143. package/presets/cursor/next/team/fixtures/bugfix-standard.json +10 -0
  144. package/presets/cursor/next/team/fixtures/feature-full.json +10 -0
  145. package/presets/cursor/next/team/fixtures/feature-light.json +10 -0
  146. package/presets/cursor/php-hexagonal/agents/build-verifier.md +8 -1
  147. package/presets/cursor/php-hexagonal/agents/code-reviewer.md +8 -1
  148. package/presets/cursor/php-hexagonal/agents/feature-developer.md +8 -1
  149. package/presets/cursor/php-hexagonal/agents/task-analyst.md +8 -1
  150. package/presets/cursor/php-hexagonal/agents/task-router.md +31 -3
  151. package/presets/cursor/php-hexagonal/commands/task.md +8 -6
  152. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +195 -53
  153. package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +30 -5
  154. package/presets/cursor/php-hexagonal/team/README.md +13 -2
  155. package/presets/cursor/php-laravel/agents/build-verifier.md +8 -1
  156. package/presets/cursor/php-laravel/agents/code-reviewer.md +8 -1
  157. package/presets/cursor/php-laravel/agents/feature-developer.md +8 -1
  158. package/presets/cursor/php-laravel/agents/task-analyst.md +8 -1
  159. package/presets/cursor/php-laravel/agents/task-router.md +31 -3
  160. package/presets/cursor/php-laravel/commands/task.md +8 -6
  161. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +195 -53
  162. package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +30 -5
  163. package/presets/cursor/php-laravel/team/README.md +13 -2
@@ -44,4 +44,10 @@ Implement MCP server features following **mcp-ts** boundaries.
44
44
 
45
45
  - Load `design-guidance` and `anti-sycophancy-discipline` when writing or changing code.
46
46
 
47
- Update `.cursor/team/tasks/<slug>/status.json` when done.
47
+
48
+ ## Artifact contract
49
+
50
+ - **Authoritative inputs:** read `.cursor/team/tasks/<slug>/artifact-manifest.json` first; consume handoff `artifactInputIds` when supplied, otherwise consume the manifest entries for `brief.md`, `decomposition.md`, current scope, and applicable prior findings.
51
+ - **Owned outputs:** `implementation.md` plus changed implementation/test paths; upsert only the manifest entry assigned by handoff (`artifactOutputId`; fallback `implementation`) and preserve all foreign entries.
52
+ - **Terminal receipt:** cover applicable AC/task IDs, list authoritative evidence paths, and emit `completed` or `blocked`. Bind it to the supplied `attemptId` when present.
53
+ - **Shared state:** never create or mutate `status.json` or `metrics.json`; the orchestration runtime/hook owns lifecycle, gates, retries, attempts, and timestamps.
@@ -10,7 +10,7 @@ Analyze MCP server work requests for the **mcp-ts** preset.
10
10
 
11
11
  1. `brief.md` — goal, AC, out of scope, assumptions, risks.
12
12
  2. `decomposition.md` — ordered tasks (contract → schema → handler → register → test → package).
13
- 3. Update `status.json` (`awaiting_approval` when human gate applies).
13
+ 3. Emit the analysis receipt; the runtime applies any configured human gate.
14
14
 
15
15
  ## Focus
16
16
 
@@ -23,3 +23,10 @@ Analyze MCP server work requests for the **mcp-ts** preset.
23
23
  - Implement production code.
24
24
  - Schedule Phase 2-only agents.
25
25
  - Prescribe Go hexagonal or Next app layers.
26
+
27
+ ## Artifact contract
28
+
29
+ - **Authoritative inputs:** read `.cursor/team/tasks/<slug>/artifact-manifest.json` first; consume `pipeline.json`, the manifest routing entry, user-approved decisions, and any authoritative architecture/approval entries.
30
+ - **Owned outputs:** `brief.md` and `decomposition.md`; upsert only the manifest entry assigned by handoff (`artifactOutputId`; fallback `analysis`) and preserve all foreign entries.
31
+ - **Terminal receipt:** cover applicable AC/task IDs, list authoritative evidence paths, and emit `completed` or `blocked`. Bind it to the supplied `attemptId` when present.
32
+ - **Shared state:** never create or mutate `status.json` or `metrics.json`; the orchestration runtime/hook owns lifecycle, gates, retries, attempts, and timestamps.
@@ -46,6 +46,27 @@ Append **`security-reviewer` after `build-verifier`** for `feature` / `bugfix` /
46
46
 
47
47
  **Never skip `build-verifier`** after developer when TypeScript sources changed.
48
48
 
49
+ ## Routing decision rubric
50
+
51
+ Keep top-level `profile` and emit this top-level object in every new `pipeline.json`:
52
+
53
+ ```json
54
+ "routingDecision": {
55
+ "complexity": "low | moderate | high",
56
+ "riskFlags": [],
57
+ "routingReasons": ["Concrete request signal and its routing consequence."],
58
+ "estimatedWorkPackages": 1,
59
+ "openDecisionCount": 0
60
+ }
61
+ ```
62
+
63
+ - `low`: one bounded schema/handler scope, explicit AC, reversible, no FS/network/auth expansion or open decisions → `light`.
64
+ - `moderate`: adjacent concerns or a regression/refactor with known boundaries → usually `standard`.
65
+ - `high`: public tool contract, FS/network/auth capability expansion, migration/destructive or concurrency/state risk, broad test surface, unclear AC, or multiple work packages → usually `full`.
66
+ - Use concrete flags: `public-contract`, `cross-layer`, `security-sensitive`, `migration`, `destructive`, `concurrency-state`, `external-dependency`, `unclear-acceptance-criteria`, `broad-test-surface`, `behavior-regression`.
67
+ - `routingReasons` must be non-empty and explain profile, gates, specialists, skips, or checkpoints; never write “standard by default.”
68
+ - `estimatedWorkPackages` is an integer ≥1; `openDecisionCount` is an integer ≥0. Do not lower complexity because implementation is familiar.
69
+
49
70
  ## Model tiers (`steps[].model`)
50
71
 
51
72
  Optional: `"model": "cheap" | "standard" | "strong"`.
@@ -66,12 +87,19 @@ Fixtures: `.cursor/team/fixtures/` (feature-full, feature-light, bugfix-standard
66
87
 
67
88
  ## Output
68
89
 
69
- Write `.cursor/team/tasks/<slug>/pipeline.json` and initial `status.json` via the **Write** tool; set `.cursor/team/active-task.json`.
90
+ Write `.cursor/team/tasks/<slug>/pipeline.json` and initialize the routing entry in `artifact-manifest.json`; set `.cursor/team/active-task.json`. The orchestration runtime creates and owns `status.json`.
70
91
 
71
92
  ## Handoff
72
93
 
73
94
  Intent + steps table + skipped + gates → invoke `steps[0].agent` (unless retro).
74
95
 
75
- ## Metrics initialization
96
+ ## Runtime initialization
97
+
98
+ Return the routing receipt to the orchestrator. The orchestration runtime/hook exclusively initializes and updates `status.json`, `metrics.json`, attempt identities, and gate lifecycle; the router does not write those shared runtime files.
99
+
100
+ ## Artifact contract
76
101
 
77
- Alongside `pipeline.json` and `status.json`, create `metrics.json` with `schemaVersion: 1`, immutable task dimensions, `task_started`, and a generated `runId`. Before the parent invokes each agent, append `attempt_started` and set `status.activeAttempts[attemptId]` with agent, step index, attempt number, and host-clock `startedAt`. For parallel work create one entry per agent; do not use `currentAgent` to identify their completion.
102
+ - **Authoritative inputs:** read `.cursor/team/tasks/<slug>/artifact-manifest.json` first; consume the user request and any existing authoritative task/decision entries.
103
+ - **Owned outputs:** `pipeline.json` and the routing manifest entry; upsert only the manifest entry assigned by handoff (`artifactOutputId`; fallback `routing`) and preserve all foreign entries.
104
+ - **Terminal receipt:** cover applicable AC/task IDs, list authoritative evidence paths, and emit `completed` or `blocked`. Bind it to the supplied `attemptId` when present.
105
+ - **Shared state:** never create or mutate `status.json` or `metrics.json`; the orchestration runtime/hook owns lifecycle, gates, retries, attempts, and timestamps.
@@ -24,14 +24,16 @@ description: Route a natural-language task through the agent-team pipeline: task
24
24
 
25
25
  ## Алгоритм
26
26
 
27
- 1. **Slug** — kebab-case из описания (≤48 символов). Создай `.cursor/team/tasks/<slug>/` через **Write** (например сразу `status.json` или пустой placeholder) — **не** через Shell `mkdir` (песочница → `Operation not permitted`).
27
+ 1. **Slug** — kebab-case из описания (≤48 символов). Создай `.cursor/team/tasks/<slug>/` через **Write** (например placeholder `pipeline.json` или пустой marker) — runtime/hook владеет `status.json` — **не** через Shell `mkdir` (песочница → `Operation not permitted`).
28
28
  2. **Router** — вызови subagent **task-router** с описанием задачи и путём к slug.
29
29
  3. **План** — покажи пользователю таблицу из `pipeline.json`: intent, steps, skipped, humanGates.
30
30
  4. **Intent retro** — если `intent === "retro"`, выполни `/technical-retro` и **остановись**.
31
- 5. **Старт** — вызови subagent для `pipeline.steps[0].agent`:
32
- - передай slug, пути к артефактам, scope из step (если есть);
33
- - обнови `status.json`: `pipelineIndex: 0`, `currentAgent`, `state: in_progress`.
34
- 6. **Human gate** если после текущего шага есть gate в `humanGates` (`after:<agent>`), после завершения агента **остановись** и попроси `/task-continue <slug>` (или `/feature-continue <slug>`).
31
+ 5. **Старт** — после router:
32
+ - подтверди `pipeline.json` и `active-task.json`;
33
+ - **не** пиши lifecycle-поля `status.json` / `metrics.json` сам — их владеет orchestration runtime/hook (см. **agent-artifact-contracts**). Если `status.json` отсутствует, допустим только минимальный bootstrap (`slug`, `intent`, `pipelineIndex: 0`, `currentAgent: steps[0]`, `state: in_progress`) — **не** увеличивай `pipelineIndex` вручную;
34
+ - вызови subagent для `pipeline.steps[0].agent` (slug, пути к артефактам, scope).
35
+ 6. **После каждого агента** — дождись hook handoff / reconciliation terminal receipt → `status.state`; не запускай следующий шаг, пока `status.json` не отражает handoff (или пока нет `followup_message` от hook).
36
+ 7. **Human gate** — если после текущего шага есть gate в `humanGates` (`after:<agent>`), после завершения агента **остановись** и попроси `/task-continue <slug>` (или `/feature-continue <slug>`).
35
37
 
36
38
  ## Не делать
37
39
 
@@ -50,4 +52,4 @@ description: Route a natural-language task through the agent-team pipeline: task
50
52
 
51
53
  ## Metrics
52
54
 
53
- Initialize `metrics.json` before the first invocation with frozen task dimensions and `task_started`; add one `activeAttempts[attemptId]` entry plus `attempt_started` per scheduled agent. On `/task-continue`, append `human_gate_ended` (referencing the stored gate event) before activating the next attempt. Do not calculate durations in agents.
55
+ Runtime/hook owns `metrics.json` and `status.json` attempt ledgers. Before the first invocation ensure `task_started` and one `activeAttempts[attemptId]` + `attempt_started` exist (router/runtime bootstrap — parent must not invent parallel indices). On `/task-continue`, run the installed chain hook `end_human_gate` action (or wrapper) so `human_gate_ended` lands before the next attempt. Do not calculate durations in agents.
@@ -124,6 +124,27 @@ function roleFor(agent) {
124
124
  if (/writer/.test(agent || '')) return 'docs';
125
125
  return 'implementation';
126
126
  }
127
+ const DEFAULT_ARTIFACT_OUTPUT_IDS = {
128
+ 'task-router': 'routing',
129
+ 'task-analyst': 'analysis',
130
+ 'solution-architect': 'architecture',
131
+ 'migration-specialist': 'migration-plan',
132
+ debugger: 'debug',
133
+ 'ci-investigator': 'ci',
134
+ 'feature-developer': 'implementation',
135
+ 'build-verifier': 'validation',
136
+ 'code-reviewer': 'review',
137
+ 'security-reviewer': 'security-review',
138
+ 'accessibility-reviewer': 'a11y-review',
139
+ 'performance-auditor': 'perf-report',
140
+ 'api-contract-reviewer': 'api-contract-review',
141
+ 'tech-writer': 'documentation',
142
+ };
143
+ function artifactOutputIdFor(step, agent) {
144
+ if (step && typeof step.artifactOutputId === 'string') return step.artifactOutputId;
145
+ if (step?.artifactOutputIds && typeof step.artifactOutputIds[agent] === 'string') return step.artifactOutputIds[agent];
146
+ return DEFAULT_ARTIFACT_OUTPUT_IDS[agent] || agent;
147
+ }
127
148
  function activateAttempts(step, stepIndex) {
128
149
  const active = { ...(status.activeAttempts || {}) }; const agents = getStepAgents(step);
129
150
  const parallelGroupId = step.parallel && agents.length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
@@ -146,11 +167,61 @@ function resolvedAttempt() {
146
167
  try { const receipts = JSON.parse(fs.readFileSync(path.join(taskDir, '.metrics-receipts.json'), 'utf8')); const receipt = Array.isArray(receipts) ? receipts.find((item) => active[item.attemptId]) : null; if (receipt) return { attemptId: receipt.attemptId, entry: active[receipt.attemptId], confidence: 'fallback', source: 'agent' }; } catch {}
147
168
  return null;
148
169
  }
170
+ function readBoundReceiptOutcome(agent, step, resolved) {
171
+ if (!agent || !resolved) return { outcome: null, receiptRequired: false };
172
+ const manifestPath = path.join(taskDir, 'artifact-manifest.json');
173
+ if (!fs.existsSync(manifestPath)) return { outcome: null, receiptRequired: false };
174
+ try {
175
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
176
+ const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
177
+ const expectedOutputId = artifactOutputIdFor(step, agent);
178
+ const attemptStartedAt = Date.parse(resolved.entry.startedAt);
179
+ const owned = artifacts
180
+ .filter((entry) => {
181
+ if (!entry || entry.producer !== agent || !entry.receipt || typeof entry.receipt.outcome !== 'string') return false;
182
+ const boundByAttempt = typeof entry.receipt.attemptId === 'string' && entry.receipt.attemptId === resolved.attemptId;
183
+ const boundByOutput = entry.receipt.attemptId == null && entry.id === expectedOutputId;
184
+ if (!boundByAttempt && !boundByOutput) return false;
185
+ const terminalAt = Date.parse(entry.timestamps?.completedAt || entry.timestamps?.updatedAt || '');
186
+ return Number.isFinite(terminalAt) && (!Number.isFinite(attemptStartedAt) || terminalAt >= attemptStartedAt);
187
+ })
188
+ .sort((a, b) => {
189
+ const ta = Date.parse(a.timestamps?.completedAt || a.timestamps?.updatedAt || 0) || 0;
190
+ const tb = Date.parse(b.timestamps?.completedAt || b.timestamps?.updatedAt || 0) || 0;
191
+ return tb - ta;
192
+ });
193
+ return { outcome: owned[0]?.receipt?.outcome || null, receiptRequired: true };
194
+ } catch {
195
+ return { outcome: null, receiptRequired: false };
196
+ }
197
+ }
198
+ function reconcileStatusFromManifest(agent, step, resolved) {
199
+ const terminal = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
200
+ const { outcome, receiptRequired } = readBoundReceiptOutcome(agent, step, resolved);
201
+ if (terminal.has(outcome)) {
202
+ status.state = outcome;
203
+ return outcome;
204
+ }
205
+ if (receiptRequired) {
206
+ status.state = 'awaiting_artifact_receipt';
207
+ status.phase = 'blocked';
208
+ return status.state;
209
+ }
210
+ if (terminal.has(status.state)) return status.state;
211
+ // Host reported subagent completed and no blocking receipt → treat as completed for metrics/advance.
212
+ if (hookInput.status === 'completed') {
213
+ status.state = 'completed';
214
+ return 'completed';
215
+ }
216
+ return status.state;
217
+ }
218
+
149
219
  function finishActiveAttempt() {
150
220
  const resolved = resolvedAttempt(); if (!resolved) return null;
151
221
  const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
152
- appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome: ['completed', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown', durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence });
153
- const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return resolved;
222
+ const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
223
+ appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome, durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence });
224
+ const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
154
225
  }
155
226
  function beginHumanGate() { const eventId = `${status.metricsRunId || slug}:gate:${Date.now()}`; appendMetric({ eventId, type: 'human_gate_started', at: now, source: 'hook', attributionConfidence: 'high' }); status.activeHumanGateEventId = eventId; }
156
227
  function endHumanGateIfResumed() {
@@ -220,19 +291,19 @@ function findNextExecutableStep(steps, startIdx, dir) {
220
291
  const AGENT_HANDOFF = {
221
292
  'task-analyst': (s) =>
222
293
  `Invoke task-analyst for slug "${s}". Write brief.md and decomposition.md under .cursor/team/tasks/${s}/. ` +
223
- `Set status.json: phase executing, state awaiting_approval if human gate applies. Do not use legacy phase analysis.`,
294
+ `Upsert the analysis receipt in artifact-manifest.json; do not mutate status.json lifecycle fields. Do not use legacy phase analysis.`,
224
295
  'solution-architect': (s) =>
225
- `Invoke solution-architect for slug "${s}". Read brief.md; write architecture.md for MCP tool/resource/prompt contracts and module boundaries. Update status.json when done.`,
296
+ `Invoke solution-architect for slug "${s}". Read brief.md; write architecture.md for MCP tool/resource/prompt contracts and module boundaries. Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`,
226
297
  'feature-developer': (s) =>
227
298
  `Invoke feature-developer for slug "${s}". Read brief.md, decomposition.md, validation-report.md, architecture.md, security-review.md, debug-report.md if present. ` +
228
299
  `Follow feature-delivery-workflow.mdc and reference-features.mdc. Mandatory flow: contract → schema → handler → registration → unit/contract verification → package validation. ` +
229
- `Include schema/handler unit tests before handoff. Update status.json when done.`,
300
+ `Include schema/handler unit tests before handoff. Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`,
230
301
  'build-verifier': (s) =>
231
302
  `Invoke build-verifier (readonly) for slug "${s}". Follow mcp-ts-tooling.mdc and post-change-test.mdc. ` +
232
303
  `Discover package manager; run typecheck + project tests — never Playwright/XCUITest/Next lint recipes/Go tools as required gates. ` +
233
- `For preset packaging: yarn check:preset-structure (mcp-ts STACKS + MCP_TS_FORBIDDEN_*). Write validation-report.md. Set state completed or validation_failed. Do not edit production code.`,
304
+ `For preset packaging: yarn check:preset-structure (mcp-ts STACKS + MCP_TS_FORBIDDEN_*). Write validation-report.md and emit receipt outcome completed or validation_failed. Do not edit production code.`,
234
305
  'security-reviewer': (s) =>
235
- `Invoke security-reviewer (readonly) for slug "${s}". Follow security-mcp.mdc and mcp-auth-secrets.mdc; write security-review.md. Update status.json when done.`,
306
+ `Invoke security-reviewer (readonly) for slug "${s}". Follow security-mcp.mdc and mcp-auth-secrets.mdc; write security-review.md. Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`,
236
307
  };
237
308
 
238
309
  const REVIEW_AGENTS = new Set([
@@ -243,15 +314,20 @@ const REVIEW_AGENTS = new Set([
243
314
  function metricsHandoff(agent) {
244
315
  const matches = Object.entries(status.activeAttempts || {}).filter(([, entry]) => entry.agent === agent);
245
316
  if (matches.length === 1) {
246
- return ` Metrics attemptId: ${matches[0][0]}; update normal status only. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`;
317
+ return ` Metrics attemptId: ${matches[0][0]}; write owned artifact-manifest receipt outcome. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not mutate status.json or calculate duration.`;
247
318
  }
248
319
  return ' Metrics: use the supplied attemptId when available; for a parallel completion, write a minimal { attemptId, outcome } receipt to .metrics-receipts.json rather than relying on currentAgent. Do not calculate duration.';
249
320
  }
250
321
 
251
- function handoffForAgent(agent, scope) {
322
+ function artifactHandoff(step, agent) {
323
+ const inputIds = Array.isArray(step?.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults';
324
+ return ` Artifact inputs: ${inputIds}; owned output ID: ${artifactOutputIdFor(step, agent)}. Bind the terminal receipt to the supplied attemptId.`;
325
+ }
326
+
327
+ function handoffForAgent(agent, scope, step = null) {
252
328
  const fn = AGENT_HANDOFF[agent];
253
- const handoff = fn ? fn(slug, scope) : `Invoke ${agent} subagent for slug "${slug}". Update status.json when done.`;
254
- return handoff + metricsHandoff(agent);
329
+ const handoff = fn ? fn(slug, scope) : `Invoke ${agent} subagent for slug "${slug}". Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`;
330
+ return handoff + artifactHandoff(step, agent) + metricsHandoff(agent);
255
331
  }
256
332
 
257
333
  function handoffForParallelStep(step) {
@@ -261,7 +337,8 @@ function handoffForParallelStep(step) {
261
337
  .map(([attemptId, entry]) => `${entry.agent}=${attemptId}`);
262
338
  return (
263
339
  `Invoke IN PARALLEL (one message, multiple Task calls): ${agents.join(' AND ')} for slug "${slug}". ` +
264
- `Each agent writes its artifact and appends itself to status.json parallelCompleted when done. ` +
340
+ `Each agent writes its artifact and owned receipt; the hook records parallelCompleted from stops. Do not mutate status.json lifecycle fields. ` +
341
+ `Artifact inputs: ${Array.isArray(step.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${agents.map((agent) => `${agent}=${artifactOutputIdFor(step, agent)}`).join('; ')}. ` +
265
342
  `Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`
266
343
  );
267
344
  }
@@ -300,8 +377,12 @@ function legacyFlow() {
300
377
  appendMetric({ type: 'retry_scheduled', at: now, attemptId: predecessorAttemptId, nextAgent: agent, retryAfterFix: retryAfterFix || null, source: 'hook', attributionConfidence: 'unknown' });
301
378
  activateAttempts({ agent }, stepIndex);
302
379
  }
303
- if (status.state === 'changes_requested' && REVIEW_AGENTS.has(status.currentAgent)) {
380
+ if (status.state === 'changes_requested') {
304
381
  const reviewer = status.currentAgent;
382
+ if (!reviewer) {
383
+ process.stdout.write('{}');
384
+ process.exit(0);
385
+ }
305
386
  scheduleLegacyRetry('feature-developer', reviewer);
306
387
  writeStatus({
307
388
  currentAgent: 'feature-developer',
@@ -375,7 +456,7 @@ if (hookInput.action === 'end_human_gate') {
375
456
  parallelCompleted: [],
376
457
  });
377
458
  if (resumeNext.step.parallel && resumeAgents.length > 1) out(handoffForParallelStep(resumeNext.step));
378
- else out(handoffForAgent(resumeAgents[0], resumeNext.step.scope));
459
+ else out(handoffForAgent(resumeAgents[0], resumeNext.step.scope, resumeNext.step));
379
460
  process.exit(0);
380
461
  }
381
462
  }
@@ -404,6 +485,19 @@ const steps = pipeline.steps || [];
404
485
  const initialIdx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
405
486
  const initialStep = steps[initialIdx];
406
487
  const activeAttemptCountBeforeFinish = Object.keys(status.activeAttempts || {}).length;
488
+ const completingAgentHint = (() => {
489
+ const resolved = resolvedAttempt();
490
+ if (resolved?.entry?.agent) return resolved.entry.agent;
491
+ if (status.currentAgent) return status.currentAgent;
492
+ return getStepAgents(initialStep)[0];
493
+ })();
494
+ const reconcilingAttempt = resolvedAttempt();
495
+ reconcileStatusFromManifest(completingAgentHint, initialStep, reconcilingAttempt);
496
+ if (status.state === 'awaiting_artifact_receipt') {
497
+ writeStatus({});
498
+ process.stdout.write('{}');
499
+ process.exit(0);
500
+ }
407
501
  const finishedAttempt = finishActiveAttempt();
408
502
  if (!finishedAttempt && (hookInput.attemptId || activeAttemptCountBeforeFinish > 0)) {
409
503
  process.stdout.write('{}');
@@ -411,6 +505,7 @@ if (!finishedAttempt && (hookInput.attemptId || activeAttemptCountBeforeFinish >
411
505
  }
412
506
  endHumanGateIfResumed();
413
507
  if (steps.length === 0 || pipeline.autoChain === false) {
508
+ writeStatus({});
414
509
  process.stdout.write('{}');
415
510
  process.exit(0);
416
511
  }
@@ -436,8 +531,74 @@ function scheduleRetry(agent, retryAfterFix, predecessor, explicitStepIndex = nu
436
531
  return stepIndex;
437
532
  }
438
533
 
439
- if (status.state === 'changes_requested' && REVIEW_AGENTS.has(status.currentAgent)) {
440
- const reviewer = status.currentAgent;
534
+ const idx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
535
+ const currentStep = steps[idx];
536
+ const completedAgent = finishedAttempt?.entry?.agent || status.currentAgent || getStepAgents(currentStep)[0];
537
+ const stepAgents = getStepAgents(currentStep);
538
+ if (currentStep?.parallel && stepAgents.length > 1) {
539
+ const done = [...(status.parallelCompleted || [])];
540
+ const outcomes = { ...(status.parallelOutcomes || {}) };
541
+ if (finishedAttempt && completedAgent) {
542
+ if (!done.includes(completedAgent)) done.push(completedAgent);
543
+ outcomes[completedAgent] = {
544
+ outcome: finishedAttempt.outcome || status.state,
545
+ attemptId: finishedAttempt.attemptId,
546
+ confidence: finishedAttempt.confidence,
547
+ };
548
+ }
549
+ writeStatus({ parallelCompleted: done, parallelOutcomes: outcomes });
550
+ const remaining = stepAgents.filter((agent) => !done.includes(agent));
551
+ if (remaining.length > 0) {
552
+ process.stdout.write('{}');
553
+ process.exit(0);
554
+ }
555
+
556
+ const blockedProducer = stepAgents.find((agent) => outcomes[agent]?.outcome === 'blocked');
557
+ if (blockedProducer) {
558
+ writeStatus({ parallelCompleted: [], parallelOutcomes: {}, state: 'blocked', phase: 'blocked', currentAgent: blockedProducer });
559
+ process.stdout.write('{}');
560
+ process.exit(0);
561
+ }
562
+
563
+ const retryReviewer = stepAgents.find((agent) => outcomes[agent]?.outcome === 'changes_requested');
564
+ if (retryReviewer) {
565
+ const retryAfterFixStepIndex = idx;
566
+ const predecessor = outcomes[retryReviewer]
567
+ ? {
568
+ attemptId: outcomes[retryReviewer].attemptId,
569
+ confidence: outcomes[retryReviewer].confidence,
570
+ }
571
+ : finishedAttempt;
572
+ const developerIndex = scheduleRetry('feature-developer', retryReviewer, predecessor);
573
+ writeStatus({
574
+ pipelineIndex: developerIndex,
575
+ currentAgent: 'feature-developer',
576
+ state: 'in_progress',
577
+ phase: 'executing',
578
+ retryAfterFix: retryReviewer,
579
+ retryAfterFixStepIndex,
580
+ parallelCompleted: [],
581
+ parallelOutcomes: {},
582
+ });
583
+ out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ` After fixes, re-run ${retryReviewer}.`);
584
+ process.exit(0);
585
+ }
586
+
587
+ writeStatus({ parallelCompleted: [], parallelOutcomes: {}, state: 'completed' });
588
+ }
589
+
590
+ if (status.state === 'blocked') {
591
+ writeStatus({ state: 'blocked', phase: 'blocked', currentAgent: completedAgent });
592
+ process.stdout.write('{}');
593
+ process.exit(0);
594
+ }
595
+
596
+ if (status.state === 'changes_requested') {
597
+ const reviewer = status.currentAgent || finishedAttempt?.entry?.agent;
598
+ if (!reviewer) {
599
+ process.stdout.write('{}');
600
+ process.exit(0);
601
+ }
441
602
  const retryAfterFixStepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
442
603
  const developerIndex = scheduleRetry('feature-developer', reviewer, finishedAttempt);
443
604
  writeStatus({
@@ -448,7 +609,7 @@ if (status.state === 'changes_requested' && REVIEW_AGENTS.has(status.currentAgen
448
609
  retryAfterFix: reviewer,
449
610
  retryAfterFixStepIndex,
450
611
  });
451
- out(handoffForAgent('feature-developer') + ` After fixes, re-run ${reviewer}.`);
612
+ out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ` After fixes, re-run ${reviewer}.`);
452
613
  process.exit(0);
453
614
  }
454
615
 
@@ -463,7 +624,7 @@ if (status.state === 'validation_failed' && status.currentAgent === 'build-verif
463
624
  retryAfterFix: 'build-verifier',
464
625
  retryAfterFixStepIndex,
465
626
  });
466
- out(handoffForAgent('feature-developer') + ' Read validation-report.md. After fixes, re-run build-verifier.');
627
+ out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ' Read validation-report.md. After fixes, re-run build-verifier.');
467
628
  process.exit(0);
468
629
  }
469
630
 
@@ -471,35 +632,16 @@ if (status.state === 'completed' && status.retryAfterFix) {
471
632
  const retry = status.retryAfterFix;
472
633
  const retryIndex = scheduleRetry(retry, null, finishedAttempt, status.retryAfterFixStepIndex);
473
634
  writeStatus({ pipelineIndex: retryIndex, currentAgent: retry, state: 'in_progress', retryAfterFix: null, retryAfterFixStepIndex: null });
474
- out(handoffForAgent(retry));
635
+ out(handoffForAgent(retry, steps[retryIndex]?.scope, steps[retryIndex]));
475
636
  process.exit(0);
476
637
  }
477
638
 
478
- const idx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
479
- const currentStep = steps[idx];
480
639
  if (!currentStep) {
481
640
  writeStatus({ phase: 'done', state: 'completed', currentAgent: null });
482
641
  out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
483
642
  process.exit(0);
484
643
  }
485
644
 
486
- const completedAgent = finishedAttempt?.entry?.agent || status.currentAgent || getStepAgents(currentStep)[0];
487
- const stepAgents = getStepAgents(currentStep);
488
-
489
- if (currentStep.parallel && stepAgents.length > 1) {
490
- const done = [...(status.parallelCompleted || [])];
491
- if (completedAgent && !done.includes(completedAgent)) {
492
- done.push(completedAgent);
493
- }
494
- writeStatus({ parallelCompleted: done });
495
- const remaining = stepAgents.filter((a) => !done.includes(a));
496
- if (remaining.length > 0) {
497
- process.stdout.write('{}');
498
- process.exit(0);
499
- }
500
- writeStatus({ parallelCompleted: [] });
501
- }
502
-
503
645
  if (hasGateAfterStep(currentStep, pipeline.humanGates)) {
504
646
  beginHumanGate();
505
647
  writeStatus({
@@ -541,6 +683,6 @@ writeStatus({
541
683
  if (nextStep.parallel && nextAgents.length > 1) {
542
684
  out(handoffForParallelStep(nextStep));
543
685
  } else {
544
- out(handoffForAgent(nextAgents[0], nextStep.scope));
686
+ out(handoffForAgent(nextAgents[0], nextStep.scope, nextStep));
545
687
  }
546
688
  NODE
@@ -35,7 +35,7 @@ Roster of specialists is **stack-specific** (agent names and write scopes differ
35
35
 
36
36
  **Cursor frontmatter:** all team pipeline agents use `readonly: false` so they can write team artifacts. Production/app restrictions live in the agent prompt body — do **not** set `readonly: true`.
37
37
 
38
- Full prompts: stack `agents/*.md`. Artifact conventions: stack `team/README.md`.
38
+ Full prompts: stack `agents/*.md`. Artifact conventions: stack `team/README.md`; schema SoT: **agent-artifact-contracts**.
39
39
 
40
40
  ## Dynamic pipeline
41
41
 
@@ -61,9 +61,21 @@ flowchart TD
61
61
 
62
62
  **Source of truth for order:** `pipeline.json` → `steps[]`. Never hardcode analyst → dev → review → QA when `pipeline.json` exists.
63
63
 
64
+ New pipelines retain top-level `profile` and include `routingDecision` with `complexity`, `riskFlags`, non-empty `routingReasons`, `estimatedWorkPackages`, and `openDecisionCount`. The stack `task-router` owns heuristics; this metadata is auditable evidence and does not change hook semantics.
65
+
64
66
  ## Metrics lifecycle
65
67
 
66
- Use the local `metrics.json` ledger described by **agent-task-metrics**: initialize attempts before invocation, let hooks record host-clock ends, and never guess a parallel completion from `currentAgent`.
68
+ Use the local `metrics.json` ledger described by **agent-task-metrics**: the orchestration runtime initializes attempts before invocation, hooks record host-clock ends, and agents never guess a parallel completion from `currentAgent`.
69
+
70
+ ## Artifact context index and receipts
71
+
72
+ Each slug has one `artifact-manifest.json`: `.cursor/team/tasks/<slug>/` or `.claude/team/tasks/<slug>/`. Schema SoT: **agent-artifact-contracts**.
73
+
74
+ - Read the manifest before broad prior-artifact discovery. Each step receives authoritative input entry IDs, owns named output entry IDs, and finishes with one terminal receipt linked to AC/task IDs.
75
+ - Markdown remains detailed evidence; the manifest records producer, status, authoritative paths, timestamps, outcome, and evidence paths.
76
+ - Agents upsert only entries they own and preserve foreign entries. Parallel agents use distinct IDs; the parent/orchestrator serializes manifest merges.
77
+ - The orchestration runtime/hook is the single writer for `status.json` lifecycle fields and `metrics.json`. Agents read status for eligibility but never rewrite state, gate, retry, attempt, timestamp, or metrics fields.
78
+ - Missing/stale manifests are reported as a handoff gap; fall back to `brief.md`, `decomposition.md`, and `pipeline.json` rather than inventing authority.
67
79
 
68
80
  ## status.json (pipeline mode)
69
81
 
@@ -75,10 +87,23 @@ Use the local `metrics.json` ledger described by **agent-task-metrics**: initial
75
87
  "currentAgent": "task-analyst",
76
88
  "phase": "executing",
77
89
  "state": "in_progress",
78
- "awaitingHumanGate": false
90
+ "awaitingHumanGate": false,
91
+ "activeAttempts": {},
92
+ "lastCompletedAttempt": null,
93
+ "parallelCompleted": [],
94
+ "parallelOutcomes": {}
79
95
  }
80
96
  ```
81
97
 
98
+ | Field | Meaning |
99
+ |-------|---------|
100
+ | `activeAttempts` | Transient timing bridge keyed by `attemptId` |
101
+ | `lastCompletedAttempt` | Diagnostic pointer to the latest finished attempt |
102
+ | `parallelCompleted` | Agents that have stopped in the current parallel step |
103
+ | `parallelOutcomes` | Per-agent `{ outcome, attemptId, confidence }` for the current parallel join; cleared when the step advances or retries |
104
+
105
+ On each `subagentStop`, the hook reconciles `status.state` from the completing producer's terminal `artifact-manifest.json` receipt when agents left lifecycle fields untouched. Wait for that handoff before invoking the next step.
106
+
82
107
  | state | Meaning |
83
108
  |-------|---------|
84
109
  | `in_progress` | Current step running |
@@ -102,7 +127,7 @@ Use the local `metrics.json` ledger described by **agent-task-metrics**: initial
102
127
  2. Read `pipeline.json` before every subagent invocation.
103
128
  3. One role per Task call — **except** parallel steps: multiple Task calls in one message.
104
129
  4. **Never** skip `humanGates` without `/task-continue` or explicit user approval.
105
- 5. Persist handoffs to disk (`brief.md`, `decomposition.md`, `debug-report.md`, `validation-report.md`, `architecture.md`, `migration-plan.md`, `ci-report.md`, `a11y-review.md`, `perf-report.md`, `security-review.md`, `api-contract-review.md`, `unit-test-plan.md`, `documentation.md`, `review.md`).
130
+ 5. Persist handoffs to disk and update the producer-owned terminal receipt in `artifact-manifest.json`; Markdown remains detailed evidence.
106
131
  6. On `changes_requested` from reviewers: hook sets `retryAfterFix` → developer → same reviewer.
107
132
  7. On `validation_failed` from `build-verifier`: hook sets `retryAfterFix: build-verifier` → developer → build-verifier.
108
133
  8. When all steps complete, suggest `/technical-retro <slug>`.
@@ -127,7 +152,7 @@ Use Task tool or `/agent-name`. Pass: slug, artifact paths, step `scope` if set.
127
152
  - **`strong`** → **never** pass `fast`; rely on agent pin or parent Max model.
128
153
  3. Parallel steps: apply the step-level `model` to **each** agent in the array (or omit → each agent’s own frontmatter).
129
154
 
130
- After each agent completes, ensure `status.json` has `state: completed` (or `awaiting_approval` if gate applies).
155
+ After each agent completes, verify its terminal manifest receipt, then let the orchestration runtime/hook reconcile `status.json` (`completed`, a blocking outcome, or `awaiting_approval`) from that receipt. Do not ask the agent to mutate shared lifecycle fields, and do not invoke the next specialist until the hook has written the handoff / updated `status.json`.
131
156
 
132
157
  ## Legacy mode
133
158
 
@@ -16,10 +16,21 @@ Phase 1 agents: see `agents/README.md`.
16
16
 
17
17
  Do **not** name Phase 2 agents (`contract-test-*`, `debugger`, Playwright stems, etc.) in fixture JSON — even as skips. Defer those until the agents ship.
18
18
 
19
+ ## Artifact manifest and receipts
20
+
21
+ Each slug stores one context index at `.cursor/team/tasks/<slug>/artifact-manifest.json`. Schema v1 is defined by shared core `agent-team/agent-artifact-contracts.md`: every entry declares its producer, status, authoritative paths, acceptance-criteria IDs, decomposition task IDs, timestamps, and a terminal completion receipt.
22
+
23
+ Producer/consumer rules:
24
+
25
+ - Read the manifest first and use only the authoritative inputs needed by the current step; fall back to `brief.md`, `decomposition.md`, and `pipeline.json` when it is missing or stale, and report that gap.
26
+ - Producers upsert only their stable entry IDs, preserve foreign entries, and finish with `completed`, `blocked`, `changes_requested`, or `validation_failed` receipt evidence.
27
+ - The router owns `pipeline.json` and its routing entry; analyst, developer, verifier, and reviewer own their named outputs and receipts. Consumers do not edit another producer's receipt.
28
+ - Agents do not mutate `status.json` or `metrics.json`. The orchestration runtime/hook is their single writer. Parallel receipt merges are serialized by the parent/orchestrator.
29
+
19
30
  ## Local metrics ledger
20
31
 
21
- `metrics.json` is an append-only schema-v1 event ledger for one task run. It contains only allowlisted IDs, task dimensions, timestamps, outcomes, and attribution confidence—never prompts, secrets, file paths, or contents. The router writes `task_started` / `attempt_started`; the hook records host-clock completion and human-gate edges under a per-task lock with temp-and-rename.
32
+ `metrics.json` is an append-only schema-v1 event ledger for one task run. It contains only allowlisted IDs, task dimensions, timestamps, outcomes, and attribution confidence—never prompts, secrets, file paths, or contents. The orchestration runtime writes `task_started` / `attempt_started`; the hook records host-clock completion and human-gate edges under a per-task lock with temp-and-rename.
22
33
 
23
- `status.json.activeAttempts` is a transient timing bridge keyed by `attemptId`; `lastCompletedAttempt` is diagnostic. For parallel stops, the hook must use a stable payload identity or the sole active attempt. Otherwise an explicit `.metrics-receipts.json` receipt is fallback data marked `source: agent`, `attributionConfidence: fallback`; it must never guess from `currentAgent`.
34
+ `status.json.activeAttempts` is a transient timing bridge keyed by `attemptId`; `lastCompletedAttempt` is diagnostic; `parallelOutcomes` holds per-agent outcomes for the current parallel join until the step advances. For parallel stops, the hook must use a stable payload identity or the sole active attempt. Otherwise an explicit `.metrics-receipts.json` receipt is fallback data marked `source: agent`, `attributionConfidence: fallback`; it must never guess from `currentAgent`.
24
35
 
25
36
  Aggregate with `node packages/ai-rules/scripts/aggregate-agent-task-metrics.mjs --team-root .cursor/team`. It reports role/agent count, completed count, total/average duration, distinct completed run IDs, separate human-gate wait, and incomplete artifacts.
@@ -48,20 +48,13 @@ PASS | PASS_WITH_NOTES | FAIL
48
48
  |-----------|--------|-------|
49
49
  ```
50
50
 
51
- ## On completion
52
-
53
- Update `status.json`:
54
-
55
- ```json
56
- {
57
- "slug": "<slug>",
58
- "currentAgent": "accessibility-reviewer",
59
- "phase": "executing",
60
- "state": "completed",
61
- "updatedAt": "<ISO8601>"
62
- }
63
- ```
51
+ ## Artifact contract
52
+
53
+ - **Authoritative inputs:** read `.cursor/team/tasks/<slug>/artifact-manifest.json` first; consume handoff `artifactInputIds` when supplied, otherwise consume the manifest entries for brief/decomposition, implementation or UI diff scope, and prior review artifacts when present.
54
+ - **Owned outputs:** `a11y-review.md`; upsert only the manifest entry assigned by handoff (`artifactOutputId`; fallback `a11y-review`) and preserve all foreign entries.
55
+ - **Terminal receipt:** cover applicable AC/task IDs, list authoritative evidence paths, and emit `completed` or `changes_requested`. Bind it to the supplied `attemptId` when present.
56
+ - **Shared state:** never create or mutate `status.json` or `metrics.json`; the orchestration runtime/hook owns lifecycle, gates, retries, attempts, and timestamps.
64
57
 
65
- If **FAIL**, set `"state": "changes_requested"` and list specific fixes for `feature-developer`.
58
+ If **FAIL**, emit receipt outcome `changes_requested` and list specific fixes for `feature-developer`.
66
59
 
67
60
  Do not modify production code or tests.
@@ -52,20 +52,13 @@ Link or path to spec/ticket.
52
52
  For feature-developer before or during implementation.
53
53
  ```
54
54
 
55
- ## On completion
56
-
57
- Update `status.json`:
58
-
59
- ```json
60
- {
61
- "slug": "<slug>",
62
- "currentAgent": "api-contract-reviewer",
63
- "phase": "executing",
64
- "state": "completed",
65
- "updatedAt": "<ISO8601>"
66
- }
67
- ```
55
+ ## Artifact contract
56
+
57
+ - **Authoritative inputs:** read `.cursor/team/tasks/<slug>/artifact-manifest.json` first; consume handoff `artifactInputIds` when supplied, otherwise consume the manifest entries for brief/decomposition, architecture when present, and changed types/API/mocks against the contract docs.
58
+ - **Owned outputs:** `api-contract-review.md`; upsert only the manifest entry assigned by handoff (`artifactOutputId`; fallback `api-contract-review`) and preserve all foreign entries.
59
+ - **Terminal receipt:** cover applicable AC/task IDs, list authoritative evidence paths, and emit `completed` or `changes_requested`. Bind it to the supplied `attemptId` when present.
60
+ - **Shared state:** never create or mutate `status.json` or `metrics.json`; the orchestration runtime/hook owns lifecycle, gates, retries, attempts, and timestamps.
68
61
 
69
- If **MISALIGNED**, set `"state": "changes_requested"` when blocking implementation.
62
+ If **MISALIGNED**, emit receipt outcome `changes_requested` when blocking implementation.
70
63
 
71
64
  Do not modify production code.