@bonesofspring/ai-rules 0.2.36 → 0.2.37

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 (181) hide show
  1. package/package.json +4 -1
  2. package/presets/_shared/hooks/README.md +137 -0
  3. package/presets/_shared/hooks/chain-team-phases.sh.tmpl +1288 -0
  4. package/presets/claude/android-kotlin/MCP.md +2 -2
  5. package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +171 -10
  6. package/presets/claude/android-kotlin/mcp.json +1 -1
  7. package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +6 -153
  8. package/presets/claude/android-kotlin/team/README.md +2 -6
  9. package/presets/claude/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
  10. package/presets/claude/go/MCP.md +2 -2
  11. package/presets/claude/go/hooks/chain-team-phases.sh +183 -16
  12. package/presets/claude/go/mcp.json +1 -1
  13. package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +6 -11
  14. package/presets/claude/go/team/README.md +2 -6
  15. package/presets/claude/ios-swift/MCP.md +2 -2
  16. package/presets/claude/ios-swift/hooks/chain-team-phases.sh +178 -17
  17. package/presets/claude/ios-swift/mcp.json +1 -1
  18. package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +6 -153
  19. package/presets/claude/ios-swift/team/README.md +2 -6
  20. package/presets/claude/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
  21. package/presets/claude/java/hooks/chain-team-phases.sh +183 -16
  22. package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +6 -28
  23. package/presets/claude/java/team/README.md +2 -6
  24. package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +182 -13
  25. package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +6 -14
  26. package/presets/claude/mcp-ts/team/README.md +2 -6
  27. package/presets/claude/next/MCP.md +2 -2
  28. package/presets/claude/next/hooks/chain-team-phases.sh +102 -6
  29. package/presets/claude/next/mcp.json +1 -1
  30. package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +6 -226
  31. package/presets/claude/next/team/README.md +2 -6
  32. package/presets/claude/next/team/fixtures/artifact-manifest.example.json +1 -0
  33. package/presets/claude/nuxt/MCP.md +2 -2
  34. package/presets/claude/nuxt/hooks/chain-team-phases.sh +148 -7
  35. package/presets/claude/nuxt/mcp.json +1 -1
  36. package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +6 -223
  37. package/presets/claude/nuxt/team/README.md +2 -6
  38. package/presets/claude/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
  39. package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +183 -16
  40. package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +6 -28
  41. package/presets/claude/php-hexagonal/team/README.md +2 -6
  42. package/presets/claude/php-laravel/hooks/chain-team-phases.sh +183 -16
  43. package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +6 -29
  44. package/presets/claude/php-laravel/team/README.md +2 -6
  45. package/presets/claude/svelte/MCP.md +2 -2
  46. package/presets/claude/svelte/hooks/chain-team-phases.sh +148 -7
  47. package/presets/claude/svelte/mcp.json +1 -1
  48. package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +6 -223
  49. package/presets/claude/svelte/team/README.md +2 -6
  50. package/presets/claude/svelte/team/fixtures/artifact-manifest.example.json +1 -0
  51. package/presets/cursor/android-kotlin/MCP.md +2 -2
  52. package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +150 -7
  53. package/presets/cursor/android-kotlin/mcp.json +1 -1
  54. package/presets/cursor/android-kotlin/team/README.md +2 -0
  55. package/presets/cursor/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
  56. package/presets/cursor/go/MCP.md +2 -2
  57. package/presets/cursor/go/hooks/chain-team-phases.sh +175 -8
  58. package/presets/cursor/go/mcp.json +1 -1
  59. package/presets/cursor/go/team/README.md +2 -0
  60. package/presets/cursor/ios-swift/MCP.md +2 -2
  61. package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +150 -7
  62. package/presets/cursor/ios-swift/mcp.json +1 -1
  63. package/presets/cursor/ios-swift/team/README.md +2 -0
  64. package/presets/cursor/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
  65. package/presets/cursor/java/hooks/chain-team-phases.sh +175 -8
  66. package/presets/cursor/java/team/README.md +2 -0
  67. package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +179 -10
  68. package/presets/cursor/mcp-ts/team/README.md +2 -0
  69. package/presets/cursor/next/MCP.md +2 -2
  70. package/presets/cursor/next/hooks/chain-team-phases.sh +99 -5
  71. package/presets/cursor/next/mcp.json +1 -1
  72. package/presets/cursor/next/team/README.md +2 -0
  73. package/presets/cursor/next/team/fixtures/artifact-manifest.example.json +1 -0
  74. package/presets/cursor/nuxt/MCP.md +2 -2
  75. package/presets/cursor/nuxt/hooks/chain-team-phases.sh +145 -6
  76. package/presets/cursor/nuxt/mcp.json +1 -1
  77. package/presets/cursor/nuxt/team/README.md +2 -0
  78. package/presets/cursor/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
  79. package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +175 -8
  80. package/presets/cursor/php-hexagonal/team/README.md +2 -0
  81. package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +175 -8
  82. package/presets/cursor/php-laravel/team/README.md +2 -0
  83. package/presets/cursor/svelte/MCP.md +2 -2
  84. package/presets/cursor/svelte/hooks/chain-team-phases.sh +145 -6
  85. package/presets/cursor/svelte/mcp.json +1 -1
  86. package/presets/cursor/svelte/team/README.md +2 -0
  87. package/presets/cursor/svelte/team/fixtures/artifact-manifest.example.json +1 -0
  88. package/presets/mavis/android-kotlin/MCP.md +2 -2
  89. package/presets/mavis/android-kotlin/adapter-map.json +1 -1
  90. package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +150 -7
  91. package/presets/mavis/android-kotlin/mcp.json +1 -1
  92. package/presets/mavis/android-kotlin/team/README.md +2 -0
  93. package/presets/mavis/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
  94. package/presets/mavis/go/MCP.md +2 -2
  95. package/presets/mavis/go/adapter-map.json +1 -1
  96. package/presets/mavis/go/hooks/chain-team-phases.sh +175 -8
  97. package/presets/mavis/go/mcp.json +1 -1
  98. package/presets/mavis/go/team/README.md +2 -0
  99. package/presets/mavis/ios-swift/MCP.md +2 -2
  100. package/presets/mavis/ios-swift/adapter-map.json +1 -1
  101. package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +150 -7
  102. package/presets/mavis/ios-swift/mcp.json +1 -1
  103. package/presets/mavis/ios-swift/team/README.md +2 -0
  104. package/presets/mavis/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
  105. package/presets/mavis/java/adapter-map.json +1 -1
  106. package/presets/mavis/java/hooks/chain-team-phases.sh +175 -8
  107. package/presets/mavis/java/team/README.md +2 -0
  108. package/presets/mavis/mcp-ts/adapter-map.json +1 -1
  109. package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +179 -10
  110. package/presets/mavis/mcp-ts/team/README.md +2 -0
  111. package/presets/mavis/next/MCP.md +2 -2
  112. package/presets/mavis/next/adapter-map.json +1 -1
  113. package/presets/mavis/next/hooks/chain-team-phases.sh +99 -5
  114. package/presets/mavis/next/mcp.json +1 -1
  115. package/presets/mavis/next/team/README.md +2 -0
  116. package/presets/mavis/next/team/fixtures/artifact-manifest.example.json +1 -0
  117. package/presets/mavis/nuxt/MCP.md +2 -2
  118. package/presets/mavis/nuxt/adapter-map.json +1 -1
  119. package/presets/mavis/nuxt/hooks/chain-team-phases.sh +145 -6
  120. package/presets/mavis/nuxt/mcp.json +1 -1
  121. package/presets/mavis/nuxt/team/README.md +2 -0
  122. package/presets/mavis/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
  123. package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
  124. package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +175 -8
  125. package/presets/mavis/php-hexagonal/team/README.md +2 -0
  126. package/presets/mavis/php-laravel/adapter-map.json +1 -1
  127. package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +175 -8
  128. package/presets/mavis/php-laravel/team/README.md +2 -0
  129. package/presets/mavis/svelte/MCP.md +2 -2
  130. package/presets/mavis/svelte/adapter-map.json +1 -1
  131. package/presets/mavis/svelte/hooks/chain-team-phases.sh +145 -6
  132. package/presets/mavis/svelte/mcp.json +1 -1
  133. package/presets/mavis/svelte/team/README.md +2 -0
  134. package/presets/mavis/svelte/team/fixtures/artifact-manifest.example.json +1 -0
  135. package/presets/opencode/android-kotlin/MCP.md +2 -2
  136. package/presets/opencode/android-kotlin/adapter-map.json +1 -1
  137. package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +150 -7
  138. package/presets/opencode/android-kotlin/opencode.json +1 -1
  139. package/presets/opencode/android-kotlin/team/README.md +2 -0
  140. package/presets/opencode/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
  141. package/presets/opencode/go/MCP.md +2 -2
  142. package/presets/opencode/go/adapter-map.json +1 -1
  143. package/presets/opencode/go/hooks/chain-team-phases.sh +175 -8
  144. package/presets/opencode/go/opencode.json +1 -1
  145. package/presets/opencode/go/team/README.md +2 -0
  146. package/presets/opencode/ios-swift/MCP.md +2 -2
  147. package/presets/opencode/ios-swift/adapter-map.json +1 -1
  148. package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +150 -7
  149. package/presets/opencode/ios-swift/opencode.json +1 -1
  150. package/presets/opencode/ios-swift/team/README.md +2 -0
  151. package/presets/opencode/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
  152. package/presets/opencode/java/adapter-map.json +1 -1
  153. package/presets/opencode/java/hooks/chain-team-phases.sh +175 -8
  154. package/presets/opencode/java/team/README.md +2 -0
  155. package/presets/opencode/mcp-ts/adapter-map.json +1 -1
  156. package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +179 -10
  157. package/presets/opencode/mcp-ts/team/README.md +2 -0
  158. package/presets/opencode/next/MCP.md +2 -2
  159. package/presets/opencode/next/adapter-map.json +1 -1
  160. package/presets/opencode/next/hooks/chain-team-phases.sh +99 -5
  161. package/presets/opencode/next/opencode.json +1 -1
  162. package/presets/opencode/next/team/README.md +2 -0
  163. package/presets/opencode/next/team/fixtures/artifact-manifest.example.json +1 -0
  164. package/presets/opencode/nuxt/MCP.md +2 -2
  165. package/presets/opencode/nuxt/adapter-map.json +1 -1
  166. package/presets/opencode/nuxt/hooks/chain-team-phases.sh +145 -6
  167. package/presets/opencode/nuxt/opencode.json +1 -1
  168. package/presets/opencode/nuxt/team/README.md +2 -0
  169. package/presets/opencode/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
  170. package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
  171. package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +175 -8
  172. package/presets/opencode/php-hexagonal/team/README.md +2 -0
  173. package/presets/opencode/php-laravel/adapter-map.json +1 -1
  174. package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +175 -8
  175. package/presets/opencode/php-laravel/team/README.md +2 -0
  176. package/presets/opencode/svelte/MCP.md +2 -2
  177. package/presets/opencode/svelte/adapter-map.json +1 -1
  178. package/presets/opencode/svelte/hooks/chain-team-phases.sh +145 -6
  179. package/presets/opencode/svelte/opencode.json +1 -1
  180. package/presets/opencode/svelte/team/README.md +2 -0
  181. package/presets/opencode/svelte/team/fixtures/artifact-manifest.example.json +1 -0
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env bash
2
2
  # preset: mcp-ts (TypeScript MCP) — chain handoffs use build-verifier + security-reviewer; no contract-test-*
3
+ # mcp-ts Phase-1 chain: validation via typecheck/tests + security-reviewer (no contract-test-* handoffs)
4
+ # Phase-2 reserved: debugger / ci-investigator are not in mcp-ts Phase 1 roster.
3
5
  # Chains agent team steps from pipeline.json after subagentStop.
4
6
  # Falls back to legacy phase-based flow when pipeline.json is absent.
5
7
 
@@ -12,7 +14,6 @@ const fs = require('fs');
12
14
  const path = require('path');
13
15
  const crypto = require('crypto');
14
16
 
15
- // mcp-ts Phase-1 chain: validation via typecheck/tests + security-reviewer (no contract-test-* handoffs)
16
17
  const TEAM_ROOT = path.join(process.cwd(), '.ai.local', 'team');
17
18
 
18
19
  const inputRaw = process.env.INPUT || '';
@@ -174,7 +175,21 @@ function mutateMetrics(mutator) {
174
175
  try { metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8')); } catch {
175
176
  const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
176
177
  status.metricsRunId = runId;
177
- metrics = { schemaVersion: 1, task: { runId, slug, preset: 'ai-rules', stack: STACK, platform: PLATFORM, intent: status.intent || 'unknown', profile: 'unknown' }, events: [] };
178
+ // Resolve profile from pipeline.json (preferred) or status.json, falling back to 'unknown'.
179
+ // The router/agent must never write profile into status.json — pipeline.json is the SoT.
180
+ let profile = 'unknown';
181
+ try {
182
+ if (fs.existsSync(pipelinePath)) {
183
+ const pipe = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
184
+ if (pipe && (pipe.profile === 'light' || pipe.profile === 'standard' || pipe.profile === 'full')) {
185
+ profile = pipe.profile;
186
+ }
187
+ }
188
+ } catch {}
189
+ if (profile === 'unknown' && (status.profile === 'light' || status.profile === 'standard' || status.profile === 'full')) {
190
+ profile = status.profile;
191
+ }
192
+ metrics = { schemaVersion: 1, task: { runId, slug, preset: 'ai-rules', stack: STACK, platform: PLATFORM, intent: status.intent || 'unknown', profile }, events: [] };
178
193
  metrics.events.push({ eventId: `${runId}:task_started`, type: 'task_started', at: now, source: 'hook', attributionConfidence: 'high' });
179
194
  }
180
195
  mutator(metrics);
@@ -231,21 +246,119 @@ function resolvedAttempt() {
231
246
  const active = status.activeAttempts || {}; const entries = Object.entries(active);
232
247
  const stableAttemptId = hookInput.attemptId;
233
248
  if (stableAttemptId) {
234
- return active[stableAttemptId] ? { attemptId: stableAttemptId, entry: active[stableAttemptId], confidence: 'high' } : null;
249
+ return active[stableAttemptId]
250
+ ? { attemptId: stableAttemptId, entry: active[stableAttemptId], confidence: 'high' }
251
+ : null;
235
252
  }
236
253
  if (entries.length === 1) return { attemptId: entries[0][0], entry: entries[0][1], confidence: 'high' };
237
254
  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 {}
238
255
  return null;
239
256
  }
257
+ let artifactStallMessage = null;
258
+
259
+ // A1: seed the manifest a modern pipeline expects instead of advancing without
260
+ // one. Exclusive publish via hard link so a producer that wrote the file in the
261
+ // meantime is never overwritten; returns null on success (or when the file
262
+ // appeared) and the fs error otherwise.
263
+ function writeSkeletonManifest(manifestPath) {
264
+ const temporary = `${manifestPath}.${process.pid}.${Date.now()}.seed`;
265
+ const body = JSON.stringify({ schemaVersion: 1, slug, artifacts: [] }, null, 2) + '\n';
266
+ let descriptor = null;
267
+ try {
268
+ descriptor = fs.openSync(temporary, 'wx');
269
+ try { fs.writeSync(descriptor, body); try { fs.fsyncSync(descriptor); } catch {} } finally { fs.closeSync(descriptor); descriptor = null; }
270
+ fs.linkSync(temporary, manifestPath);
271
+ fs.unlinkSync(temporary);
272
+ return null;
273
+ } catch (error) {
274
+ if (descriptor !== null) { try { fs.closeSync(descriptor); } catch {} }
275
+ try { fs.unlinkSync(temporary); } catch {}
276
+ if (error && error.code === 'EEXIST' && fs.existsSync(manifestPath)) return null;
277
+ return String(error && error.message ? error.message : error);
278
+ }
279
+ }
280
+
281
+ // A2: a `completed` receipt must cite evidence the harness can inspect. Order is
282
+ // the message order — the first failing predicate wins, so the operator sees one
283
+ // actionable line. `authoritativePaths[]` stays task-dir-relative; external
284
+ // references belong in `evidencePaths[]`.
285
+ function validateCompletedArtifact(entry) {
286
+ const artifactId = entry && entry.id ? entry.id : '(unnamed)';
287
+ const entryStatus = entry && entry.status;
288
+ if (entryStatus !== 'completed') {
289
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" has receipt.outcome "completed" but entry status "${entryStatus}". Make entry.status and receipt.outcome agree, then resume with: /task-continue ${slug}`;
290
+ }
291
+ const authoritativePaths = entry && Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : [];
292
+ if (authoritativePaths.length === 0) {
293
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritativePaths[] is empty. Record at least one file you produced under .ai.local/team/tasks/${slug}/, then resume with: /task-continue ${slug}`;
294
+ }
295
+ for (const cited of authoritativePaths) {
296
+ const value = typeof cited === 'string' ? cited.trim() : '';
297
+ const resolvedPath = value ? path.resolve(taskDir, value) : taskDir;
298
+ const relative = path.relative(taskDir, resolvedPath);
299
+ const escapes = !value || path.isAbsolute(value) || relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
300
+ if (escapes) {
301
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}", which resolves outside .ai.local/team/tasks/${slug}/ (relative: "${relative}"). Cite a task-relative path; keep external references in evidencePaths[]. Then resume with: /task-continue ${slug}`;
302
+ }
303
+ let stat = null;
304
+ try { stat = fs.statSync(resolvedPath); } catch {}
305
+ if (!stat || !stat.isFile()) {
306
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}" but no such file exists under .ai.local/team/tasks/${slug}/. Write the file, then resume with: /task-continue ${slug}`;
307
+ }
308
+ if (/\.md[c]?$/i.test(value)) {
309
+ let content = '';
310
+ try { content = fs.readFileSync(resolvedPath, 'utf8'); } catch {}
311
+ if (!/\S/.test(content)) {
312
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritative path "${value}" has no non-whitespace content. Produce the artifact, then resume with: /task-continue ${slug}`;
313
+ }
314
+ }
315
+ }
316
+ return null;
317
+ }
318
+
240
319
  function readBoundReceiptOutcome(agent, step, resolved) {
241
320
  if (!agent || !resolved) return { outcome: null, receiptRequired: false };
242
321
  const manifestPath = path.join(taskDir, 'artifact-manifest.json');
243
- if (!fs.existsSync(manifestPath)) return { outcome: null, receiptRequired: false };
322
+ const expectedOutputId = artifactOutputIdFor(step, agent);
323
+ if (!fs.existsSync(manifestPath)) {
324
+ // A1: absent manifest + a parsed modern pipeline denies silent advancement.
325
+ // Legacy/step-less pipelines keep their previous behaviour (legacyFlow owns them).
326
+ if (!(Array.isArray(steps) && steps.length > 0)) return { outcome: null, receiptRequired: false };
327
+ const seeded = writeSkeletonManifest(manifestPath);
328
+ const stepIndex = typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : 0;
329
+ if (seeded) {
330
+ return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: artifact-manifest.json is missing and the skeleton could not be written (${seeded}). Create .ai.local/team/tasks/${slug}/artifact-manifest.json with {schemaVersion:1, slug, artifacts:[]}, add the receipt for artifactOutputId "${expectedOutputId}", then resume with: /task-continue ${slug}` };
331
+ }
332
+ return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: no artifact-manifest.json for step ${stepIndex} (${agent}). Wrote a skeleton {schemaVersion:1, slug, artifacts:[]}. Expected artifactOutputId "${expectedOutputId}". Write the artifact and its receipt, then resume with: /task-continue ${slug}` };
333
+ }
244
334
  try {
245
335
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
336
+ // Guard: the schema key is `artifacts` (see agent-artifact-contracts.md). A top-level
337
+ // `entries` key is a silent bug — producer wrote to a wrong field, hook would not
338
+ // see the receipt, and the step hangs in `awaiting_artifact_receipt`. Warn loudly.
339
+ if (manifest && typeof manifest === 'object' && !Array.isArray(manifest.artifacts) && Array.isArray(manifest.entries)) {
340
+ process.stderr.write(`WARNING: ${manifestPath} has top-level "entries" but no "artifacts" array; reading only "artifacts" per schema. The producer likely upserted into the wrong key. See agent-artifact-contracts.md (Schema field name).` + '\n');
341
+ } else if (manifest && typeof manifest === 'object' && Array.isArray(manifest.entries) && Array.isArray(manifest.artifacts)) {
342
+ process.stderr.write(`WARNING: ${manifestPath} has both "artifacts" and "entries" keys; reading only "artifacts" per schema. Foreign "entries" content is ignored.` + '\n');
343
+ }
246
344
  const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
247
- const expectedOutputId = artifactOutputIdFor(step, agent);
248
345
  const attemptStartedAt = Date.parse(resolved.entry.startedAt);
346
+ // Pre-scan: warn on the silent-bug classes the filter below would otherwise drop.
347
+ // A receipt with a non-matching attemptId is dropped silently; without this warning,
348
+ // the step hangs in `awaiting_artifact_receipt` with no signal of why. Same for
349
+ // receipts whose terminal timestamp is older than the active attempt (stale retry).
350
+ const activeIds = new Set(Object.keys(status.activeAttempts || {}));
351
+ for (const entry of artifacts) {
352
+ if (!entry || entry.producer !== agent || !entry.receipt || typeof entry.receipt.outcome !== 'string') continue;
353
+ const rid = entry.receipt.attemptId;
354
+ if (typeof rid === 'string' && rid !== resolved.attemptId && !activeIds.has(rid)) {
355
+ process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${entry.id}" carries attemptId "${rid}" that does not match the active attempt "${resolved.attemptId}". The receipt is being dropped; step will hang in \`awaiting_artifact_receipt\` unless the producer retries. Common cause: agent reused an attemptId from a prior failed attempt. See agent-artifact-contracts.md (Receipt binding).` + '\n');
356
+ }
357
+ const terminalAt = Date.parse(entry.timestamps?.completedAt || entry.timestamps?.updatedAt || '');
358
+ if (Number.isFinite(attemptStartedAt) && Number.isFinite(terminalAt) && terminalAt < attemptStartedAt) {
359
+ process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${entry.id}" has timestamps.completedAt older than the active attempt's startedAt. Likely a stale receipt from a previous attempt; it is being dropped. See agent-artifact-contracts.md (Receipt binding).` + '\n');
360
+ }
361
+ }
249
362
  const owned = artifacts
250
363
  .filter((entry) => {
251
364
  if (!entry || entry.producer !== agent || !entry.receipt || typeof entry.receipt.outcome !== 'string') return false;
@@ -260,19 +373,33 @@ function readBoundReceiptOutcome(agent, step, resolved) {
260
373
  const tb = Date.parse(b.timestamps?.completedAt || b.timestamps?.updatedAt || 0) || 0;
261
374
  return tb - ta;
262
375
  });
263
- return { outcome: owned[0]?.receipt?.outcome || null, receiptRequired: true };
376
+ // Bonus: warn if the active attempt's receipts all lack attemptId in a non-parallel step.
377
+ // The orchestrator always provides attemptId, so a missing one means the agent dropped it
378
+ // (model output, JSON.stringify omission, etc.). boundByOutput still binds the receipt by
379
+ // expectedOutputId, so this is not fatal — but it is a contract violation worth flagging.
380
+ if (owned.length > 0 && owned[0].receipt.attemptId == null && !(step && step.parallel && Array.isArray(getStepAgents(step)) && getStepAgents(step).length > 1)) {
381
+ process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${owned[0].id}" lacks entry.receipt.attemptId on a non-parallel step. The receipt is bound by output-id fallback; the agent should always include the attemptId the orchestrator provides. See agent-artifact-contracts.md (Receipt binding).` + '\n');
382
+ }
383
+ const outcome = owned[0]?.receipt?.outcome || null;
384
+ if (outcome === 'completed') {
385
+ const stallMessage = validateCompletedArtifact(owned[0]);
386
+ if (stallMessage) return { outcome: null, receiptRequired: true, stallMessage };
387
+ }
388
+ return { outcome, receiptRequired: true };
264
389
  } catch {
265
390
  return { outcome: null, receiptRequired: false };
266
391
  }
267
392
  }
268
393
  function reconcileStatusFromManifest(agent, step, resolved) {
269
394
  const terminal = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
270
- const { outcome, receiptRequired } = readBoundReceiptOutcome(agent, step, resolved);
395
+ artifactStallMessage = null;
396
+ const { outcome, receiptRequired, stallMessage } = readBoundReceiptOutcome(agent, step, resolved);
271
397
  if (terminal.has(outcome)) {
272
398
  status.state = outcome;
273
399
  return outcome;
274
400
  }
275
401
  if (receiptRequired) {
402
+ artifactStallMessage = stallMessage || null;
276
403
  status.state = 'awaiting_artifact_receipt';
277
404
  status.phase = 'blocked';
278
405
  return status.state;
@@ -331,6 +458,15 @@ function out(message) {
331
458
  process.stdout.write(JSON.stringify({ followup_message: message }));
332
459
  }
333
460
 
461
+ // The stall text always reaches stderr so a second, different rejection is never
462
+ // silent; `out()` fires only when the stop enters the stall, so the follow-up
463
+ // message cannot loop.
464
+ function emitArtifactStall(message, announce) {
465
+ if (message) process.stderr.write(message + '\n');
466
+ if (message && announce) out(message);
467
+ else process.stdout.write('{}');
468
+ }
469
+
334
470
  function readArtifact(name) {
335
471
  const p = path.join(taskDir, name);
336
472
  if (!fs.existsSync(p)) return '';
@@ -348,7 +484,6 @@ function getStepAgents(step) {
348
484
 
349
485
  function skipIfMatches(skipIf, dir) {
350
486
  if (!skipIf) return false;
351
- // Phase-2 reserved: debugger / ci-investigator are not in mcp-ts Phase 1 roster.
352
487
  if (skipIf === 'debugger.fixed') {
353
488
  const text = readArtifact('debug-report.md');
354
489
  return /fixApplied:\s*true/i.test(text) || /\*\*Fix applied:\*\*\s*true/i.test(text);
@@ -578,21 +713,23 @@ const AGENT_HANDOFF = {
578
713
  `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.`,
579
714
  'feature-developer': (s) =>
580
715
  `Invoke feature-developer for slug "${s}". Read brief.md, decomposition.md, validation-report.md, architecture.md, security-review.md, debug-report.md if present. ` +
581
- `Follow feature-delivery-workflow.mdc and reference-features.mdc. Mandatory flow: contract → schema → handler → registration → unit/contract verification → package validation. ` +
716
+ `Follow architecture/feature-delivery.md and architecture/reference-features.md. Mandatory flow: contract → schema → handler → registration → unit/contract verification → package validation. ` +
582
717
  `Include schema/handler unit tests before handoff. Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`,
583
718
  'build-verifier': (s) =>
584
- `Invoke build-verifier (readonly) for slug "${s}". Follow mcp-ts-tooling.mdc and post-change-test.mdc. ` +
719
+ `Invoke build-verifier (readonly) for slug "${s}". Follow tooling-and-review/mcp-ts-tooling.md and tooling-and-review/post-change-test.md. ` +
585
720
  `Discover package manager; run typecheck + project tests — never Playwright/XCUITest/Next lint recipes/Go tools as required gates. ` +
586
721
  `Write validation-report.md and emit receipt outcome completed or validation_failed. Do not edit production code.`,
587
722
  'security-reviewer': (s) =>
588
- `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.`,
723
+ `Invoke security-reviewer (readonly) for slug "${s}". Follow tooling-and-review/security-mcp.md and api-and-data/mcp-auth-secrets.md; write security-review.md. Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`,
589
724
  };
590
725
 
591
726
  const REVIEW_AGENTS = new Set([
727
+ 'code-reviewer',
728
+ 'accessibility-reviewer',
592
729
  'security-reviewer',
730
+ 'api-contract-reviewer',
593
731
  ]);
594
732
 
595
-
596
733
  function metricsHandoff(agent) {
597
734
  const matches = Object.entries(status.activeAttempts || {}).filter(([, entry]) => entry.agent === agent);
598
735
  if (matches.length === 1) {
@@ -866,10 +1003,11 @@ const completingAgentHint = (() => {
866
1003
  return getStepAgents(initialStep)[0];
867
1004
  })();
868
1005
  const reconcilingAttempt = resolvedAttempt();
1006
+ const wasWaitingForReceipt = status.state === 'awaiting_artifact_receipt';
869
1007
  reconcileStatusFromManifest(completingAgentHint, initialStep, reconcilingAttempt);
870
1008
  if (status.state === 'awaiting_artifact_receipt') {
871
1009
  writeStatus({});
872
- process.stdout.write('{}');
1010
+ emitArtifactStall(artifactStallMessage, !wasWaitingForReceipt);
873
1011
  process.exit(0);
874
1012
  }
875
1013
  let finishedAttempt = finishActiveAttempt();
@@ -879,6 +1017,11 @@ if (!finishedAttempt && activeAttemptCountBeforeFinish > 0) {
879
1017
  if (repaired) {
880
1018
  appendMetric({ type: 'parallel_attribution_repair', at: now, attemptIds: [repaired.attemptId], source: 'hook', attributionConfidence: 'fallback' });
881
1019
  reconcileStatusFromManifest(repaired.entry.agent, steps[repaired.entry.stepIndex], repaired);
1020
+ if (status.state === 'awaiting_artifact_receipt') {
1021
+ writeStatus({});
1022
+ emitArtifactStall(artifactStallMessage, true);
1023
+ process.exit(0);
1024
+ }
882
1025
  finishedAttempt = finishActiveAttempt(repaired);
883
1026
  } else {
884
1027
  writeStatus({});
@@ -935,6 +1078,7 @@ const waveIndexes = activeWave
935
1078
  ? [idx]
936
1079
  : (isGraphMode() && finishedAttempt ? [completedStepIndex] : null));
937
1080
 
1081
+
938
1082
  if (waveIndexes) {
939
1083
  const waveAgents = waveIndexes.flatMap((i) => getStepAgents(steps[i]));
940
1084
  const done = [...(status.parallelCompleted || [])];
@@ -987,6 +1131,20 @@ if (waveIndexes) {
987
1131
  }
988
1132
 
989
1133
  const retryReviewer = waveAgents.find((agent) => outcomes[agent]?.outcome === 'changes_requested');
1134
+ if (retryReviewer === 'mockup-reviewer') {
1135
+ beginHumanGate();
1136
+ writeStatus({
1137
+ awaitingHumanGate: true,
1138
+ state: 'awaiting_approval',
1139
+ currentAgent: 'mockup-reviewer',
1140
+ parallelCompleted: [],
1141
+ parallelOutcomes: {},
1142
+ waveSteps: [],
1143
+ waveId: null,
1144
+ });
1145
+ out(`Mockup review FAIL for slug "${slug}". Read mockup-review.md. Resume only via /task-continue. Do not retry feature-developer.`);
1146
+ process.exit(0);
1147
+ }
990
1148
  if (retryReviewer) {
991
1149
  if (isGraphMode()) {
992
1150
  const reviewerStepIndex = waveIndexes.find((i) => getStepAgents(steps[i]).includes(retryReviewer));
@@ -1093,6 +1251,17 @@ if (status.state === 'blocked') {
1093
1251
  process.exit(0);
1094
1252
  }
1095
1253
 
1254
+ if (status.state === 'changes_requested' && (completedAgent === 'mockup-reviewer' || status.currentAgent === 'mockup-reviewer')) {
1255
+ beginHumanGate();
1256
+ writeStatus({
1257
+ awaitingHumanGate: true,
1258
+ state: 'awaiting_approval',
1259
+ currentAgent: 'mockup-reviewer',
1260
+ });
1261
+ out(`Mockup review FAIL for slug "${slug}". Read mockup-review.md. Resume only via /task-continue. Do not retry feature-developer.`);
1262
+ process.exit(0);
1263
+ }
1264
+
1096
1265
  if (status.state === 'changes_requested') {
1097
1266
  const reviewer = status.currentAgent || finishedAttempt?.entry?.agent;
1098
1267
  if (!reviewer) {
@@ -32,10 +32,14 @@ Roster of specialists is **stack-specific** (agent names and write scopes differ
32
32
  | Tests | unit planner/generator/healer; e2e/UI planner/generator/healer (stack-native) |
33
33
  | Docs | `tech-writer` |
34
34
 
35
- **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`.
35
+ **Claude packaging:** team pipeline agents are Markdown files with YAML frontmatter under `.claude/agents/`; subagents are invoked with the Task tool and start with no always-on context, so each prompt re-declares the rules it needs. Production/app restrictions live in the agent prompt body. See `agents/README.md`.
36
36
 
37
37
  Full prompts: stack `agents/*.md`. Artifact conventions: stack `team/README.md`; schema SoT: **agent-artifact-contracts**.
38
38
 
39
+ ## Stack notes
40
+
41
+ Roles, write scopes, and Claude `tools` / frontmatter packaging — **`agents/README.md`**.
42
+
39
43
  ## Dynamic pipeline
40
44
 
41
45
  ```mermaid
@@ -203,7 +207,7 @@ On each `subagentStop`, the hook reconciles `status.state` from the completing p
203
207
  12. **Invoke the ready set, and never advance before reconciliation.** In graph mode the hook computes the ready queue; invoke exactly the handoff's agent list (a wave in one assistant turn, multiple Task calls) and do not start any next step from your own reasoning until the hook records the join and emits the next handoff. The wave is the join unit; `status.joinedSlots` is the satisfaction ledger.
204
208
  13. **Only a proven conflict-free set is `parallel: true`.** Disjoint declared `writeScopes`, distinct agents, distinct `artifactOutputIds`, no shared lifecycle file; `mockup-reviewer` is never parallel (its FAIL gate is serial). See **plan-graph** § Conflict model.
205
209
 
206
- ## Team artifact I/O (Cursor Shell sandbox)
210
+ ## Team artifact I/O
207
211
 
208
212
  - **Persist the original prompt.** For **every** task — `/task` or a routed work request — write the user's **verbatim** prompt to `.ai.local/team/tasks/<slug>/prompt.md` during slug bootstrap (write-if-absent; never overwrite on resume). The header is additive provenance only; the fenced text block holds the user's words unchanged. It is not a manifest `artifacts[]` body — the path lives on the `routing` entry. See **agent-artifact-contracts** § Prompt artifact.
209
213
  - **Append follow-up prompts.** When a user-authored prompt arrives for an active slug (new message, `/task-continue` args, gate feedback, clarification), append it verbatim to `.ai.local/team/tasks/<slug>/prompt-log.md` — `seq` = current max + 1, create on first append, never rewrite or duplicate an entry, never touch `prompt.md`. Exclude hook `followup_message` and empty/argument-less invocations. Not a manifest `artifacts[]` body — the path lives on the `routing` entry. See **agent-artifact-contracts** § Prompt log.
@@ -249,15 +253,3 @@ When user describes a **non-trivial task** (not a question), suggest `/task <mes
249
253
  ## Preset authoring
250
254
 
251
255
  When the work edits `packages/ai-rules/presets/**` (or dogfood `.cursor/` sync of presets), follow meta-rules: **preset-goals**, **preset-pr-checklist**, **preset-twin-sync**, **preset-layering**, **preset-token-budget**, **preset-no-cross-stack-leakage**.
252
-
253
- ## Stack notes
254
-
255
- - Scope: TypeScript MCP server modules (`src/tools|resources|prompts`, `src/index.ts`) — not Next `app/src`, iOS `Features/`, or Go hexagonal trees.
256
- - **Phase 1 roster only:** `task-router`, `task-analyst`, `solution-architect`, `feature-developer`, `build-verifier`, `security-reviewer`.
257
- - **No** `accessibility-reviewer`, Playwright, XCUITest, `integration-test-*`, `contract-test-*`, or `codebase-analyzer` (Phase 2) — do not schedule them.
258
- - **Explain-as-is override:** shared catalog mentions `codebase-analyzer` — in Phase 1 answer inline or load requestable MCP rules; do not invoke a missing agent.
259
- - **Phase 1 artifacts:** `brief.md`, `decomposition.md`, `architecture.md`, `validation-report.md`, `security-review.md`; schema/style review via parent skill `code-review` → `review.md`. Shared-core names like `a11y-review.md`, `ci-report.md`, `unit-test-plan.md` are N/A until Phase 2 agents ship.
260
- - **Review-only:** pipeline step = `security-reviewer` for threat/capability diffs; parent applies skill `code-review` for schema/contract/style (no `code-reviewer` agent in Phase 1).
261
- - After TS changes, pipeline includes **build-verifier** with repository typecheck/test via `post-change-test` / `mcp-ts-tooling`.
262
-
263
- **Product specs:** When `/task` or `/spec-start` touches pages/features/`docs/specs`: if INDEX exists and no generate intent → instruct next agent to load requestable **`product-specs`** (consume; soft-fail; never invent). If generate/bootstrap/`spec-gen` → load **`product-specs-authoring`** + skill **`spec-authoring`** inside **task-analyst** (not a separate pipeline step); pass created spec paths + INDEX diff in handoff; human gate must approve before feature-developer. No-op if INDEX absent and no author intent.
@@ -74,6 +74,8 @@ Same JSON on Claude, Mavis, or OpenCode: `bash .<tool>/hooks/chain-team-phases.s
74
74
 
75
75
  ## Contracts
76
76
 
77
+ - **Manifest field name:** receipts go in `artifacts[]`. Anything written under `entries` is ignored — the hook reads only `artifacts` and prints a dual-read warning naming the file. See `agent-team/agent-artifact-contracts.md` § Schema field name.
78
+ - **Evidence paths:** `authoritativePaths[]` must be task-relative (`.ai.local/team/tasks/<slug>/…`). Put anything outside the task directory — e.g. `openspec/changes/**` — in `evidencePaths[]`.
77
79
  - Manifest schema: shared core `agent-team/agent-artifact-contracts.md`. Read it first; producers upsert only their IDs.
78
80
  - Metrics: append-only allowlisted events — `agent-team/agent-task-metrics.md`. Aggregate: `node node_modules/@bonesofspring/ai-rules/scripts/aggregate-agent-task-metrics.mjs --team-root .ai.local/team`.
79
81
  - Commit `.ai.local/team/` templates (and slugs if you want them in clones).
@@ -89,9 +91,3 @@ Same JSON on Claude, Mavis, or OpenCode: `bash .<tool>/hooks/chain-team-phases.s
89
91
  **Checkpoint / resume:** progress is checkpointed to `tasks/<slug>/.memlog.md` (`## <date>` + `event:` entries) and the `artifact-manifest.json` `implementation` entry (`authoritativePaths`). A resumed run reads both and continues at the first stage whose exit criteria are unmet.
90
92
 
91
93
  **Self-review / re-anchor:** each producing agent records a `## Self-review` block in the artifact it owns (`brief.md` / `implementation.md` / `debug-report.md` / `validation-report.md` / `review.md`) and, on detected context loss / excess, a re-anchor line in `.memlog.md` — `event:` (no plan change) or `decision: replan rev N → N+1` (plan change). No hook/lifecycle field is added.
92
-
93
- ## Contracts
94
-
95
- - Manifest schema: shared core `agent-team/agent-artifact-contracts.md`. Read it first; producers upsert only their IDs.
96
- - Metrics: append-only allowlisted events — `agent-team/agent-task-metrics.md`. Aggregate: `node node_modules/@bonesofspring/ai-rules/scripts/aggregate-agent-task-metrics.mjs --team-root .ai.local/team`.
97
- - Commit `.ai.local/team/` templates (and slugs if you want them in clones).
@@ -9,9 +9,9 @@ Copied to the **project root** as `.mcp.json` on `ai-rules init claude --preset
9
9
  | `context7` | `@upstash/context7-mcp` | Up-to-date Next/React/TS docs |
10
10
  | `playwright-test` | `@playwright/mcp` | Browser MCP; server name matches `mcp__playwright-test__*` in agents |
11
11
  | `chrome-devtools` | `chrome-devtools-mcp` | Live DOM/network/performance |
12
- | `figma` | remote `https://mcp.figma.com/mcp` | Design context → code; OAuth on first connect |
12
+ | `figma` | desktop `http://127.0.0.1:3845/mcp` | Design context → code; local desktop server (enable in Figma Desktop, Dev/Full seat) |
13
13
 
14
- Do not commit secrets. Optional: `CONTEXT7_API_KEY`. Figma — OAuth (do not write the token to a file). After clone/init Claude Code will ask to approve project MCP (`/mcp`).
14
+ Do not commit secrets. Optional: `CONTEXT7_API_KEY`. Figma — local desktop server (enable in Figma Desktop, Dev/Full seat). After clone/init Claude Code will ask to approve project MCP (`/mcp`).
15
15
 
16
16
  For the full Playwright Test Agents loop (`planner_*` / `generator_*` / `test_*`) additionally: `npx playwright init-agents --loop=claude` in an app with `@playwright/test`.
17
17
 
@@ -259,16 +259,91 @@ function resolvedAttempt() {
259
259
  const active = status.activeAttempts || {}; const entries = Object.entries(active);
260
260
  const stableAttemptId = hookInput.attemptId;
261
261
  if (stableAttemptId) {
262
- return active[stableAttemptId] ? { attemptId: stableAttemptId, entry: active[stableAttemptId], confidence: 'high' } : null;
262
+ return active[stableAttemptId]
263
+ ? { attemptId: stableAttemptId, entry: active[stableAttemptId], confidence: 'high' }
264
+ : null;
263
265
  }
264
266
  if (entries.length === 1) return { attemptId: entries[0][0], entry: entries[0][1], confidence: 'high' };
265
267
  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 {}
266
268
  return null;
267
269
  }
270
+ let artifactStallMessage = null;
271
+
272
+ // A1: seed the manifest a modern pipeline expects instead of advancing without
273
+ // one. Exclusive publish via hard link so a producer that wrote the file in the
274
+ // meantime is never overwritten; returns null on success (or when the file
275
+ // appeared) and the fs error otherwise.
276
+ function writeSkeletonManifest(manifestPath) {
277
+ const temporary = `${manifestPath}.${process.pid}.${Date.now()}.seed`;
278
+ const body = JSON.stringify({ schemaVersion: 1, slug, artifacts: [] }, null, 2) + '\n';
279
+ let descriptor = null;
280
+ try {
281
+ descriptor = fs.openSync(temporary, 'wx');
282
+ try { fs.writeSync(descriptor, body); try { fs.fsyncSync(descriptor); } catch {} } finally { fs.closeSync(descriptor); descriptor = null; }
283
+ fs.linkSync(temporary, manifestPath);
284
+ fs.unlinkSync(temporary);
285
+ return null;
286
+ } catch (error) {
287
+ if (descriptor !== null) { try { fs.closeSync(descriptor); } catch {} }
288
+ try { fs.unlinkSync(temporary); } catch {}
289
+ if (error && error.code === 'EEXIST' && fs.existsSync(manifestPath)) return null;
290
+ return String(error && error.message ? error.message : error);
291
+ }
292
+ }
293
+
294
+ // A2: a `completed` receipt must cite evidence the harness can inspect. Order is
295
+ // the message order — the first failing predicate wins, so the operator sees one
296
+ // actionable line. `authoritativePaths[]` stays task-dir-relative; external
297
+ // references belong in `evidencePaths[]`.
298
+ function validateCompletedArtifact(entry) {
299
+ const artifactId = entry && entry.id ? entry.id : '(unnamed)';
300
+ const entryStatus = entry && entry.status;
301
+ if (entryStatus !== 'completed') {
302
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" has receipt.outcome "completed" but entry status "${entryStatus}". Make entry.status and receipt.outcome agree, then resume with: /task-continue ${slug}`;
303
+ }
304
+ const authoritativePaths = entry && Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : [];
305
+ if (authoritativePaths.length === 0) {
306
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritativePaths[] is empty. Record at least one file you produced under .ai.local/team/tasks/${slug}/, then resume with: /task-continue ${slug}`;
307
+ }
308
+ for (const cited of authoritativePaths) {
309
+ const value = typeof cited === 'string' ? cited.trim() : '';
310
+ const resolvedPath = value ? path.resolve(taskDir, value) : taskDir;
311
+ const relative = path.relative(taskDir, resolvedPath);
312
+ const escapes = !value || path.isAbsolute(value) || relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
313
+ if (escapes) {
314
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}", which resolves outside .ai.local/team/tasks/${slug}/ (relative: "${relative}"). Cite a task-relative path; keep external references in evidencePaths[]. Then resume with: /task-continue ${slug}`;
315
+ }
316
+ let stat = null;
317
+ try { stat = fs.statSync(resolvedPath); } catch {}
318
+ if (!stat || !stat.isFile()) {
319
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}" but no such file exists under .ai.local/team/tasks/${slug}/. Write the file, then resume with: /task-continue ${slug}`;
320
+ }
321
+ if (/\.md[c]?$/i.test(value)) {
322
+ let content = '';
323
+ try { content = fs.readFileSync(resolvedPath, 'utf8'); } catch {}
324
+ if (!/\S/.test(content)) {
325
+ return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritative path "${value}" has no non-whitespace content. Produce the artifact, then resume with: /task-continue ${slug}`;
326
+ }
327
+ }
328
+ }
329
+ return null;
330
+ }
331
+
268
332
  function readBoundReceiptOutcome(agent, step, resolved) {
269
333
  if (!agent || !resolved) return { outcome: null, receiptRequired: false };
270
334
  const manifestPath = path.join(taskDir, 'artifact-manifest.json');
271
- if (!fs.existsSync(manifestPath)) return { outcome: null, receiptRequired: false };
335
+ const expectedOutputId = artifactOutputIdFor(step, agent);
336
+ if (!fs.existsSync(manifestPath)) {
337
+ // A1: absent manifest + a parsed modern pipeline denies silent advancement.
338
+ // Legacy/step-less pipelines keep their previous behaviour (legacyFlow owns them).
339
+ if (!(Array.isArray(steps) && steps.length > 0)) return { outcome: null, receiptRequired: false };
340
+ const seeded = writeSkeletonManifest(manifestPath);
341
+ const stepIndex = typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : 0;
342
+ if (seeded) {
343
+ return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: artifact-manifest.json is missing and the skeleton could not be written (${seeded}). Create .ai.local/team/tasks/${slug}/artifact-manifest.json with {schemaVersion:1, slug, artifacts:[]}, add the receipt for artifactOutputId "${expectedOutputId}", then resume with: /task-continue ${slug}` };
344
+ }
345
+ return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: no artifact-manifest.json for step ${stepIndex} (${agent}). Wrote a skeleton {schemaVersion:1, slug, artifacts:[]}. Expected artifactOutputId "${expectedOutputId}". Write the artifact and its receipt, then resume with: /task-continue ${slug}` };
346
+ }
272
347
  try {
273
348
  const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
274
349
  // Guard: the schema key is `artifacts` (see agent-artifact-contracts.md). A top-level
@@ -280,7 +355,6 @@ function readBoundReceiptOutcome(agent, step, resolved) {
280
355
  process.stderr.write(`WARNING: ${manifestPath} has both "artifacts" and "entries" keys; reading only "artifacts" per schema. Foreign "entries" content is ignored.` + '\n');
281
356
  }
282
357
  const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
283
- const expectedOutputId = artifactOutputIdFor(step, agent);
284
358
  const attemptStartedAt = Date.parse(resolved.entry.startedAt);
285
359
  // Pre-scan: warn on the silent-bug classes the filter below would otherwise drop.
286
360
  // A receipt with a non-matching attemptId is dropped silently; without this warning,
@@ -319,19 +393,26 @@ function readBoundReceiptOutcome(agent, step, resolved) {
319
393
  if (owned.length > 0 && owned[0].receipt.attemptId == null && !(step && step.parallel && Array.isArray(getStepAgents(step)) && getStepAgents(step).length > 1)) {
320
394
  process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${owned[0].id}" lacks entry.receipt.attemptId on a non-parallel step. The receipt is bound by output-id fallback; the agent should always include the attemptId the orchestrator provides. See agent-artifact-contracts.md (Receipt binding).` + '\n');
321
395
  }
322
- return { outcome: owned[0]?.receipt?.outcome || null, receiptRequired: true };
396
+ const outcome = owned[0]?.receipt?.outcome || null;
397
+ if (outcome === 'completed') {
398
+ const stallMessage = validateCompletedArtifact(owned[0]);
399
+ if (stallMessage) return { outcome: null, receiptRequired: true, stallMessage };
400
+ }
401
+ return { outcome, receiptRequired: true };
323
402
  } catch {
324
403
  return { outcome: null, receiptRequired: false };
325
404
  }
326
405
  }
327
406
  function reconcileStatusFromManifest(agent, step, resolved) {
328
407
  const terminal = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
329
- const { outcome, receiptRequired } = readBoundReceiptOutcome(agent, step, resolved);
408
+ artifactStallMessage = null;
409
+ const { outcome, receiptRequired, stallMessage } = readBoundReceiptOutcome(agent, step, resolved);
330
410
  if (terminal.has(outcome)) {
331
411
  status.state = outcome;
332
412
  return outcome;
333
413
  }
334
414
  if (receiptRequired) {
415
+ artifactStallMessage = stallMessage || null;
335
416
  status.state = 'awaiting_artifact_receipt';
336
417
  status.phase = 'blocked';
337
418
  return status.state;
@@ -390,6 +471,15 @@ function out(message) {
390
471
  process.stdout.write(JSON.stringify({ followup_message: message }));
391
472
  }
392
473
 
474
+ // The stall text always reaches stderr so a second, different rejection is never
475
+ // silent; `out()` fires only when the stop enters the stall, so the follow-up
476
+ // message cannot loop.
477
+ function emitArtifactStall(message, announce) {
478
+ if (message) process.stderr.write(message + '\n');
479
+ if (message && announce) out(message);
480
+ else process.stdout.write('{}');
481
+ }
482
+
393
483
  function readArtifact(name) {
394
484
  const p = path.join(taskDir, name);
395
485
  if (!fs.existsSync(p)) return '';
@@ -969,10 +1059,11 @@ const completingAgentHint = (() => {
969
1059
  return getStepAgents(initialStep)[0];
970
1060
  })();
971
1061
  const reconcilingAttempt = resolvedAttempt();
1062
+ const wasWaitingForReceipt = status.state === 'awaiting_artifact_receipt';
972
1063
  reconcileStatusFromManifest(completingAgentHint, initialStep, reconcilingAttempt);
973
1064
  if (status.state === 'awaiting_artifact_receipt') {
974
1065
  writeStatus({});
975
- process.stdout.write('{}');
1066
+ emitArtifactStall(artifactStallMessage, !wasWaitingForReceipt);
976
1067
  process.exit(0);
977
1068
  }
978
1069
  let finishedAttempt = finishActiveAttempt();
@@ -982,6 +1073,11 @@ if (!finishedAttempt && activeAttemptCountBeforeFinish > 0) {
982
1073
  if (repaired) {
983
1074
  appendMetric({ type: 'parallel_attribution_repair', at: now, attemptIds: [repaired.attemptId], source: 'hook', attributionConfidence: 'fallback' });
984
1075
  reconcileStatusFromManifest(repaired.entry.agent, steps[repaired.entry.stepIndex], repaired);
1076
+ if (status.state === 'awaiting_artifact_receipt') {
1077
+ writeStatus({});
1078
+ emitArtifactStall(artifactStallMessage, true);
1079
+ process.exit(0);
1080
+ }
985
1081
  finishedAttempt = finishActiveAttempt(repaired);
986
1082
  } else {
987
1083
  writeStatus({});
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "figma": {
16
16
  "type": "http",
17
- "url": "https://mcp.figma.com/mcp"
17
+ "url": "http://127.0.0.1:3845/mcp"
18
18
  }
19
19
  }
20
20
  }