@kontourai/flow-agents 3.2.0 → 3.4.0

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 (281) hide show
  1. package/.github/workflows/add-to-project.yml +15 -0
  2. package/.github/workflows/ci.yml +173 -0
  3. package/CHANGELOG.md +54 -0
  4. package/CONTEXT.md +5 -1
  5. package/README.md +19 -8
  6. package/build/src/builder-flow-run-adapter.d.ts +80 -0
  7. package/build/src/builder-flow-run-adapter.js +241 -0
  8. package/build/src/builder-flow-runtime.d.ts +16 -0
  9. package/build/src/builder-flow-runtime.js +290 -0
  10. package/build/src/cli/assignment-provider.js +10 -1
  11. package/build/src/cli/builder-run.d.ts +1 -0
  12. package/build/src/cli/builder-run.js +27 -0
  13. package/build/src/cli/effective-backlog-settings.js +70 -2
  14. package/build/src/cli/init.d.ts +34 -0
  15. package/build/src/cli/init.js +341 -61
  16. package/build/src/cli/kit.js +55 -12
  17. package/build/src/cli/pull-work-provider.js +346 -5
  18. package/build/src/cli/skill-drift-check.d.ts +1 -0
  19. package/build/src/cli/skill-drift-check.js +165 -0
  20. package/build/src/cli/telemetry-doctor.d.ts +37 -0
  21. package/build/src/cli/telemetry-doctor.js +53 -6
  22. package/build/src/cli/validate-hook-influence.js +37 -7
  23. package/build/src/cli/workflow-artifact-cleanup-audit.js +418 -11
  24. package/build/src/cli/workflow-sidecar.d.ts +310 -1
  25. package/build/src/cli/workflow-sidecar.js +1914 -126
  26. package/build/src/cli.js +5 -0
  27. package/build/src/flow-kit/validate.d.ts +54 -34
  28. package/build/src/flow-kit/validate.js +237 -26
  29. package/build/src/index.d.ts +2 -0
  30. package/build/src/index.js +1 -0
  31. package/build/src/lib/console-connect-options.d.ts +97 -0
  32. package/build/src/lib/console-connect-options.js +199 -0
  33. package/build/src/lib/console-telemetry-validate.d.ts +49 -0
  34. package/build/src/lib/console-telemetry-validate.js +91 -0
  35. package/build/src/lib/flow-resolver.d.ts +54 -1
  36. package/build/src/lib/flow-resolver.js +112 -5
  37. package/build/src/lib/fs.d.ts +17 -0
  38. package/build/src/lib/fs.js +172 -0
  39. package/build/src/lib/local-artifact-root.d.ts +44 -1
  40. package/build/src/lib/local-artifact-root.js +131 -3
  41. package/build/src/runtime-adapters.d.ts +39 -3
  42. package/build/src/runtime-adapters.js +77 -31
  43. package/build/src/tools/build-universal-bundles.js +40 -2
  44. package/build/src/tools/codex-agent-routing.d.ts +2 -0
  45. package/build/src/tools/codex-agent-routing.js +49 -0
  46. package/build/src/tools/generate-context-map.js +1 -0
  47. package/build/src/tools/validate-source-tree.js +30 -3
  48. package/context/contracts/artifact-contract.md +16 -2
  49. package/context/scripts/hooks/lib/kit-catalog.js +235 -0
  50. package/context/scripts/hooks/lib/runnable-command.js +177 -0
  51. package/context/scripts/hooks/stop-goal-fit.js +278 -48
  52. package/context/scripts/hooks/workflow-steering.js +194 -22
  53. package/context/scripts/package.json +3 -0
  54. package/context/scripts/telemetry/install-console-config.sh +25 -4
  55. package/context/scripts/telemetry/lib/config.sh +102 -12
  56. package/context/scripts/telemetry/lib/pricing.sh +50 -0
  57. package/context/scripts/telemetry/lib/session.sh +3 -0
  58. package/context/scripts/telemetry/lib/transport.sh +87 -0
  59. package/context/scripts/telemetry/lib/usage.sh +205 -4
  60. package/context/scripts/telemetry/telemetry.conf +6 -0
  61. package/context/scripts/telemetry/telemetry.sh +48 -0
  62. package/context/settings/workspace-backlog-provider-settings.example.json +48 -0
  63. package/docs/agent-usage-feedback-loop.md +35 -0
  64. package/docs/architecture-engine-and-kits.md +110 -0
  65. package/docs/context-map.md +2 -0
  66. package/docs/coordination-guide.md +370 -0
  67. package/docs/decisions/agent-coordination.md +26 -9
  68. package/docs/decisions/embeddable-engine.md +152 -0
  69. package/docs/decisions/index.md +5 -3
  70. package/docs/decisions/trust-ledger-retention.md +88 -0
  71. package/docs/decisions/trust-reconcile.md +42 -9
  72. package/docs/decisions/workflow-enforcement.md +31 -9
  73. package/docs/fixture-ownership.md +6 -2
  74. package/docs/implementing-trust-reconciliation.md +129 -0
  75. package/docs/index.md +23 -9
  76. package/docs/integrations/flow-agents-console.md +275 -0
  77. package/docs/integrations/index.md +4 -0
  78. package/docs/kit-authoring-guide.md +52 -21
  79. package/docs/spec/builder-flow-runtime.md +80 -0
  80. package/docs/spec/runtime-hook-surface.md +45 -1
  81. package/docs/specs/economics-record-contract.md +270 -0
  82. package/docs/specs/harness-capability-matrix.md +74 -0
  83. package/docs/specs/learning-review-proposals-contract.md +340 -0
  84. package/docs/specs/routing-efficiency-review.md +59 -0
  85. package/docs/verifiable-trust.md +74 -25
  86. package/docs/workflow-artifact-lifecycle.md +38 -1
  87. package/docs/workflow-usage-guide.md +10 -0
  88. package/evals/acceptance/prove-capture-teeth.sh +132 -0
  89. package/evals/ci/antigaming-suite.sh +2 -0
  90. package/evals/ci/run-baseline.sh +78 -4
  91. package/evals/fixtures/economics/acceptance.json +12 -0
  92. package/evals/fixtures/economics/agents/tool-worker-1/events.jsonl +2 -0
  93. package/evals/fixtures/economics/agents/tool-worker-2/events.jsonl +2 -0
  94. package/evals/fixtures/economics/agents/tool-worker-3/events.jsonl +2 -0
  95. package/evals/fixtures/economics/agents/tool-worker-4/events.jsonl +1 -0
  96. package/evals/fixtures/economics/agents/tool-worker-5/events.jsonl +2 -0
  97. package/evals/fixtures/economics/critique.json +22 -0
  98. package/evals/fixtures/economics/expected-record.json +71 -0
  99. package/evals/fixtures/economics/session-usage-event.json +1 -0
  100. package/evals/fixtures/economics/state.json +11 -0
  101. package/evals/fixtures/economics/transcript.jsonl +3 -0
  102. package/evals/fixtures/hook-influence/cases.json +7 -7
  103. package/evals/fixtures/learning-review-proposals/balanced/economics.jsonl +6 -0
  104. package/evals/fixtures/learning-review-proposals/effect-follow-up/economics.jsonl +5 -0
  105. package/evals/fixtures/learning-review-proposals/effect-follow-up/sessions/task-lr-ef-1/trust.bundle +21 -0
  106. package/evals/fixtures/learning-review-proposals/effect-follow-up/sessions/task-lr-ef-2/trust.bundle +21 -0
  107. package/evals/fixtures/learning-review-proposals/effect-follow-up/sessions/task-lr-ef-3/trust.bundle +21 -0
  108. package/evals/fixtures/learning-review-proposals/effect-follow-up/sessions/task-lr-ef-4/trust.bundle +21 -0
  109. package/evals/fixtures/learning-review-proposals/effect-follow-up/sessions/task-lr-ef-5/trust.bundle +21 -0
  110. package/evals/fixtures/learning-review-proposals/pattern-present/economics.jsonl +6 -0
  111. package/evals/fixtures/learning-review-proposals/pattern-present/expected-aggregates.json +30 -0
  112. package/evals/fixtures/learning-review-proposals/pattern-present/expected-aggregates.md +66 -0
  113. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-1/gate-review.inquiries.json +26 -0
  114. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-1/trust.bundle +21 -0
  115. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-2/gate-review.inquiries.json +26 -0
  116. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-2/trust.bundle +21 -0
  117. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-3/gate-review.inquiries.json +26 -0
  118. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-3/trust.bundle +21 -0
  119. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-4/gate-review.inquiries.json +26 -0
  120. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-4/trust.bundle +21 -0
  121. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-5/trust.bundle +21 -0
  122. package/evals/fixtures/learning-review-proposals/pattern-present/sessions/task-lr-pp-6/trust.bundle +21 -0
  123. package/evals/fixtures/learning-review-proposals/repeat-window/economics.jsonl +6 -0
  124. package/evals/fixtures/learning-review-proposals/under-threshold/economics.jsonl +3 -0
  125. package/evals/fixtures/reconcile-preflight/disputed-critique-unsuperseded.json +48 -0
  126. package/evals/fixtures/reconcile-preflight/standalone-disputed-session-local.json +59 -0
  127. package/evals/fixtures/telemetry/usage-transcript-sample.jsonl +4 -0
  128. package/evals/fixtures/trust-reconcile-exploits/mcp-degrade.json +42 -0
  129. package/evals/integration/test_builder_entry_enforcement.sh +241 -0
  130. package/evals/integration/test_builder_step_producers.sh +18 -10
  131. package/evals/integration/test_bundle_install.sh +172 -0
  132. package/evals/integration/test_checkpoint_signing.sh +10 -2
  133. package/evals/integration/test_ci_actor_identity.sh +221 -0
  134. package/evals/integration/test_console_tenant_isolation.sh +167 -0
  135. package/evals/integration/test_critique_supersession_roundtrip.sh +4 -1
  136. package/evals/integration/test_dual_emit_flow_step.sh +10 -4
  137. package/evals/integration/test_economics_record.sh +674 -0
  138. package/evals/integration/test_effective_backlog_settings.sh +1 -1
  139. package/evals/integration/test_evidence_capture_hook.sh +17 -2
  140. package/evals/integration/test_exemption_usage_review.sh +198 -0
  141. package/evals/integration/test_fixture_retirement_audit.sh +2 -2
  142. package/evals/integration/test_flow_kit_install_git.sh +83 -0
  143. package/evals/integration/test_flowdef_session_activation.sh +0 -1
  144. package/evals/integration/test_flowdef_session_history_preservation.sh +13 -3
  145. package/evals/integration/test_gate_lockdown.sh +7 -0
  146. package/evals/integration/test_gate_review_inquiry_records.sh +9 -1
  147. package/evals/integration/test_goal_fit_hook.sh +2031 -0
  148. package/evals/integration/test_hook_category_behaviors.sh +8 -1
  149. package/evals/integration/test_hook_influence_cases.sh +25 -1
  150. package/evals/integration/test_install_merge.sh +227 -2
  151. package/evals/integration/test_kit_conformance_levels.sh +6 -6
  152. package/evals/integration/test_learning_review_proposals.sh +329 -0
  153. package/evals/integration/test_liveness_conflict_injection.sh +26 -22
  154. package/evals/integration/test_liveness_console_relay.sh +166 -0
  155. package/evals/integration/test_liveness_heartbeat.sh +17 -17
  156. package/evals/integration/test_liveness_worktree_root.sh +575 -0
  157. package/evals/integration/test_phase_map_and_gate_claim.sh +6 -1
  158. package/evals/integration/test_publish_delivery.sh +389 -2
  159. package/evals/integration/test_pull_work_board.sh +200 -0
  160. package/evals/integration/test_pull_work_provider.sh +1 -1
  161. package/evals/integration/test_reconcile_preflight.sh +304 -0
  162. package/evals/integration/test_record_check.sh +378 -0
  163. package/evals/integration/test_routing_efficiency.sh +71 -0
  164. package/evals/integration/test_runtime_adapter_activation.sh +28 -0
  165. package/evals/integration/test_session_resume_roundtrip.sh +16 -19
  166. package/evals/integration/test_skill_drift_check.sh +870 -0
  167. package/evals/integration/test_takeover_protocol.sh +340 -0
  168. package/evals/integration/test_telemetry.sh +445 -0
  169. package/evals/integration/test_telemetry_doctor.sh +66 -0
  170. package/evals/integration/test_telemetry_usage_pipeline.sh +228 -0
  171. package/evals/integration/test_trust_reconcile_negatives.sh +121 -13
  172. package/evals/integration/test_trust_reconcile_trailer_diagnostic.sh +247 -0
  173. package/evals/integration/test_usage_cost.sh +61 -0
  174. package/evals/integration/test_verify_hold.sh +910 -0
  175. package/evals/integration/test_veritas_governance_kit.sh +257 -0
  176. package/evals/integration/test_workflow_artifact_cleanup_audit.sh +575 -3
  177. package/evals/integration/test_workflow_sidecar_writer.sh +1395 -0
  178. package/evals/integration/test_workflow_steering_hook.sh +157 -16
  179. package/evals/integration/test_workspace_settings.sh +176 -0
  180. package/evals/lib/env.sh +26 -0
  181. package/evals/lib/node.sh +8 -0
  182. package/evals/run.sh +37 -0
  183. package/evals/static/test_ci_integration_coverage.sh +115 -0
  184. package/evals/static/test_declared_scope_forms_documented.sh +114 -0
  185. package/evals/static/test_universal_bundles.sh +34 -0
  186. package/evals/static/test_validate_source_kit_asset_scope.sh +259 -0
  187. package/evals/static/test_workflow_skills.sh +1 -1
  188. package/kits/builder/flows/build.flow.json +9 -18
  189. package/kits/builder/flows/publish-learn.flow.json +5 -1
  190. package/kits/builder/kit.json +120 -0
  191. package/kits/builder/skills/continue-work/SKILL.md +2 -0
  192. package/kits/builder/skills/deliver/SKILL.md +115 -0
  193. package/kits/builder/skills/evidence-gate/SKILL.md +12 -0
  194. package/kits/builder/skills/execute-plan/SKILL.md +9 -0
  195. package/kits/builder/skills/learning-review/SKILL.md +51 -0
  196. package/kits/builder/skills/plan-work/SKILL.md +17 -20
  197. package/kits/builder/skills/pull-work/SKILL.md +33 -2
  198. package/kits/builder/skills/release-readiness/SKILL.md +12 -0
  199. package/kits/knowledge/kit.json +9 -0
  200. package/kits/veritas-governance/docs/README.md +113 -7
  201. package/kits/veritas-governance/fixtures/exemption/approved.trust-bundle.json +74 -0
  202. package/kits/veritas-governance/fixtures/exemption/not-approved.trust-bundle.json +74 -0
  203. package/kits/veritas-governance/fixtures/exemption-review/mixed-fresh-stale.DECLARED.json +14 -0
  204. package/kits/veritas-governance/flows/exemption-issuance.flow.json +35 -0
  205. package/kits/veritas-governance/kit.json +19 -0
  206. package/kits/veritas-governance/skills/exemption-usage-review/SKILL.md +128 -0
  207. package/kits/veritas-governance/skills/exemption-usage-review/review-exemptions.mjs +231 -0
  208. package/package.json +2 -2
  209. package/packaging/manifest.json +29 -0
  210. package/schemas/backlog-provider-settings.schema.json +13 -0
  211. package/schemas/workflow-state.schema.json +44 -0
  212. package/scripts/README.md +4 -0
  213. package/scripts/check-content-boundary.cjs +8 -1
  214. package/scripts/ci/trust-reconcile.js +214 -253
  215. package/scripts/hooks/codex-hook-adapter.js +77 -2
  216. package/scripts/hooks/evidence-capture.js +38 -5
  217. package/scripts/hooks/lib/actor-identity.js +82 -0
  218. package/scripts/hooks/lib/codex-exit-code.js +316 -0
  219. package/scripts/hooks/lib/kit-catalog.js +235 -0
  220. package/scripts/hooks/lib/liveness-write.js +28 -1
  221. package/scripts/hooks/lib/local-artifact-paths.js +97 -1
  222. package/scripts/hooks/lib/runnable-command.js +177 -0
  223. package/scripts/hooks/lib/skill-drift.js +350 -0
  224. package/scripts/hooks/stop-goal-fit.js +278 -48
  225. package/scripts/hooks/workflow-steering.js +194 -22
  226. package/scripts/install-codex-home.sh +97 -47
  227. package/scripts/install-merge.js +72 -14
  228. package/scripts/install-owned-files.js +178 -0
  229. package/scripts/lib/reconcile-shape.js +381 -0
  230. package/scripts/liveness/relay.sh +84 -0
  231. package/scripts/telemetry/economics-record.schema.json +145 -0
  232. package/scripts/telemetry/economics-record.sh +331 -0
  233. package/scripts/telemetry/install-console-config.sh +25 -4
  234. package/scripts/telemetry/learning-review-decide.sh +124 -0
  235. package/scripts/telemetry/learning-review-proposals.schema.json +161 -0
  236. package/scripts/telemetry/learning-review-proposals.sh +484 -0
  237. package/scripts/telemetry/lib/config.sh +102 -12
  238. package/scripts/telemetry/lib/pricing.sh +14 -6
  239. package/scripts/telemetry/lib/session.sh +3 -0
  240. package/scripts/telemetry/lib/transport.sh +133 -15
  241. package/scripts/telemetry/lib/usage.sh +121 -28
  242. package/scripts/telemetry/routing-efficiency.sh +0 -0
  243. package/scripts/telemetry/telemetry.conf +6 -0
  244. package/scripts/telemetry/telemetry.sh +48 -0
  245. package/src/builder-flow-run-adapter.ts +357 -0
  246. package/src/builder-flow-runtime.ts +348 -0
  247. package/src/cli/assignment-provider.ts +12 -1
  248. package/src/cli/builder-flow-run-adapter.test.mjs +495 -0
  249. package/src/cli/builder-flow-runtime.test.mjs +213 -0
  250. package/src/cli/builder-run.ts +28 -0
  251. package/src/cli/codex-agent-routing.test.mjs +44 -0
  252. package/src/cli/codex-exit-code.test.mjs +207 -0
  253. package/src/cli/console-connect-options.test.mjs +329 -0
  254. package/src/cli/console-telemetry-validate.test.mjs +157 -0
  255. package/src/cli/effective-backlog-settings.ts +68 -2
  256. package/src/cli/flow-resolver-composition.test.mjs +72 -0
  257. package/src/cli/init.test.mjs +161 -0
  258. package/src/cli/init.ts +407 -62
  259. package/src/cli/kit-metadata-security.test.mjs +443 -0
  260. package/src/cli/kit.ts +50 -12
  261. package/src/cli/pull-work-provider.ts +377 -3
  262. package/src/cli/sidecar-pure-helpers.test.mjs +64 -0
  263. package/src/cli/skill-drift-check.ts +196 -0
  264. package/src/cli/telemetry-doctor.test.mjs +53 -0
  265. package/src/cli/telemetry-doctor.ts +50 -7
  266. package/src/cli/validate-hook-influence.ts +37 -6
  267. package/src/cli/workflow-artifact-cleanup-audit.ts +483 -10
  268. package/src/cli/workflow-sidecar.ts +1980 -119
  269. package/src/cli.ts +5 -0
  270. package/src/flow-kit/validate.ts +277 -38
  271. package/src/index.ts +19 -0
  272. package/src/lib/console-connect-options.ts +261 -0
  273. package/src/lib/console-telemetry-validate.ts +88 -0
  274. package/src/lib/flow-resolver.ts +117 -4
  275. package/src/lib/fs.ts +160 -0
  276. package/src/lib/local-artifact-root.ts +129 -3
  277. package/src/runtime-adapters.ts +113 -33
  278. package/src/tools/build-universal-bundles.ts +36 -2
  279. package/src/tools/codex-agent-routing.ts +48 -0
  280. package/src/tools/generate-context-map.ts +1 -0
  281. package/src/tools/validate-source-tree.ts +29 -3
@@ -2,13 +2,14 @@
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
- import { execFileSync } from "node:child_process";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
6
  import { createHash } from "node:crypto";
7
7
  import { createRequire } from "node:module";
8
8
  import { fileURLToPath } from "node:url";
9
9
  // ADR 0016 Abstraction A: shared FlowDefinition resolver (P-a)
10
- import { resolveActiveFlowStep, resolveFlowFilePath, resolvePhaseMap, resolveRouteBackPolicy } from "../lib/flow-resolver.js";
10
+ import { resolveActiveFlowStep, resolveAllFlowGateExpects, resolveFlowFilePath, resolvePhaseMap, resolveRouteBackPolicy } from "../lib/flow-resolver.js";
11
11
  import { defaultArtifactRootForRead, flowAgentsArtifactRoot } from "../lib/local-artifact-root.js";
12
+ import { syncBuilderFlowSessionIfPresent } from "../builder-flow-runtime.js";
12
13
  // #291 Wave 1 Task 1.1 exports: ensure-session's ownership guard reuses the EXACT same
13
14
  // assignment ⋈ liveness join / claim / supersede logic #290 already ships for the
14
15
  // `assignment-provider` CLI, rather than reimplementing a second, parallel join (static ESM
@@ -54,6 +55,32 @@ function workItemSlug(ref) {
54
55
  const [owner, repo] = parts;
55
56
  return slugify(`${owner}-${repo}-${id}`, "work-item");
56
57
  }
58
+ function sessionWorkItem(p, slug, dir) {
59
+ const providerRef = opt(p, "work-item");
60
+ if (providerRef) {
61
+ return { ref: providerRef };
62
+ }
63
+ const existingState = loadJson(path.join(dir, "state.json"));
64
+ if (Array.isArray(existingState.work_item_refs) && typeof existingState.work_item_refs[0] === "string") {
65
+ return { ref: existingState.work_item_refs[0] };
66
+ }
67
+ const title = opt(p, "title", slug).trim() || slug;
68
+ const body = opt(p, "summary").trim();
69
+ return {
70
+ ref: `local:${slug}`,
71
+ localRecord: {
72
+ id: slug,
73
+ title,
74
+ ...(body ? { body } : {}),
75
+ status: "ready",
76
+ source_provider: {
77
+ kind: "local",
78
+ path: "work-item.json",
79
+ },
80
+ artifact_refs: ["state.json", "handoff.json"],
81
+ },
82
+ };
83
+ }
57
84
  /** Pure, lock-free, side-effect-free CLI wrapper around workItemSlug() — the single source of
58
85
  * truth for the deterministic subjectId/session-directory-name slug. Named resolveSlugCmd (not
59
86
  * resolveSlug) to avoid colliding with any future export named resolveSlug. */
@@ -230,9 +257,17 @@ function resolveEnsureSessionActor(p) {
230
257
  // the ownership guard entirely when unresolved, rather than claiming under a synthetic identity.
231
258
  return { actorStruct: { runtime: "unresolved", session_id: branchActorKey, host: os.hostname() }, actorKey: resolved.actor, branchActorKey, unresolved: true };
232
259
  }
260
+ // #398: the CI-runtime tier must reconstruct the SAME struct resolveActor serialized, or
261
+ // `serializeActor(actorStruct)` would diverge from `resolved.actor` (the else-branch would rebuild
262
+ // an ANCESTRY struct — detectRuntime→unknown, runtimeSessionId→'' — so the claim's stored
263
+ // actor_key would not match the CI actor at publish → self not recognized → false-block, the exact
264
+ // bug this issue removes). Uses the SAME helper.detectCiActor as resolveActor, single-sourced.
265
+ const ciActor = resolved.source.startsWith("ci-runtime") ? helper.detectCiActor(process.env) : null;
233
266
  const actorStruct = resolved.source === "explicit-override"
234
267
  ? { runtime: "explicit-override", session_id: resolved.actor, host: os.hostname() }
235
- : { runtime: helper.detectRuntime(process.env), session_id: helper.runtimeSessionId(process.env) || (() => { const seed = helper.ancestorActorSeed(); return seed ? `anc-${seed}` : ""; })(), host: os.hostname() };
268
+ : ciActor && ciActor.session_id
269
+ ? { runtime: ciActor.runtime, session_id: ciActor.session_id, host: os.hostname() }
270
+ : { runtime: helper.detectRuntime(process.env), session_id: helper.runtimeSessionId(process.env) || (() => { const seed = helper.ancestorActorSeed(); return seed ? `anc-${seed}` : ""; })(), host: os.hostname() };
236
271
  const actorKey = helper.serializeActor(actorStruct);
237
272
  return { actorStruct, actorKey, branchActorKey, unresolved: false };
238
273
  }
@@ -463,6 +498,68 @@ function critiqueToEventStatus(verdict, findings) {
463
498
  return "assumed";
464
499
  return null; // not_verified or unknown → no event → Surface returns "unknown"
465
500
  }
501
+ /**
502
+ * Fold a raw command-log (command-log.jsonl entries) into a per-command classification,
503
+ * keyed by normalized command text (whitespace-collapsed, trimmed). Pure and side-effect-free
504
+ * so it is directly unit-testable (#470 iteration 2, finding #2 — HIGH: the prior inline reducer
505
+ * collapsed every non-"fail" `observedResult` — including "ambiguous" — to "pass", feeding a
506
+ * verified event + `passing:true` and reintroducing the #470 false-pass through the trust-bundle
507
+ * reconciliation path).
508
+ *
509
+ * Three-way classification, keyed on `observedResult` (never re-derived from `exitCode` alone,
510
+ * which would miscoerce the #362 grep/diff absence carve-out `ambiguous,exitCode:1` entry to
511
+ * `fail`):
512
+ * - "fail" when `observedResult==="fail"`, or (legacy, no observedResult) a nonzero
513
+ * integer `exitCode`.
514
+ * - "ambiguous" when `observedResult==="ambiguous"`, or (legacy) `exitCode` is `null` with no
515
+ * fail signal.
516
+ * - "pass" when `observedResult==="pass"`, or (legacy) `exitCode===0`.
517
+ *
518
+ * Precedence across repeated entries for the same command: fail > pass > ambiguous. A genuine
519
+ * exit-0 pass is positive evidence and confirms; ambiguous holds only when there is neither a
520
+ * fail nor a positive pass, since a "pass" always requires positive evidence.
521
+ *
522
+ * The caller (buildTrustBundle) maps "ambiguous" onto the existing canonical non-confirming
523
+ * status `not_verified` — consume-never-fork, mirroring record-check's identical mapping — so
524
+ * `checkStatusToEventStatus("not_verified")` returns null (no verification event emitted) and the
525
+ * evidence item is stamped `passing:false`. See Decision/finding #2 in the iteration-2 plan.
526
+ */
527
+ export function reduceCaptureLogByCommand(commandLog) {
528
+ const captureByCommand = new Map();
529
+ for (const entry of Array.isArray(commandLog) ? commandLog : []) {
530
+ if (!entry || typeof entry.command !== "string")
531
+ continue;
532
+ const key = entry.command.replace(/\s+/g, " ").trim();
533
+ if (!key)
534
+ continue;
535
+ const exitCode = Number.isInteger(entry.exitCode) ? entry.exitCode : null;
536
+ let result;
537
+ if (entry.observedResult === "fail" || (entry.observedResult === undefined && exitCode !== null && exitCode !== 0)) {
538
+ result = "fail";
539
+ }
540
+ else if (entry.observedResult === "pass" || (entry.observedResult === undefined && exitCode === 0)) {
541
+ result = "pass";
542
+ }
543
+ else {
544
+ // Covers observedResult==="ambiguous" AND the legacy no-observedResult, exitCode:null case.
545
+ result = "ambiguous";
546
+ }
547
+ const prev = captureByCommand.get(key);
548
+ let merged = result;
549
+ if (prev) {
550
+ // fail > pass > ambiguous precedence.
551
+ if (prev.observedResult === "fail" || result === "fail")
552
+ merged = "fail";
553
+ else if (prev.observedResult === "pass" || result === "pass")
554
+ merged = "pass";
555
+ else
556
+ merged = "ambiguous";
557
+ }
558
+ const mergedExitCode = exitCode !== null ? exitCode : (prev ? prev.exitCode : null);
559
+ captureByCommand.set(key, { observedResult: merged, exitCode: mergedExitCode });
560
+ }
561
+ return captureByCommand;
562
+ }
466
563
  /**
467
564
  * Build a Hachure trust.bundle from raw check/criterion/critique inputs.
468
565
  * trust.bundle is the PRIMARY artifact (ADR 0010 Phase 4a producer inversion).
@@ -490,6 +587,114 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
490
587
  // writeTrustBundle below) threads through to resolveActiveFlowStep's per-actor-first,
491
588
  // legacy-fallback current.json read; omitted, this is IDENTICAL to pre-#291 behavior.
492
589
  const activeStep = flowAgentsDir ? resolveActiveFlowStep(flowAgentsDir, actorKey) : null;
590
+ // #270 CRITICAL/HIGH fix: resolve the session's active_flow_id independent of whether the
591
+ // CURRENTLY-active step resolves — a stamped gate claim names the STEP IT WAS ORIGINALLY
592
+ // RECORDED AT (frozen in metadata.gate_claim.step_id), which is routinely a DIFFERENT step than
593
+ // whatever is active now. Validating the stamp against only the currently-active step's
594
+ // expects[] would reject every honest round-trip the moment the session advances past the step
595
+ // the gate claim was recorded at — the validation must be against the FULL flow definition
596
+ // (every step's gate expects[], via resolveAllFlowGateExpects), not just the active one.
597
+ const sessionFlowId = (() => {
598
+ if (!flowAgentsDir)
599
+ return null;
600
+ try {
601
+ const pointer = loadCurrentPointerHelper().readCurrentPointer(flowAgentsDir, actorKey);
602
+ const payload = pointer.payload;
603
+ const fid = payload && typeof payload["active_flow_id"] === "string" ? payload["active_flow_id"] : null;
604
+ return fid && fid.length > 0 ? fid : null;
605
+ }
606
+ catch {
607
+ return null;
608
+ }
609
+ })();
610
+ const workflowSubjectRef = (() => {
611
+ if (!flowAgentsDir)
612
+ return null;
613
+ try {
614
+ const state = loadJson(path.join(flowAgentsDir, slug, "state.json"));
615
+ const refs = Array.isArray(state.work_item_refs) ? state.work_item_refs : [];
616
+ return refs.length === 1 && typeof refs[0] === "string" && refs[0].length > 0 ? refs[0] : null;
617
+ }
618
+ catch {
619
+ return null;
620
+ }
621
+ })();
622
+ // repoRoot resolution mirrors resolveActiveFlowStep's own internal findRepoRoot(path.dirname(
623
+ // flowAgentsDir)) call exactly (flow-resolver.ts) — findRepoRootFromDir is this file's
624
+ // fallback-to-cwd equivalent of that unexported helper. NOTE (#270 MEDIUM fix, iteration 3):
625
+ // findRepoRootFromDir ALWAYS returns a truthy string (it falls back to process.cwd() — see
626
+ // findRepoRootFromDir's own doc comment above) whenever flowAgentsDir is set, so `flowRepoRoot`
627
+ // is only ever null when `!flowAgentsDir`. It can therefore never by itself signal a FlowDefinition
628
+ // load failure; that signal now comes from resolveAllFlowGateExpects's own null return (below).
629
+ const flowRepoRoot = flowAgentsDir ? findRepoRootFromDir(path.dirname(flowAgentsDir)) : null;
630
+ // Built lazily (only when at least one check actually carries a metadata.gate_claim stamp or
631
+ // gate-claim shape to validate) and cached across every check in this call's loop — the
632
+ // FlowDefinition file is read once per buildTrustBundle call, not once per claim.
633
+ //
634
+ // #270 MEDIUM fix (iteration 3): tri-state cache — `undefined` (not yet built), `null` (the
635
+ // FlowDefinition could not be loaded/parsed — see resolveAllFlowGateExpects's doc comment),
636
+ // or an array (loaded; possibly genuinely empty). This lets assertStampedGateClaimValid tell
637
+ // "cannot load the flow definition" apart from "loaded fine, tuple just doesn't match" — the
638
+ // previous code collapsed both into `[]`, which always failed the `.some()` match below and
639
+ // was misreported as "forged or corrupt" even when the real cause was an unloadable
640
+ // FlowDefinition (e.g. a bogus/renamed active_flow_id, or a `kits/` path that no longer
641
+ // resolves) — a `!flowRepoRoot` check can never catch this because flowRepoRoot is always
642
+ // truthy here (see the note above), so that check was dead code against this failure mode.
643
+ let _allGateExpectsCache = undefined;
644
+ const allGateExpectsForSession = () => {
645
+ if (_allGateExpectsCache !== undefined)
646
+ return _allGateExpectsCache;
647
+ _allGateExpectsCache = (sessionFlowId && flowRepoRoot) ? resolveAllFlowGateExpects(sessionFlowId, flowRepoRoot) : null;
648
+ return _allGateExpectsCache;
649
+ };
650
+ /**
651
+ * Validate a RESTORED metadata.gate_claim stamp's (expectation_id, claim_type, subject_type,
652
+ * step_id) tuple against the session's FULL flow definition (every step's gate expects[], not
653
+ * just the currently-active step). This is the honest round-trip check: a claim recorded by
654
+ * record-gate-claim/buildTrustBundle can only ever carry a tuple that matches some real
655
+ * expects[] entry, because that is the only place the stamp is ever written (see the
656
+ * declaredMetadata.gate_claim assembly below). A tuple that does NOT match a real expectation is
657
+ * either FORGED (a hand-edited/attacker-supplied metadata.gate_claim) or CORRUPT — never a
658
+ * legitimate state this code can produce — so it dies loudly naming the claim id and the
659
+ * invalid stamp. It must NEVER fall through to matchExpectsEntry: that silent fall-through
660
+ * IS the re-typing bug this fix closes (a forged/corrupt stamp would otherwise get a fresh,
661
+ * heuristic-derived typing instead of being rejected).
662
+ *
663
+ * Accepted residual (#270, documented not fixed — iteration 3): this check validates
664
+ * STRUCTURAL conformance of the stamp's tuple against the flow definition's declared
665
+ * expects[] shape — it does not (and cannot, at this layer) verify WHO produced the stamp. A
666
+ * stamp that reuses a REAL (expectation_id, claim_type, subject_type, step_id) tuple copied
667
+ * from a legitimately-earned claim will PASS this validation, because it is, structurally,
668
+ * indistinguishable from an honest one. This is an accepted floor equal to the pre-existing
669
+ * trust boundary: any local process with filesystem access to this session already has an
670
+ * equivalent capability by invoking record-gate-claim directly. This validator closes the
671
+ * STRICTLY WORSE case — a forged tuple that does NOT correspond to any real expects[] entry,
672
+ * or a stamp silently re-typed via matchExpectsEntry's heuristic fallback — not general
673
+ * authorship/provenance binding. Provenance binding (e.g. cryptographically tying a stamp to
674
+ * the actor/process that recorded it) is future work; see issue #270's review thread.
675
+ *
676
+ * #270 MEDIUM fix (iteration 3): a DIFFERENT failure class — the FlowDefinition genuinely
677
+ * cannot be loaded/parsed (missing kits/ file, unreadable, invalid JSON, or a since-renamed/
678
+ * bogus active_flow_id) — must NEVER be reported as "forged or corrupt"; that message asserts
679
+ * the stamp itself is untrustworthy, which is not what happened here. This case dies with its
680
+ * own dedicated, distinctly-worded message instead.
681
+ */
682
+ function assertStampedGateClaimValid(claimId, stamp) {
683
+ if (!sessionFlowId) {
684
+ die(`buildTrustBundle: claim '${claimId}' carries a metadata.gate_claim stamp (expectation_id='${stamp.expectationId}') but no flow definition is resolvable for this session (no active_flow_id) — a stamped gate claim cannot be validated without the flow definition it was recorded against. This is either a legacy non-flow session or a missing --flow-id; re-record the gate claim inside a session with a resolvable --flow-id.`);
685
+ }
686
+ const allExpects = allGateExpectsForSession();
687
+ if (allExpects === null) {
688
+ die(`buildTrustBundle: claim '${claimId}' carries a metadata.gate_claim stamp (expectation_id='${stamp.expectationId}') naming flow '${sessionFlowId}', but FlowDefinition '${sessionFlowId}' cannot be loaded — cannot validate the gate-claim stamp. This is a load/parse failure (missing FlowDefinition file, unreadable, invalid JSON, or a renamed/bogus active_flow_id) — never treat this as a forged stamp. Restore or correct the '${sessionFlowId}' FlowDefinition (or the session's active_flow_id) before this claim can be validated.`);
689
+ }
690
+ const match = allExpects.some((entry) => entry.gateExpects.some((exp) => exp.id === stamp.expectationId
691
+ && exp.bundle_claim.claimType === stamp.claimType
692
+ && exp.bundle_claim.subjectType === stamp.subjectType
693
+ && (stamp.stepId === null || stamp.stepId === entry.stepId)));
694
+ if (!match) {
695
+ die(`buildTrustBundle: claim '${claimId}' carries a metadata.gate_claim stamp that does not match any expects[] entry declared in the '${sessionFlowId}' flow definition (expectation_id='${stamp.expectationId}', claim_type='${stamp.claimType}', subject_type='${stamp.subjectType}', step_id='${stamp.stepId ?? "<none>"}'). This stamp is forged or corrupt — it can never legitimately fail validation, since it is only ever written by this same code against a real expects[] entry. Refusing to trust it; never silently re-typing via matchExpectsEntry.`);
696
+ }
697
+ }
493
698
  const claims = [];
494
699
  const evidenceItems = [];
495
700
  const events = [];
@@ -520,19 +725,15 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
520
725
  }
521
726
  return p;
522
727
  };
523
- // Index the deterministic capture log by normalized command (a single FAIL wins),
524
- // so a claimed-pass check whose command actually FAILED becomes authoritative here.
525
- const captureByCommand = new Map();
526
- for (const entry of Array.isArray(commandLog) ? commandLog : []) {
527
- if (!entry || typeof entry.command !== "string")
528
- continue;
529
- const key = entry.command.replace(/\s+/g, " ").trim();
530
- if (!key)
531
- continue;
532
- const failed = entry.observedResult === "fail" || (Number.isInteger(entry.exitCode) && entry.exitCode !== 0);
533
- const prev = captureByCommand.get(key);
534
- captureByCommand.set(key, { observedResult: failed || (prev && prev.observedResult === "fail") ? "fail" : "pass", exitCode: Number.isInteger(entry.exitCode) ? entry.exitCode : (prev ? prev.exitCode : null) });
535
- }
728
+ // Index the deterministic capture log by normalized command (fail > pass > ambiguous
729
+ // precedence wins across repeated entries for the same command), so a claimed-pass check
730
+ // whose command actually FAILED (or never produced usable signal) becomes authoritative here.
731
+ // Extracted to reduceCaptureLogByCommand (below) for direct unit testing (#470 iteration 2,
732
+ // finding #2): the three-way classification is keyed on `observedResult`, NEVER re-derived
733
+ // from `exitCode` alone, so an `ambiguous,exitCode:1` entry (the #362 grep/diff absence
734
+ // carve-out) is never miscoerced to `fail` here, and a no-signal `ambiguous` (exitCode:null)
735
+ // is never coerced to `pass`.
736
+ const captureByCommand = reduceCaptureLogByCommand(commandLog);
536
737
  // ─── P-b dual-emit helper ──────────────────────────────────────────────────
537
738
  // Semantic matching table (ADR 0016 Abstraction A P-b):
538
739
  // check (non-policy kind) → expects[] entry where claimType does NOT contain
@@ -650,18 +851,75 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
650
851
  ? { evidenceType: "attestation", method: "attestation", reconcilable: false }
651
852
  : classifyEvidence(check.kind, cmd.length > 0);
652
853
  const policy = ensurePolicy(legacyClaimType, "high", [evClass.evidenceType]);
653
- const effectiveStatus = captured ? captured.observedResult : String(check.status ?? "");
854
+ // #470 iteration 2, finding #2: an "ambiguous" capture (no positive pass/fail signal —
855
+ // e.g. the codex no-signal default, or the #362 grep/diff absence carve-out) is
856
+ // non-confirming and must never be surfaced as a claim value of "pass". Map it onto the
857
+ // EXISTING canonical non-confirming status "not_verified" (consume-never-fork; the same
858
+ // mapping record-check already applies at its `ambiguous` branch above) so
859
+ // checkStatusToEventStatus("not_verified") returns null — no verification event, and the
860
+ // evidence item below is stamped passing:false. `isError` stays fail-only (ambiguous is
861
+ // not an error).
862
+ const effectiveStatus = captured ? (captured.observedResult === "ambiguous" ? "not_verified" : captured.observedResult) : String(check.status ?? "");
654
863
  const evStatus = waiver ? "assumed" : checkStatusToEventStatus(effectiveStatus);
655
864
  // Promotion claim marker (issue #312): a `promote` check carries a session-local
656
865
  // _promotion object that must survive onto claim.metadata.promotion so the archive gate
657
866
  // (workflow-artifact-cleanup-audit) and validators can detect the promotion claim without a
658
867
  // new manifest entry. It rides alongside any waiver in a single merged metadata object.
659
868
  const promotionMeta = (check._promotion && typeof check._promotion === "object") ? check._promotion : null;
869
+ // #298: artifact_refs/standard_refs are validated on input by normalizeCheck but were
870
+ // previously never persisted onto the claim — silently lost on the very first write, not
871
+ // just on round-trip. Stamp them onto claim.metadata (additive, mirrors waiver/promotion
872
+ // above) so checksFromBundle can restore them for every subsequent writer.
873
+ const artifactRefsMeta = Array.isArray(check.artifact_refs) && check.artifact_refs.length > 0 ? check.artifact_refs : null;
874
+ const standardRefsMeta = Array.isArray(check.standard_refs) && check.standard_refs.length > 0 ? check.standard_refs : null;
875
+ // #270/#380 MEDIUM fix: record-check's captured-output sha256 digest (see recordCheck's
876
+ // outputSha256 computation) — hash ONLY, never the raw output text, so this is secret-safe by
877
+ // construction even though trust.bundle is often committed/shared. Stamped onto
878
+ // claim.metadata (additive, mirrors artifact_refs/standard_refs above) so checksFromBundle can
879
+ // restore it for every subsequent writer, and so it survives any later rebuild.
880
+ // NOTE (#270 LOW fix, iteration 3): this digest is over the CLAMPED capture (recordCheck's
881
+ // clampOutput, first RECORD_CHECK_MAX_OUTPUT / 64 KiB of combined stdout+stderr), not the full
882
+ // raw command output — a command producing >64KiB of output has its digest computed only over
883
+ // the retained prefix, so two runs whose outputs diverge only past the 64KiB boundary hash
884
+ // identically.
885
+ const outputDigestMeta = typeof check._output_sha256 === "string" && check._output_sha256.length > 0
886
+ ? { algorithm: "sha256", hex: check._output_sha256 }
887
+ : null;
888
+ // #270(a)/(c): a gate claim's declared claimType/subjectType, once resolved (either freshly
889
+ // via matchExpectsEntry below, or restored from a prior write's metadata.gate_claim stamp by
890
+ // checksFromBundle), is stamped here so it is frozen at record time — a later bundle rebuild
891
+ // (record-evidence/record-critique/record-learning) must never re-derive it from whatever
892
+ // step happens to be active THEN. See the matchExpectsEntry call site immediately below.
893
+ const gateClaimExpectationId = typeof check._gate_claim_expectation_id === "string" ? check._gate_claim_expectation_id : null;
894
+ const gateClaimDeclaredType = typeof check._gate_claim_declared_type === "string" ? check._gate_claim_declared_type : null;
895
+ const gateClaimDeclaredSubject = typeof check._gate_claim_declared_subject === "string" ? check._gate_claim_declared_subject : null;
896
+ const gateClaimDeclaredStepId = typeof check._gate_claim_declared_step_id === "string" ? check._gate_claim_declared_step_id : null;
897
+ const gateClaimRouteReason = typeof check._gate_claim_route_reason === "string" ? check._gate_claim_route_reason : null;
898
+ // #270 CRITICAL/HIGH fix: checksFromBundle stamps this when it read a claim that is
899
+ // gate-claim-SHAPED (origin:"check", check_kind:"external", kit-typed claimType) but carries
900
+ // NO metadata.gate_claim stamp — a claim this code could not have produced without also
901
+ // writing the stamp, so it predates cluster #270/#344. Die loudly with the same remedy
902
+ // pattern requireStampedClaim already uses elsewhere in this file, instead of silently
903
+ // falling through to matchExpectsEntry (which would re-derive a FRESH, possibly-wrong typing
904
+ // for what is actually a previously-recorded, now-untraceable gate claim — the re-typing bug).
905
+ const gateClaimShapeUnstampedClaimId = typeof check._gate_claim_shape_unstamped_claim_id === "string" ? check._gate_claim_shape_unstamped_claim_id : null;
906
+ if (gateClaimShapeUnstampedClaimId) {
907
+ die(`pre-cluster-270 gate claim '${gateClaimShapeUnstampedClaimId}' has no metadata.gate_claim stamp and cannot be re-typed authoritatively — re-record it (record-gate-claim) to regenerate.`);
908
+ }
660
909
  // #268: stamp a stable origin discriminator so checksFromBundle / critiquesFromBundle can
661
910
  // distinguish check vs critique vs acceptance claims across round-trips even under --flow-id,
662
911
  // where all three collapse onto the same declared claimType (and a command-less critique claim
663
912
  // would otherwise be re-absorbed as a test_output check → permanent [not-run] divergence).
664
- const claimMetadata = { origin: "check", check_kind: String(check.kind ?? "external"), ...(waiver ? { waiver } : {}), ...(promotionMeta ? { promotion: promotionMeta } : {}) };
913
+ const claimMetadata = {
914
+ origin: "check",
915
+ check_kind: String(check.kind ?? "external"),
916
+ ...(activeStep && workflowSubjectRef ? { workflow_subject_ref: workflowSubjectRef } : {}),
917
+ ...(waiver ? { waiver } : {}),
918
+ ...(promotionMeta ? { promotion: promotionMeta } : {}),
919
+ ...(artifactRefsMeta ? { artifact_refs: artifactRefsMeta } : {}),
920
+ ...(standardRefsMeta ? { standard_refs: standardRefsMeta } : {}),
921
+ ...(outputDigestMeta ? { output_digest: outputDigestMeta } : {}),
922
+ };
665
923
  const claimEvents = [];
666
924
  if (evStatus) {
667
925
  const evt = { id: `evt:${claimId}`, claimId, status: evStatus, actor: "flow-agents/workflow-sidecar", method: "validation", evidenceIds: [evId], createdAt: ts, verifiedAt: ts };
@@ -684,11 +942,47 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
684
942
  evidenceItems.push(evItem);
685
943
  // P-d: declared-only when active flow/step present (shadow retired); no-flow path unchanged.
686
944
  // When record-gate-claim sets _gate_claim_expectation_id, pass it for exact lookup (ADR 0016 P-d Increment 2).
687
- const declared = matchExpectsEntry("check", check.kind, typeof check._gate_claim_expectation_id === "string" ? check._gate_claim_expectation_id : undefined);
945
+ // #270(c): a REBUILD of a previously-recorded gate claim (both the expectation id AND its
946
+ // originally-declared claimType/subjectType round-tripped via checksFromBundle's
947
+ // metadata.gate_claim restoration) uses the STAMPED typing directly instead of re-resolving
948
+ // matchExpectsEntry against whatever step is active NOW — that re-resolution is the exact
949
+ // defect (a claim recorded at step N silently re-typed as step N+1's claim on rebuild).
950
+ // matchExpectsEntry is still the resolver for the FIRST write (no prior stamp to trust).
951
+ //
952
+ // #270 CRITICAL/HIGH fix: a RESTORED stamp (gateClaimDeclaredType/gateClaimDeclaredSubject
953
+ // both present — meaning this is a REBUILD reading back a prior write's metadata.gate_claim,
954
+ // not a fresh record-gate-claim call, which only ever sets gateClaimExpectationId) must be
955
+ // VALIDATED against the session's full flow definition before being trusted — see
956
+ // assertStampedGateClaimValid above. A stamp that fails validation dies loudly; it must NEVER
957
+ // silently fall through to matchExpectsEntry (that fall-through was the exact #270 defect:
958
+ // ANY invalid/forged/corrupt stamp got silently re-typed by the heuristic matcher instead of
959
+ // being rejected). A FRESH write (only gateClaimExpectationId set, no declared type/subject
960
+ // yet) has no stamp to validate — matchExpectsEntry is still the correct, and only, resolver
961
+ // for that case, exactly as before.
962
+ if (gateClaimExpectationId && gateClaimDeclaredType && gateClaimDeclaredSubject) {
963
+ assertStampedGateClaimValid(claimId, {
964
+ expectationId: gateClaimExpectationId,
965
+ claimType: gateClaimDeclaredType,
966
+ subjectType: gateClaimDeclaredSubject,
967
+ stepId: gateClaimDeclaredStepId,
968
+ });
969
+ }
970
+ const declared = (gateClaimExpectationId && gateClaimDeclaredType && gateClaimDeclaredSubject)
971
+ ? { claimType: gateClaimDeclaredType, subjectType: gateClaimDeclaredSubject }
972
+ : matchExpectsEntry("check", check.kind, gateClaimExpectationId ?? undefined);
688
973
  if (declared) {
689
974
  // Declared kit-typed claim only — no legacy shadow (ADR 0016 P-d).
690
975
  const declaredPolicy = ensurePolicy(declared.claimType, "high", [evClass.evidenceType]);
691
- const declaredClaimObj = { id: claimId, subjectType: declared.subjectType, subjectId, facet: "flow-agents.workflow", claimType: declared.claimType, fieldOrBehavior, value: effectiveStatus, createdAt: ts, updatedAt: ts, impactLevel: "high", verificationPolicyId: declaredPolicy.id, ...(claimMetadata ? { metadata: claimMetadata } : {}) };
976
+ // Freeze the resolved typing (fresh or restored) into metadata.gate_claim so it survives
977
+ // any subsequent rebuild regardless of the then-active step (#270a/c).
978
+ // step_id prefers the ORIGINALLY-recorded step (restored from a prior stamp) on a
979
+ // rebuild that has no active flow step of its own; only a genuinely first write (no
980
+ // restored stamp) takes the currently-active step's id.
981
+ const declaredStepId = gateClaimDeclaredStepId ?? (activeStep ? activeStep.stepId : null);
982
+ const declaredMetadata = gateClaimExpectationId
983
+ ? { ...claimMetadata, gate_claim: { expectation_id: gateClaimExpectationId, claim_type: declared.claimType, subject_type: declared.subjectType, step_id: declaredStepId, ...(gateClaimRouteReason ? { route_reason: gateClaimRouteReason } : {}) } }
984
+ : claimMetadata;
985
+ const declaredClaimObj = { id: claimId, subjectType: declared.subjectType, subjectId, facet: "flow-agents.workflow", claimType: declared.claimType, fieldOrBehavior, value: effectiveStatus, createdAt: ts, updatedAt: ts, impactLevel: "high", verificationPolicyId: declaredPolicy.id, ...(declaredMetadata ? { metadata: declaredMetadata } : {}) };
692
986
  const { status: declaredStatus } = deriveClaimStatus({ claim: declaredClaimObj, evidence: [evItem], events: claimEvents, policies: [declaredPolicy] });
693
987
  claims.push({ ...declaredClaimObj, status: declaredStatus });
694
988
  }
@@ -720,7 +1014,7 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
720
1014
  if (declared) {
721
1015
  // Declared kit-typed claim only — no legacy shadow (ADR 0016 P-d).
722
1016
  const declaredPolicy = ensurePolicy(declared.claimType, "high", []);
723
- const declaredClaimObj = { id: claimId, subjectType: declared.subjectType, subjectId, facet: "flow-agents.workflow", claimType: declared.claimType, fieldOrBehavior, value: criterion.status, createdAt: ts, updatedAt: ts, impactLevel: "high", verificationPolicyId: declaredPolicy.id, metadata: { origin: "acceptance" } };
1017
+ const declaredClaimObj = { id: claimId, subjectType: declared.subjectType, subjectId, facet: "flow-agents.workflow", claimType: declared.claimType, fieldOrBehavior, value: criterion.status, createdAt: ts, updatedAt: ts, impactLevel: "high", verificationPolicyId: declaredPolicy.id, metadata: { origin: "acceptance", ...(workflowSubjectRef ? { workflow_subject_ref: workflowSubjectRef } : {}) } };
724
1018
  const { status: declaredStatus } = deriveClaimStatus({ claim: declaredClaimObj, evidence: [], events: claimEvents, policies: [declaredPolicy] });
725
1019
  claims.push({ ...declaredClaimObj, status: declaredStatus });
726
1020
  }
@@ -744,7 +1038,7 @@ export async function buildTrustBundle(slug, timestamp, checks, criteria, critiq
744
1038
  const supersededBy = typeof c.superseded_by === "string" && c.superseded_by.length > 0 ? c.superseded_by : null;
745
1039
  const critiqueReviewer = String(c.reviewer ?? "tool-code-reviewer");
746
1040
  const critiqueReviewedAt = String(c.reviewed_at ?? ts);
747
- const critMeta = { origin: "critique", reviewer: critiqueReviewer, reviewed_at: critiqueReviewedAt, ...(supersededBy ? { superseded_by: supersededBy } : {}) };
1041
+ const critMeta = { origin: "critique", reviewer: critiqueReviewer, reviewed_at: critiqueReviewedAt, ...(activeStep && workflowSubjectRef ? { workflow_subject_ref: workflowSubjectRef } : {}), ...(supersededBy ? { superseded_by: supersededBy } : {}) };
748
1042
  // A superseded historical write gets a distinct, stable claimId so it co-exists with the live
749
1043
  // claim of the same critique id (never overwrites or duplicates it). The salt is reproducible
750
1044
  // across rebuilds because superseded_by + reviewed_at are preserved in metadata.
@@ -840,6 +1134,7 @@ export async function writeTrustBundle(dir, slug, timestamp, checks, criteria, c
840
1134
  return { written: false, errors: result.errors };
841
1135
  }
842
1136
  writeJson(path.join(dir, "trust.bundle"), bundle);
1137
+ await syncBuilderFlowSessionIfPresent(dir);
843
1138
  return { written: true, errors: [] };
844
1139
  }
845
1140
  catch (err) {
@@ -1079,8 +1374,23 @@ function parseCriterion(line, index) {
1079
1374
  if (m)
1080
1375
  text = text.slice(0, m.index).trim().replace(/\.$/, "");
1081
1376
  const item = { id: slugify(text, `criterion-${index + 1}`), description: text, status: "pending" };
1082
- if (evidence)
1083
- item.evidence_refs = [evidenceRef("command", { excerpt: evidence })];
1377
+ // #412 (AC8 interaction, planning-contract.md line ~46/84): the "- Evidence: <...>" Markdown
1378
+ // field is contractually a "test, command, screenshot, dashboard, doc, CI, or manual check" —
1379
+ // NOT always a runnable command. Unconditionally synthesizing kind:"command" with the raw text
1380
+ // in `excerpt` for EVERY Evidence line (the pre-existing behavior here) was already
1381
+ // contract-incorrect for prose evidence; it is now also a hard failure at record time
1382
+ // (validateAcceptanceEvidenceRefs's new runnability rejection targets kind:"command"'s
1383
+ // excerpt/url), so fixing the classification here is required, not optional polish. Use the
1384
+ // SAME isRunnableCommandText heuristic the record-time rejection itself uses (single-sourced):
1385
+ // literally-runnable text goes in `excerpt` (reconcilable, execution.label-eligible); anything
1386
+ // else (prose, or ensure-session's own "pending" scaffold placeholder) goes in `summary`
1387
+ // instead (never validated for runnability, never executed) — still kind:"command" (a
1388
+ // structured ref is still produced either way; only WHICH field carries the text changes),
1389
+ // per the contract's own "prose belongs in ref.summary" rule.
1390
+ if (evidence) {
1391
+ const { isRunnableCommandText } = loadRunnableCommandHelper();
1392
+ item.evidence_refs = [evidenceRef("command", isRunnableCommandText(evidence) ? { excerpt: evidence } : { summary: evidence })];
1393
+ }
1084
1394
  return item;
1085
1395
  }
1086
1396
  function artifactDirFrom(value) { return path.extname(value) ? path.dirname(value) : value; }
@@ -1205,6 +1515,45 @@ function loadCurrentPointerHelper() {
1205
1515
  const helperPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/hooks/lib/current-pointer.js");
1206
1516
  return _req(helperPath);
1207
1517
  }
1518
+ /**
1519
+ * #412: delegate to the shared pure-CJS runnable-command-text heuristic
1520
+ * (scripts/hooks/lib/runnable-command.js), mirroring the createRequire idiom used by
1521
+ * loadCurrentPointerHelper()/loadActorIdentityHelper() above. Single-sources the heuristic
1522
+ * between stop-goal-fit.js's Stop-time backstop and this file's record-time rejection
1523
+ * (validateAcceptanceEvidenceRefs, recordGateClaim --command, recordCheck --command) — see
1524
+ * AC9.
1525
+ *
1526
+ * #362 (Wave 3, AC6/AC7): extended (not a new sibling loader — same module, same
1527
+ * createRequire call, single require() of runnable-command.js) to also return
1528
+ * `isAmbiguousAbsenceCommand`, landed in that module by Wave 1's Task 1.2. This keeps
1529
+ * `recordCheck`'s record-time ambiguous-status stamp and `validateAcceptanceEvidenceRefs`'s
1530
+ * record-time advisory single-sourced against the SAME heuristic `runBackstop`/
1531
+ * `readCommandLog`/`evidence-capture.js`'s `observeResult` already consume (Waves 1-2) —
1532
+ * never a second, divergent implementation of "what counts as ambiguous."
1533
+ */
1534
+ function loadRunnableCommandHelper() {
1535
+ const _req = createRequire(import.meta.url);
1536
+ const helperPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/hooks/lib/runnable-command.js");
1537
+ return _req(helperPath);
1538
+ }
1539
+ /**
1540
+ * #362 (iteration-2 fix item 4/LOW): single-sourced human-facing remediation fragment shared by
1541
+ * this file's two ambiguous-absence-command emission sites (`validateAcceptanceEvidenceRefs`'s
1542
+ * record-time advisory and `recordCheck`'s ambiguous-status stderr note) — mirrors how
1543
+ * `isAmbiguousAbsenceCommand` itself is single-sourced above. Cross-ref: scripts/hooks/
1544
+ * stop-goal-fit.js keeps its OWN copy of the equivalent shared string (`AMBIGUOUS_REMEDIATION`)
1545
+ * for its three Stop-hook emission sites — the two files do not share a module for this string,
1546
+ * so each file single-sources independently.
1547
+ */
1548
+ const AMBIGUOUS_REMEDIATION_ADVICE = "self-asserting command ('! grep ...' or 'grep -c ... | grep -qx 0')";
1549
+ function validateRunnableCheckCommand(check, context) {
1550
+ if (check.kind !== "command" || !hasNonEmptyString(check.command))
1551
+ return;
1552
+ const { isRunnableCommandText } = loadRunnableCommandHelper();
1553
+ if (!isRunnableCommandText(check.command)) {
1554
+ die(`${context}: kind:"command" check command is not a runnable shell command: "${check.command}" — remediate by either (1) moving the prose to summary and omitting command/execution.label, or (2) reclassifying this check as kind:"external" (session-local attestation) instead of kind:"command".`);
1555
+ }
1556
+ }
1208
1557
  /**
1209
1558
  * #291 Wave 2 Task 2.1 (§5): writes the UNCHANGED legacy global `<root>/current.json` (the
1210
1559
  * compat-shim's write-side half — every existing consumer without an actorKey keeps reading
@@ -1214,7 +1563,7 @@ function loadCurrentPointerHelper() {
1214
1563
  * byte-identical to this function's pre-#291 behavior — with a stderr note mirroring the existing
1215
1564
  * unresolved-actor branch-naming diagnostic.
1216
1565
  */
1217
- function writeCurrent(root, dir, timestamp, owner, source, flowId, stepId, adHocReason, actorKey) {
1566
+ function writeCurrent(root, dir, timestamp, owner, source, flowId, stepId, actorKey) {
1218
1567
  // #289: mirror the active session's already-recorded branch (state.json.branch) into
1219
1568
  // current.json so consumers of current.json (which has no schema of its own — not one of the
1220
1569
  // 9 schemas under schemas/) see the routing branch without re-reading state.json separately.
@@ -1233,11 +1582,6 @@ function writeCurrent(root, dir, timestamp, owner, source, flowId, stepId, adHoc
1233
1582
  // FlowDefinition omit them and fall through to the workflow.* claim type path.
1234
1583
  ...(flowId ? { active_flow_id: flowId } : {}),
1235
1584
  ...(stepId ? { active_step_id: stepId } : {}),
1236
- // WS8 (AC12): sanctioned ad-hoc direct entry marker. Set when --step-id explicitly
1237
- // targets a step other than the flow's resolved first step, so stop-goal-fit /
1238
- // gate-review can distinguish an intentional direct entry (e.g. a planning-only
1239
- // session that skips pull-work) from a stale/mis-stamped active_step_id.
1240
- ...(adHocReason ? { ad_hoc_entry: true, ad_hoc_reason: adHocReason } : {}),
1241
1585
  };
1242
1586
  writeJson(path.join(root, "current.json"), payload);
1243
1587
  if (actorKey && !loadActorIdentityHelper().isUnresolvedActor(actorKey)) {
@@ -1316,7 +1660,7 @@ function updateCurrentAgent(root, dir, agentId, status, timestamp, actorKey) {
1316
1660
  }
1317
1661
  }
1318
1662
  }
1319
- function initSidecars(dir, slug, sourceRequest, summary, nextAction, timestamp, markdown) {
1663
+ function initSidecars(dir, slug, sourceRequest, summary, nextAction, timestamp, markdown, workItemRefs = [], initialLifecycle) {
1320
1664
  const criteria = markdown ? definitionAcceptanceLines(markdown).map(parseCriterion) : [];
1321
1665
  // #289/#309: `markdown` here is NOT always the session `<slug>--deliver.md` that
1322
1666
  // ensureSession seeds the `branch:` line into — initPlan is called against the tool-planner's
@@ -1347,9 +1691,11 @@ function initSidecars(dir, slug, sourceRequest, summary, nextAction, timestamp,
1347
1691
  // current call's timestamp silently rewrites a session's original creation time. Preserve the
1348
1692
  // existing state.json's created_at when present; stamp only on true first-creation.
1349
1693
  // updated_at still reflects "now" on every call — that field is intentionally mutable.
1694
+ const retainedWorkItemRefs = workItemRefs.length > 0 ? workItemRefs : (Array.isArray(existingState.work_item_refs) ? existingState.work_item_refs : []);
1350
1695
  writeJson(path.join(dir, "state.json"), {
1351
- ...sidecarBase(slug), status: "planned", phase: "planning", created_at: existingState.created_at || timestamp, updated_at: timestamp,
1696
+ ...sidecarBase(slug), status: initialLifecycle?.status ?? "planned", phase: initialLifecycle?.phase ?? "planning", created_at: existingState.created_at || timestamp, updated_at: timestamp,
1352
1697
  ...(branch ? { branch } : {}),
1698
+ ...(retainedWorkItemRefs.length > 0 ? { work_item_refs: retainedWorkItemRefs } : {}),
1353
1699
  artifact_paths: relArtifacts(dir),
1354
1700
  next_action: { status: "continue", summary: nextAction || summary },
1355
1701
  });
@@ -1418,6 +1764,11 @@ function enforceEnsureSessionOwnership(p, root, slug, dir, resolution) {
1418
1764
  // assignment-provider.ts's sanitizeAuditEntryForDisplay) — this guard never echoes `--reason`
1419
1765
  // into a die() message, so it has no free-text field requiring the 240 tier today.
1420
1766
  const sanitize = (value) => stripControlCharsForDisplay(value).slice(0, 64);
1767
+ // #294: the 240-char free-text tier (repo convention: 64 for id-like, 240 for free text — cf.
1768
+ // assignment-provider.ts sanitizeDisplayField(record.branch/reason, 240)). Used for the takeover
1769
+ // `resumed_branch` (a realistic agent/<actor>/<slug> branch exceeds 64 — truncation would produce a
1770
+ // bad `git checkout` target) and the audit `reason` (else "resuming from trust bundle" is cut off).
1771
+ const sanitizeWide = (value) => stripControlCharsForDisplay(value).slice(0, 240);
1421
1772
  const nowMs = opt(p, "now") ? Date.parse(opt(p, "now")) : Date.now();
1422
1773
  const assignmentProviderKind = opt(p, "assignment-provider", "local-file");
1423
1774
  let effective;
@@ -1496,15 +1847,32 @@ function enforceEnsureSessionOwnership(p, root, slug, dir, resolution) {
1496
1847
  const fromActor = assignment.record?.actor;
1497
1848
  if (!fromActor)
1498
1849
  die(`ensure-session --supersede-stale: no existing local-file claim record found for subject ${sanitize(slug)} to supersede`);
1850
+ // #294 (ADR 0021 §5): takeover is resumption — the successor CONTINUES the incumbent's branch,
1851
+ // never a parallel one. Capture the incumbent's branch (from its pre-supersede record) and
1852
+ // surface it as `resumed_branch` so the skill can `git checkout` it; default the audit reason to
1853
+ // the ADR §5 wording (superseded actor X, last seen T, resuming from trust bundle).
1854
+ const incumbentBranch = assignment.record?.branch;
1855
+ const incumbentLastSeen = effective.holder?.last_at ?? assignment.record?.claimed_at;
1856
+ const takeoverReason = opt(p, "reason") || `takeover: superseded ${holderActor}${incumbentLastSeen ? `, last seen ${sanitize(incumbentLastSeen)}` : ""}, resuming from trust bundle`;
1499
1857
  performLocalSupersede(root, slug, fromActor, resolution.actorStruct, {
1500
- branch: resolveBranchForClaim(),
1858
+ // #294 (ADR 0021 §5): takeover is RESUMPTION — the successor continues the incumbent's branch,
1859
+ // so the record must keep pointing at that branch, NOT be overwritten with the successor's
1860
+ // current branch (`resolveBranchForClaim()`). At supersede time the successor has not yet
1861
+ // `git checkout`ed the resume branch (the skill claims ownership first, then checks out), so
1862
+ // resolveBranchForClaim() would otherwise clobber the record with a parallel branch and make a
1863
+ // later reader (resume surface / verify-hold guidance) see the wrong branch. Preserve the
1864
+ // incumbent's branch; fall back to the successor's only if the incumbent record had none.
1865
+ branch: incumbentBranch || resolveBranchForClaim(),
1501
1866
  artifactDir: path.relative(root, dir) || ".",
1502
- reason: opt(p, "reason", "ensure-session takeover: stale claim"),
1867
+ reason: takeoverReason,
1503
1868
  // F1 fix (fix-plan iteration 1, HIGH): persist the canonical actor_key on the record so
1504
1869
  // computeEffectiveState's holderActorKey (assignment-provider.ts) matches this same
1505
1870
  // branchActorKey string on the next status/guard check, cross-tool.
1506
1871
  actorKey: resolution.branchActorKey,
1507
1872
  });
1873
+ // Render-don't-execute: emit the incumbent's branch so the skill continues it (never a new
1874
+ // branch). The successor re-enters the SAME artifact dir (deterministic slug) by construction.
1875
+ printJson({ role: "SupersedeTakeover", subject: sanitize(slug), superseded_actor: holderActor, ...(incumbentBranch ? { resumed_branch: sanitizeWide(incumbentBranch) } : {}), reason: sanitizeWide(takeoverReason) });
1508
1876
  return;
1509
1877
  }
1510
1878
  case "free": {
@@ -1537,10 +1905,40 @@ function enforceEnsureSessionOwnership(p, root, slug, dir, resolution) {
1537
1905
  * --claim-ttl-seconds <n> Overrides the liveness-policy TTL default for a new claim.
1538
1906
  * --reason <text> Audit-trail reason recorded on the claim/supersede record.
1539
1907
  */
1908
+ function resolveEnsureSessionEntry(p, dir) {
1909
+ const flowId = opt(p, "flow-id");
1910
+ const explicitStep = opt(p, "step-id");
1911
+ if (!flowId) {
1912
+ if (explicitStep)
1913
+ die("ensure-session --step-id requires --flow-id");
1914
+ if (opt(p, "ad-hoc-reason"))
1915
+ die("ensure-session --ad-hoc-reason is no longer supported");
1916
+ return { flowId: "", stepId: "", firstStep: "" };
1917
+ }
1918
+ const firstStep = resolveFirstStep(flowId, findRepoRootFromDir(dir));
1919
+ if (!firstStep)
1920
+ die(`ensure-session could not resolve the first step for Flow Definition ${JSON.stringify(flowId)}`);
1921
+ if (opt(p, "ad-hoc-reason")) {
1922
+ die("ensure-session --ad-hoc-reason cannot authorize workflow entry; start at the Flow Definition's first step or resume persisted run state");
1923
+ }
1924
+ if (explicitStep && explicitStep !== firstStep) {
1925
+ die(`ensure-session refused workflow entry at ${JSON.stringify(explicitStep)}: new runs must start at first step ${JSON.stringify(firstStep)}; resume an existing run without --step-id`);
1926
+ }
1927
+ return { flowId, stepId: explicitStep || firstStep, firstStep };
1928
+ }
1929
+ function preflightEnsureSession(p) {
1930
+ const root = opt(p, "artifact-root") ? path.resolve(opt(p, "artifact-root")) : flowAgentsArtifactRoot();
1931
+ const slug = opt(p, "task-slug") || (opt(p, "work-item") ? workItemSlug(opt(p, "work-item")) : die("--task-slug is required (or pass --work-item to derive it)"));
1932
+ const dir = sessionDirFor(root, slug);
1933
+ resolveEnsureSessionEntry(p, dir);
1934
+ sessionWorkItem(p, slug, dir);
1935
+ }
1540
1936
  function ensureSession(p) {
1541
1937
  const root = opt(p, "artifact-root") ? path.resolve(opt(p, "artifact-root")) : flowAgentsArtifactRoot();
1542
1938
  const slug = opt(p, "task-slug") || (opt(p, "work-item") ? workItemSlug(opt(p, "work-item")) : die("--task-slug is required (or pass --work-item to derive it)"));
1543
1939
  const dir = sessionDirFor(root, slug);
1940
+ const entry = resolveEnsureSessionEntry(p, dir);
1941
+ const workItem = sessionWorkItem(p, slug, dir);
1544
1942
  // #291 Wave 2 Task 2.1 (§3, §4): resolve the actor ONCE, then run the ownership guard BEFORE
1545
1943
  // any directory/file is created — a refusal must never leave a stray empty session dir. Reused
1546
1944
  // below (writeCurrent's per-actor dual-write) so the branch-naming actor and the
@@ -1549,6 +1947,9 @@ function ensureSession(p) {
1549
1947
  enforceEnsureSessionOwnership(p, root, slug, dir, actorResolution);
1550
1948
  fs.mkdirSync(dir, { recursive: true });
1551
1949
  const timestamp = opt(p, "timestamp", now());
1950
+ if (workItem.localRecord && !fs.existsSync(path.join(dir, "work-item.json"))) {
1951
+ writeJson(path.join(dir, "work-item.json"), workItem.localRecord);
1952
+ }
1552
1953
  let md = fs.existsSync(path.join(dir, `${slug}--deliver.md`)) ? read(path.join(dir, `${slug}--deliver.md`)) : "";
1553
1954
  if (!md) {
1554
1955
  // #289: derive the routing branch ONLY on fresh session creation (this `if (!md)` guard).
@@ -1556,11 +1957,19 @@ function ensureSession(p) {
1556
1957
  // of code is skipped on a resumed/taken-over session, which is what makes ADR 0021 §5
1557
1958
  // takeover continuity true by construction (see Design Decision 3 in the plan).
1558
1959
  const branch = resolveSessionBranch(p, slug);
1559
- md = `# ${opt(p, "title", slug)}\n\nbranch: ${branch}\nworktree: main\ncreated: ${timestamp}\nstatus: planning\ntype: deliver\niteration: 1\n\n## Plan\n\n${opt(p, "summary", "")}\n\n## Definition Of Done\n\n- **User outcome:** ${opt(p, "summary", "Workflow session is durable.")}\n- **Scope:** Workflow session artifacts and sidecars.\n- **Acceptance criteria:**\n${opts(p, "criterion").map((c) => ` - [ ] ${c} - Evidence: pending.`).join("\n")}\n- **Usefulness checks:**\n - [ ] User-facing workflow is documented or discoverable\n- **Stop-short risks:** Workflow artifacts could drift.\n- **Durable docs target:** not needed\n- **Sandbox mode:** local-edit\n\n## Execution Progress\n\n- [ ] Session initialized.\n\n## Verification Report\n\nBuild: [NOT_VERIFIED] Verification has not run yet.\n\n### Acceptance Criteria\n- [NOT_VERIFIED] Verification has not run yet - Evidence: pending workflow execution and checks.\n\n### Verdict: NOT_VERIFIED\n\n## Goal Fit Gate\n\n- [ ] Original user goal restated\n\n## Final Acceptance\n\n- [ ] CI/relevant checks passed or local equivalent recorded\n`;
1960
+ const initialMarkdownStatus = entry.flowId ? "new" : "planning";
1961
+ md = `# ${opt(p, "title", slug)}\n\nbranch: ${branch}\nworktree: main\ncreated: ${timestamp}\nstatus: ${initialMarkdownStatus}\ntype: deliver\niteration: 1\n\n## Plan\n\n${opt(p, "summary", "")}\n\n## Definition Of Done\n\n- **User outcome:** ${opt(p, "summary", "Workflow session is durable.")}\n- **Scope:** Workflow session artifacts and sidecars.\n- **Acceptance criteria:**\n${opts(p, "criterion").map((c) => ` - [ ] ${c} - Evidence: pending.`).join("\n")}\n- **Usefulness checks:**\n - [ ] User-facing workflow is documented or discoverable\n- **Stop-short risks:** Workflow artifacts could drift.\n- **Durable docs target:** not needed\n- **Sandbox mode:** local-edit\n\n## Execution Progress\n\n- [ ] Session initialized.\n\n## Verification Report\n\nBuild: [NOT_VERIFIED] Verification has not run yet.\n\n### Acceptance Criteria\n- [NOT_VERIFIED] Verification has not run yet - Evidence: pending workflow execution and checks.\n\n### Verdict: NOT_VERIFIED\n\n## Goal Fit Gate\n\n- [ ] Original user goal restated\n\n## Final Acceptance\n\n- [ ] CI/relevant checks passed or local equivalent recorded\n`;
1560
1962
  fs.writeFileSync(path.join(dir, `${slug}--deliver.md`), md);
1561
1963
  }
1562
1964
  if (!fs.existsSync(path.join(dir, "state.json")) || !fs.existsSync(path.join(dir, "acceptance.json")) || !fs.existsSync(path.join(dir, "handoff.json"))) {
1563
- initSidecars(dir, slug, opt(p, "source-request"), opt(p, "summary"), opt(p, "next-action", "Continue."), timestamp, md);
1965
+ const phaseMap = entry.flowId ? resolvePhaseMap(entry.flowId, findRepoRootFromDir(dir)) : null;
1966
+ const initialPhase = Object.entries(phaseMap ?? {}).find(([, step]) => step === entry.firstStep)?.[0];
1967
+ const nextAction = entry.flowId
1968
+ ? entry.flowId === "builder.build"
1969
+ ? `Start the canonical Flow run with \`flow-agents builder-run start --session-dir .kontourai/flow-agents/${slug}\`; activate \`pull-work\` for work item ${JSON.stringify(workItem.ref)}, and satisfy the declared gate before advancing.`
1970
+ : `Continue at Flow step ${JSON.stringify(entry.stepId)} for work item ${JSON.stringify(workItem.ref)}; satisfy its declared gate before advancing.`
1971
+ : opt(p, "next-action", "Continue.");
1972
+ initSidecars(dir, slug, opt(p, "source-request"), opt(p, "summary"), nextAction, timestamp, md, [workItem.ref], initialPhase ? { status: "new", phase: initialPhase } : undefined);
1564
1973
  }
1565
1974
  // ADR 0016 Abstraction A (P-a): optional --flow-id / --step-id flags persist FlowDefinition
1566
1975
  // routing keys into current.json for the producer (P-b) and enforcer (P-c) to consume.
@@ -1569,29 +1978,14 @@ function ensureSession(p) {
1569
1978
  // active_step_id to the FIRST step in the FlowDefinition's steps[] list. This ensures
1570
1979
  // ensure-session --flow-id builder.build produces a FlowDefinition-driven session even
1571
1980
  // before the first advance-state call.
1572
- const flowId = opt(p, "flow-id");
1573
- const explicitStep = opt(p, "step-id");
1574
- let stepId = explicitStep;
1575
- let adHocReason;
1576
- if (flowId && !stepId) {
1577
- const repoRoot = findRepoRootFromDir(dir);
1578
- const firstStep = resolveFirstStep(flowId, repoRoot);
1579
- if (firstStep)
1580
- stepId = firstStep;
1581
- }
1582
- else if (flowId && explicitStep) {
1583
- // WS8 (AC12): --step-id is the sanctioned ad-hoc direct-entry mechanism. When it names
1584
- // a step other than the flow's resolved first step, record an explicit ad_hoc_entry
1585
- // marker (with a reason) instead of silently letting the mis-stamp look like the
1586
- // flow's normal first step. This is the root-cause fix for a planning-only session
1587
- // whose active_step_id would otherwise default to builder.build's first step.
1588
- const repoRoot = findRepoRootFromDir(dir);
1589
- const firstStep = resolveFirstStep(flowId, repoRoot);
1590
- if (firstStep && firstStep !== explicitStep) {
1591
- adHocReason = opt(p, "ad-hoc-reason") || `direct entry at step "${explicitStep}" via --step-id (flow first step is "${firstStep}")`;
1592
- }
1593
- }
1594
- writeCurrent(root, dir, timestamp, "workflow-sidecar", "ensure-session", flowId || undefined, stepId || undefined, adHocReason, actorResolution.unresolved ? undefined : actorResolution.branchActorKey);
1981
+ const persistedCurrent = loadCurrent(root);
1982
+ const resumedStep = !opt(p, "step-id")
1983
+ && persistedCurrent?.active_slug === slug
1984
+ && persistedCurrent?.active_flow_id === entry.flowId
1985
+ && typeof persistedCurrent?.active_step_id === "string"
1986
+ ? persistedCurrent.active_step_id
1987
+ : entry.stepId;
1988
+ writeCurrent(root, dir, timestamp, "workflow-sidecar", "ensure-session", entry.flowId || undefined, resumedStep || undefined, actorResolution.unresolved ? undefined : actorResolution.branchActorKey);
1595
1989
  console.log(dir);
1596
1990
  return 0;
1597
1991
  }
@@ -1720,14 +2114,62 @@ export function normalizeEvidenceRefs(raw, label) {
1720
2114
  return validateEvidenceRef({ ...ref }, label);
1721
2115
  });
1722
2116
  }
1723
- export function normalizeCheck(raw) {
2117
+ // #270 HIGH fix (iteration 3): the `gate-claim-` check-id prefix is RESERVED for
2118
+ // record-gate-claim's own internally-constructed ids (`id: \`gate-claim-${checkId}\`` — see
2119
+ // recordGateClaim below). Every OTHER writer of check ids (record-evidence --check-json,
2120
+ // record-check, dogfood-pass --check-json) flows through this same normalizeCheck, and until
2121
+ // this fix any of them could ALSO hand-supply an id starting with "gate-claim-". That collision
2122
+ // silently satisfies the id-shape half of gateClaimShapeUnstampedId's four-signal detector (see
2123
+ // its comment above) without ever having gone through record-gate-claim, so a later rebuild
2124
+ // misclassifies the caller's check as an unstamped pre-cluster-270 gate claim and dies, losing
2125
+ // the write. Rejecting the prefix HERE, at record time, for every caller-supplied id makes the
2126
+ // id-shape signal sound again: only record-gate-claim's own path can ever produce that shape.
2127
+ // record-gate-claim opts in via allowGateClaimPrefix=true since it is the sole legitimate
2128
+ // producer of that id shape; every other caller uses the default (reject).
2129
+ //
2130
+ // #270 follow-up fix (publish-preflight, iteration 5): the rejection above must apply ONLY to
2131
+ // NEW mints, not to a correction of an id that already exists as a check claim id in the
2132
+ // session's CURRENT trust.bundle. A mis-recorded claim that already carries a `gate-claim-`
2133
+ // prefixed id (e.g. one that slipped through before this guard shipped, or was recorded via a
2134
+ // binary predating it) can otherwise NEVER be corrected: every attempt to re-record that exact
2135
+ // id — the only way to supersede/fix it — is itself rejected by this same guard, permanently
2136
+ // wedging that id.
2137
+ //
2138
+ // #270 CRITICAL fix (iteration 6, narrowing the above): "the id's identity already exists in
2139
+ // the bundle" is NOT by itself a safe supersession signal — an id that already exists MIGHT be
2140
+ // a REAL, properly-stamped claim produced by record-gate-claim itself (its own generated
2141
+ // `gate-claim-${checkId}` ids always already "exist" once minted). Exempting every existing id
2142
+ // unconditionally let record-evidence/record-check/dogfood-pass silently overwrite a live,
2143
+ // correctly-stamped gate claim — destroying its metadata.gate_claim stamp — and the caller
2144
+ // fully controls check_kind, so the replacement claim can trivially be shaped to evade
2145
+ // gateClaimShapeUnstampedId's detector (that detector requires check_kind==="external", which
2146
+ // only fires the alarm when the caller happens to pick that kind). The narrowed rule: an
2147
+ // existing id is supersedable via this path ONLY when the EXISTING claim for that id carries NO
2148
+ // metadata.gate_claim stamp — i.e. only the mis-recorded/wedged shape (the legitimate
2149
+ // correction target this exemption exists for). An existing id whose claim IS stamped is a live
2150
+ // gate claim; only record-gate-claim (allowGateClaimPrefix=true, its own unconditional opt-in)
2151
+ // may ever supersede it. Callers therefore pass `existingCheckStampById` (a Map from the
2152
+ // bundle's CURRENT check ids to whether that check's claim already carries a metadata.gate_claim
2153
+ // stamp, read via readBundleState/checksFromBundle's `_gate_claim_expectation_id` restoration
2154
+ // BEFORE normalizeCheck runs — see applyGateClaimStamp). This does not weaken new-mint
2155
+ // enforcement: a NOVEL gate-claim-* id (not already present at all) is still rejected exactly as
2156
+ // before, and superseding a STAMPED existing id is now rejected too.
2157
+ export function normalizeCheck(raw, allowGateClaimPrefix = false, existingCheckStampById) {
1724
2158
  const check = { ...raw };
1725
2159
  if (!check.id || !check.kind || !check.status || !check.summary)
1726
2160
  die("check requires id, kind, status, and summary");
2161
+ if (!allowGateClaimPrefix && typeof check.id === "string" && check.id.startsWith("gate-claim-")) {
2162
+ const existingHasStamp = existingCheckStampById?.get(check.id);
2163
+ if (existingHasStamp === true)
2164
+ die(`check id "${check.id}" belongs to a live, properly-stamped gate claim — only record-gate-claim may supersede it. Superseding a stamped gate claim via record-evidence/record-check/dogfood-pass would silently destroy its metadata.gate_claim stamp. Re-record via record-gate-claim, or choose a different --id.`);
2165
+ if (existingHasStamp === undefined)
2166
+ die(`check id "${check.id}" starts with the reserved "gate-claim-" prefix — that namespace is reserved for record-gate-claim's own generated ids. Choose a different --id (or omit --id to let the check derive one from its command/summary). Supersession of an EXISTING, UNSTAMPED check claim with this same id (a correction) is permitted — this rejection applies to newly-minted ids not already present in the session's trust.bundle, and to ids that already belong to a stamped (live) gate claim.`);
2167
+ }
1727
2168
  if (!checkKinds.has(check.kind))
1728
2169
  die("kind must be one of: build, types, lint, test, command, security, diff, browser, runtime, policy, external");
1729
2170
  if (!checkStatuses.has(check.status))
1730
2171
  die("status must be one of: pass, fail, not_verified, skip");
2172
+ validateRunnableCheckCommand(check, `check ${String(check.id)}`);
1731
2173
  if (Array.isArray(check.standard_refs))
1732
2174
  for (const ref of check.standard_refs)
1733
2175
  if (!["junit", "sarif", "coverage", "veritas"].includes(ref.standard))
@@ -1859,16 +2301,59 @@ function surfaceCheckFromArtifact(file, index) {
1859
2301
  }
1860
2302
  return { id: `surface-trust-${index + 1}`, kind: "policy", status: ref.status, summary: ref.summary, surface_trust_refs: [ref] };
1861
2303
  }
1862
- function validateAcceptanceEvidenceRefs(dir) {
2304
+ /**
2305
+ * #270 MEDIUM security fix: a `kind:"command"` evidence_refs entry whose command source is
2306
+ * genuinely non-runnable-by-design (e.g. a screenshot/dashboard reference the record-time
2307
+ * heuristic misclassifies) previously had NO escape hatch — this validator's die() was an
2308
+ * unconditional lockout. Mirrors --skip-ownership-guard's existing pattern in this file exactly:
2309
+ * a named, logged (never silent) bypass flag, not a silent fallback. `--skip-evidence-ref-
2310
+ * runnability-guard` is intentionally verbose/unambiguous so it is never reached for
2311
+ * accidentally — the die() message itself names the concrete remediations FIRST (move the prose
2312
+ * to ref.summary, or reclassify as kind:"external"/"artifact"), so the bypass is a last resort,
2313
+ * not the first thing an agent reaches for.
2314
+ */
2315
+ function validateAcceptanceEvidenceRefs(dir, p) {
2316
+ if (p?.flags.has("skip-evidence-ref-runnability-guard")) {
2317
+ process.stderr.write("[record-evidence] evidence-ref runnability guard skipped via --skip-evidence-ref-runnability-guard\n");
2318
+ return;
2319
+ }
1863
2320
  const file = path.join(dir, "acceptance.json");
1864
2321
  if (!fs.existsSync(file))
1865
2322
  return;
1866
2323
  const data = loadJson(file);
1867
2324
  if (!Array.isArray(data.criteria))
1868
2325
  return;
2326
+ const { isRunnableCommandText, isAmbiguousAbsenceCommand } = loadRunnableCommandHelper();
1869
2327
  data.criteria.forEach((criterion, index) => {
1870
- if (criterion.evidence_refs !== undefined)
1871
- normalizeEvidenceRefs(criterion.evidence_refs, `acceptance.criteria[${index}].evidence_refs`);
2328
+ if (criterion.evidence_refs === undefined)
2329
+ return;
2330
+ const refs = normalizeEvidenceRefs(criterion.evidence_refs, `acceptance.criteria[${index}].evidence_refs`);
2331
+ // #412 (AC8): a kind:"command" ref's command source (excerpt, falling back to url when that
2332
+ // is where the command string lives) must be a literally runnable shell command, not prose
2333
+ // describing a manual verification step — reject at RECORD time instead of letting it reach
2334
+ // the Stop-hook backstop (stop-goal-fit.js's bundleClaimedPassCommandChecks section B), which
2335
+ // would otherwise spawn `bash -lc "<a sentence>"` and misreport the resulting shell error as
2336
+ // a caught false-completion. Prose belongs in `summary` (never executed).
2337
+ refs.forEach((ref, refIndex) => {
2338
+ if (ref.kind !== "command")
2339
+ return;
2340
+ const commandSource = hasNonEmptyString(ref.excerpt) ? ref.excerpt : (hasNonEmptyString(ref.url) ? ref.url : "");
2341
+ if (!commandSource)
2342
+ return; // command refs may carry only `summary` — nothing to validate
2343
+ if (!isRunnableCommandText(commandSource)) {
2344
+ die(`acceptance.criteria[${index}].evidence_refs[${refIndex}]: kind:"command" ref's command text is not a runnable shell command: "${commandSource}" — remediate by either (1) moving the prose to ref.summary (never executed) and dropping/emptying ref.excerpt/ref.url, or (2) reclassifying this ref as kind:"external" (session-local attestation) or kind:"artifact" (a file/screenshot/dashboard reference) instead of kind:"command". As a last resort, --skip-evidence-ref-runnability-guard bypasses this check (logged, not silent).`);
2345
+ }
2346
+ // #362 (Wave 3, AC7): ADVISORY ONLY — never die(), never rejects/alters the ref. This is
2347
+ // deliberately the opposite posture from the runnability guard immediately above (which
2348
+ // stays fatal, unchanged). Guidance, not enforcement, per the plan's item 2: nudge a
2349
+ // newly-recorded bare (non-negated, non-count-asserted, non-chained) grep/diff evidence
2350
+ // ref toward a self-asserting form, without breaking back-compat with any already-recorded
2351
+ // evidence ref (#412) — an already-recorded ref reaching this validator on every subsequent
2352
+ // record-evidence call must keep passing, just with a repeated nudge, never a new failure.
2353
+ if (isAmbiguousAbsenceCommand(commandSource)) {
2354
+ process.stderr.write(`[record-evidence] advisory: acceptance.criteria[${index}].evidence_refs[${refIndex}] kind:"command" ref "${commandSource}" is a bare grep/diff invocation — its exit code is AMBIGUOUS (zero matches/no diff could mean PASS for an absence check or FAIL for a presence check). Consider re-recording it as a ${AMBIGUOUS_REMEDIATION_ADVICE} to remove the ambiguity. This is advisory only; the ref is NOT rejected.\n`);
2355
+ }
2356
+ });
1872
2357
  });
1873
2358
  }
1874
2359
  export function writeState(dir, slug, status, phase, timestamp, summary, next = "continue") {
@@ -1930,6 +2415,106 @@ function checksFromBundle(dir) {
1930
2415
  const seen = new Set();
1931
2416
  const checks = [];
1932
2417
  const kindOf = (claim) => String(claim.metadata.check_kind);
2418
+ // Read side of the buildTrustBundle waiver round-trip (write side: buildTrustBundle reads
2419
+ // check._waiver at line ~689 and stamps it onto claimMetadata.waiver at line ~705). Without
2420
+ // this, any caller that rebuilds checks via checksFromBundle() (recordCritique/recordLearning)
2421
+ // silently drops a previously-recorded waiver on the next bundle write.
2422
+ const waiverOf = (claim) => {
2423
+ const md = claim.metadata;
2424
+ return md && typeof md === "object" && md.waiver && typeof md.waiver === "object" ? md.waiver : undefined;
2425
+ };
2426
+ // #298: read side of the artifact_refs/standard_refs stamp (write side: buildTrustBundle's
2427
+ // claimMetadata.artifact_refs/.standard_refs, above). Previously these were validated on input
2428
+ // but never persisted at all — restoring them here is what makes them round-trip through a
2429
+ // second writer's rebuild instead of vanishing on the very first write.
2430
+ const refsOf = (claim) => {
2431
+ const md = claim.metadata;
2432
+ if (!md || typeof md !== "object")
2433
+ return {};
2434
+ const out = {};
2435
+ if (Array.isArray(md.artifact_refs) && md.artifact_refs.length > 0)
2436
+ out.artifact_refs = md.artifact_refs;
2437
+ if (Array.isArray(md.standard_refs) && md.standard_refs.length > 0)
2438
+ out.standard_refs = md.standard_refs;
2439
+ return out;
2440
+ };
2441
+ // #270/#380: read side of the record-check output-digest stamp (write side: buildTrustBundle's
2442
+ // claimMetadata.output_digest, above). Restoring it here is what makes the digest survive a
2443
+ // subsequent writer's rebuild instead of vanishing on the very next record-evidence/
2444
+ // record-critique/record-learning call.
2445
+ const outputSha256Of = (claim) => {
2446
+ const md = claim.metadata;
2447
+ const od = md && typeof md === "object" ? md.output_digest : undefined;
2448
+ return od && typeof od === "object" && od.algorithm === "sha256" && typeof od.hex === "string" && od.hex.length > 0 ? od.hex : undefined;
2449
+ };
2450
+ // #270(a)/(c): read side of the gate_claim stamp (write side: buildTrustBundle's
2451
+ // claimMetadata.gate_claim, above). Restoring expectation_id/claim_type/subject_type/step_id
2452
+ // is what lets a REBUILD (record-evidence/record-critique/record-learning, after the recorded
2453
+ // gate claim) recognize this as a previously-typed gate claim and reuse its frozen typing
2454
+ // instead of re-deriving via matchExpectsEntry against whatever step is active at rebuild time.
2455
+ const gateClaimOf = (claim) => {
2456
+ const md = claim.metadata;
2457
+ return md && typeof md === "object" && md.gate_claim && typeof md.gate_claim === "object" ? md.gate_claim : undefined;
2458
+ };
2459
+ const applyGateClaimStamp = (check, claim) => {
2460
+ const gc = gateClaimOf(claim);
2461
+ if (!gc)
2462
+ return;
2463
+ if (typeof gc.expectation_id === "string")
2464
+ check._gate_claim_expectation_id = gc.expectation_id;
2465
+ if (typeof gc.claim_type === "string")
2466
+ check._gate_claim_declared_type = gc.claim_type;
2467
+ if (typeof gc.subject_type === "string")
2468
+ check._gate_claim_declared_subject = gc.subject_type;
2469
+ if (typeof gc.step_id === "string")
2470
+ check._gate_claim_declared_step_id = gc.step_id;
2471
+ if (typeof gc.route_reason === "string")
2472
+ check._gate_claim_route_reason = gc.route_reason;
2473
+ };
2474
+ // #270 CRITICAL/HIGH fix: a claim that is gate-claim-SHAPED but carries NO metadata.gate_claim
2475
+ // stamp predates this cluster (#270/#344): buildTrustBundle could not have produced this shape
2476
+ // without ALSO writing the stamp, once the stamping code shipped, EXCEPT for one legitimate,
2477
+ // longstanding case that must NOT be flagged: a plain record-evidence check (kind:"external" or
2478
+ // otherwise) that simply happens to auto-match a declared kit-typed claim via matchExpectsEntry's
2479
+ // existing P-d fallback (ADR 0016) while a flow step is active — that path has ALWAYS existed,
2480
+ // never goes through record-gate-claim, and correctly has no gate_claim stamp (there is no
2481
+ // expectation id to freeze; matchExpectsEntry's heuristic result is expected to re-derive on
2482
+ // every rebuild for a plain check). The ONLY structurally reliable signal that a claim was
2483
+ // ACTUALLY produced by record-gate-claim (as opposed to a plain check that merely resembles one)
2484
+ // is record-gate-claim's own check-id-generation convention: `id: \`gate-claim-${checkId}\``
2485
+ // (see recordGateClaim) — no other producer in this file ever creates that id shape. Requiring
2486
+ // ALL FOUR signals (origin:"check", check_kind:"external", a kit-typed claimType — i.e. does NOT
2487
+ // start with "workflow." — AND a subjectId whose last path segment starts with "gate-claim-")
2488
+ // narrows detection to exactly the pre-cluster-270 defect class, without misclassifying an
2489
+ // ordinary declared check. Detected here (not in buildTrustBundle) because the claim's OWN
2490
+ // claimType/origin/check_kind/subjectId — the fields the detection needs — live on the bundle
2491
+ // claim, not on the reconstructed `check` object; buildTrustBundle only ever sees the `check`,
2492
+ // so the detection result is threaded through as a stamp on the check object itself, exactly
2493
+ // like every other gate_claim field above. buildTrustBundle's job is then only to die() loudly
2494
+ // on this stamp — never to re-derive or silently re-type it (that silent re-typing IS the
2495
+ // #268/#270 defect class).
2496
+ const gateClaimShapeUnstampedId = (claim) => {
2497
+ if (claimOrigin(claim) !== "check")
2498
+ return null;
2499
+ const md = (claim.metadata && typeof claim.metadata === "object") ? claim.metadata : {};
2500
+ if (md.check_kind !== "external")
2501
+ return null;
2502
+ const claimType = typeof claim.claimType === "string" ? claim.claimType : "";
2503
+ if (!claimType || claimType.startsWith("workflow."))
2504
+ return null;
2505
+ const subjectId = typeof claim.subjectId === "string" ? claim.subjectId : "";
2506
+ const lastSegment = subjectId.split("/").pop() ?? "";
2507
+ if (!lastSegment.startsWith("gate-claim-"))
2508
+ return null; // not record-gate-claim-shaped at all
2509
+ if (gateClaimOf(claim))
2510
+ return null; // properly stamped — not this defect class
2511
+ return typeof claim.id === "string" ? claim.id : "<unknown>";
2512
+ };
2513
+ const applyGateClaimShapeUnstamped = (check, claim) => {
2514
+ const unstampedId = gateClaimShapeUnstampedId(claim);
2515
+ if (unstampedId)
2516
+ check._gate_claim_shape_unstamped_claim_id = unstampedId;
2517
+ };
1933
2518
  for (const ev of bundle.evidence) {
1934
2519
  if (!ev || !ev.claimId)
1935
2520
  continue;
@@ -1948,6 +2533,15 @@ function checksFromBundle(dir) {
1948
2533
  check.command = ev.execution.label;
1949
2534
  if (ev.evidenceType)
1950
2535
  check.evidenceType = ev.evidenceType;
2536
+ const waiver = waiverOf(claim);
2537
+ if (waiver)
2538
+ check._waiver = waiver;
2539
+ Object.assign(check, refsOf(claim));
2540
+ const outputSha256 = outputSha256Of(claim);
2541
+ if (outputSha256)
2542
+ check._output_sha256 = outputSha256;
2543
+ applyGateClaimStamp(check, claim);
2544
+ applyGateClaimShapeUnstamped(check, claim);
1951
2545
  checks.push(check);
1952
2546
  }
1953
2547
  // Also include check claims that have no evidence item (surface_trust_refs style).
@@ -1960,10 +2554,71 @@ function checksFromBundle(dir) {
1960
2554
  continue;
1961
2555
  seen.add(claim.id);
1962
2556
  const kind = kindOf(claim);
1963
- checks.push({ id: String(claim.subjectId || "").split("/").pop() || claim.id, kind, status: claim.value ?? "not_verified", summary: claim.fieldOrBehavior || "" });
2557
+ const check = { id: String(claim.subjectId || "").split("/").pop() || claim.id, kind, status: claim.value ?? "not_verified", summary: claim.fieldOrBehavior || "" };
2558
+ const waiver = waiverOf(claim);
2559
+ if (waiver)
2560
+ check._waiver = waiver;
2561
+ Object.assign(check, refsOf(claim));
2562
+ const outputSha256 = outputSha256Of(claim);
2563
+ if (outputSha256)
2564
+ check._output_sha256 = outputSha256;
2565
+ applyGateClaimStamp(check, claim);
2566
+ applyGateClaimShapeUnstamped(check, claim);
2567
+ checks.push(check);
1964
2568
  }
1965
2569
  return checks;
1966
2570
  }
2571
+ /**
2572
+ * #270 CRITICAL fix (iteration 6): build the id -> hasStamp map normalizeCheck's narrowed
2573
+ * reserved-prefix exemption needs. A check's reconstructed `_gate_claim_expectation_id` (set by
2574
+ * applyGateClaimStamp above, from the claim's metadata.gate_claim) is present if and only if the
2575
+ * bundle claim backing this check id currently carries a live stamp. Every caller of
2576
+ * normalizeCheck (record-evidence, record-check, dogfood-pass) must derive this from the SAME
2577
+ * readBundleState/checksFromBundle snapshot used for the compose-safe merge, taken BEFORE
2578
+ * normalizeCheck runs, so the exemption sees the bundle state as it stands right now — not a
2579
+ * stale or partial view.
2580
+ */
2581
+ function existingCheckStampMap(checks) {
2582
+ const byId = new Map();
2583
+ for (const c of checks)
2584
+ if (c && typeof c.id === "string")
2585
+ byId.set(c.id, typeof c._gate_claim_expectation_id === "string");
2586
+ return byId;
2587
+ }
2588
+ /**
2589
+ * #298/#270: the shared compose-safe read path every trust-bundle writer should use instead of
2590
+ * hand-assembling its own partial slice. Reconstructs ALL THREE families losslessly from the
2591
+ * existing bundle (checks via checksFromBundle, extended per above; criteria from
2592
+ * acceptance.json; critiques via critiquesFromBundle) so a writer that only intends to touch ONE
2593
+ * family never has to pass `[]` for the other two — that `[]`-for-untouched-slices pattern is
2594
+ * exactly what caused #270's 21-claims-to-1 wipe. Generalizes the pattern recordLearning already
2595
+ * used inline; behavior-neutral for recordLearning itself.
2596
+ */
2597
+ function readBundleState(dir) {
2598
+ const acceptance = loadJson(path.join(dir, "acceptance.json"));
2599
+ return {
2600
+ checks: checksFromBundle(dir),
2601
+ criteria: Array.isArray(acceptance.criteria) ? acceptance.criteria : [],
2602
+ critiques: critiquesFromBundle(dir),
2603
+ };
2604
+ }
2605
+ /**
2606
+ * #298: compose-safe merge-by-id for the `checks` slice of readBundleState — a later check
2607
+ * with the same `id` supersedes/replaces the earlier one (same-id resupply is a legitimate
2608
+ * update, e.g. re-recording the same gate claim or the same named check after a fix); a check
2609
+ * with a new `id` is additive. Order is preserved (existing order, then newly-introduced ids
2610
+ * appended) so unrelated diagnostics (e.g. CI reconcile output) do not reorder churn.
2611
+ */
2612
+ function mergeChecksById(existing, incoming) {
2613
+ const byId = new Map();
2614
+ for (const c of existing)
2615
+ if (c && c.id)
2616
+ byId.set(c.id, c);
2617
+ for (const c of incoming)
2618
+ if (c && c.id)
2619
+ byId.set(c.id, c);
2620
+ return [...byId.values()];
2621
+ }
1967
2622
  function critiquesFromBundle(dir) {
1968
2623
  const bundle = loadJson(path.join(dir, "trust.bundle"));
1969
2624
  if (!Array.isArray(bundle.claims))
@@ -2015,7 +2670,14 @@ async function recordEvidence(p) {
2015
2670
  const slug = taskSlugFor(dir, opt(p, "task-slug"));
2016
2671
  const _ts0 = opt(p, "timestamp", now());
2017
2672
  const _waiver = parseWaiver(p, _ts0);
2018
- const _checksRaw = [...opts(p, "check-json").map((v) => normalizeCheck(parseJson(v, "--check-json"))), ...opts(p, "surface-trust-json").map(surfaceCheckFromArtifact)];
2673
+ // #270 follow-up fix (iteration 5, narrowed iteration 6): read the bundle's CURRENT check ids
2674
+ // (and stamp status) before normalizeCheck runs so a correction of an UNSTAMPED wedged id is
2675
+ // exempted from the reserved gate-claim- prefix rejection below, while a brand-new mint of
2676
+ // that shape, OR supersession of a STAMPED (live) gate claim, is still rejected. Reused below
2677
+ // (not re-read) as _existingState for the compose-safe merge — one readBundleState call.
2678
+ const _existingState = readBundleState(dir);
2679
+ const _existingCheckStampById = existingCheckStampMap(_existingState.checks);
2680
+ const _checksRaw = [...opts(p, "check-json").map((v) => normalizeCheck(parseJson(v, "--check-json"), false, _existingCheckStampById)), ...opts(p, "surface-trust-json").map(surfaceCheckFromArtifact)];
2019
2681
  // WS8 (AC4, iteration 2): a command-backed check reconciles against CI or fails — it can
2020
2682
  // NEVER be waived. Reject --accepted-gap-reason/--waived-by on any check whose evidence
2021
2683
  // classifies as test_output (build/types/lint/test/command, and security/browser/runtime
@@ -2034,22 +2696,182 @@ async function recordEvidence(p) {
2034
2696
  const checks = _checksRaw.map((c) => _waiver ? { ...c, _waiver } : c);
2035
2697
  if (!checks.length && opts(p, "surface-trust-json").length === 0)
2036
2698
  die("record-evidence requires at least one --check-json or --surface-trust-json");
2037
- validateAcceptanceEvidenceRefs(dir);
2699
+ validateAcceptanceEvidenceRefs(dir, p);
2038
2700
  // Phase 4c: bundle is the sole verification artifact — stop writing evidence.json and acceptance.json update.
2039
2701
  const ts = opt(p, "timestamp", now());
2040
- const _existingAcceptance = loadJson(path.join(dir, "acceptance.json"));
2041
- const _existingCriteria = Array.isArray(_existingAcceptance.criteria) ? _existingAcceptance.criteria : [];
2702
+ // #298: readBundleState + merge-by-id instead of unconditionally replacing every prior check —
2703
+ // record-evidence previously never called checksFromBundle(dir), so it dropped every check
2704
+ // recorded by an earlier record-evidence/record-check/record-gate-claim call. A later check
2705
+ // with the same id supersedes the earlier one (same-id resupply); a new id is additive.
2706
+ // (_existingState was already read above, before normalizeCheck ran, so the reserved-prefix
2707
+ // exists-check sees the SAME bundle snapshot the merge below uses — no second read needed.)
2042
2708
  const _criteriaStatus = verdict === "pass" ? "pass" : verdict === "fail" ? "fail" : "not_verified";
2043
- const _criteriaForBundle = _existingCriteria.map((c) => ({ ...c, status: _criteriaStatus }));
2709
+ const _criteriaForBundle = _existingState.criteria.map((c) => ({ ...c, status: _criteriaStatus }));
2710
+ const _mergedChecks = mergeChecksById(_existingState.checks, checks);
2044
2711
  // #268: preserve any existing critique claims (including superseded history) instead of dropping
2045
2712
  // them — record-evidence previously hardcoded critiques:[] here, silently erasing finding history
2046
2713
  // whenever it ran after a critique existed.
2047
- const _existingCritiques = critiquesFromBundle(dir);
2048
- assertBundleWritten(await writeTrustBundle(dir, slug, ts, checks, _criteriaForBundle, _existingCritiques));
2714
+ assertBundleWritten(await writeTrustBundle(dir, slug, ts, _mergedChecks, _criteriaForBundle, _existingState.critiques));
2049
2715
  const stateStatus = verdict === "pass" ? "verified" : verdict === "fail" ? "failed" : "not_verified";
2050
2716
  writeState(dir, slug, stateStatus, "verification", ts, "Evidence recorded.");
2051
2717
  return 0;
2052
2718
  }
2719
+ // #380: bounded stdout+stderr digest for a record-check execution, mirroring
2720
+ // scripts/hooks/evidence-capture.js's MAX_OUTPUT_SCAN bound (64 KiB) so the two capture code
2721
+ // paths (host-observed vs. self-executed) stay size-disciplined the same way, even though this
2722
+ // one runs the command itself rather than observing a host tool_response.
2723
+ const RECORD_CHECK_MAX_OUTPUT = 64 * 1024;
2724
+ function clampOutput(text) {
2725
+ return text.length > RECORD_CHECK_MAX_OUTPUT ? text.slice(0, RECORD_CHECK_MAX_OUTPUT) : text;
2726
+ }
2727
+ /**
2728
+ * record-check — run a command and record a capture-backed check in one step (#380).
2729
+ *
2730
+ * Trust posture (#270 MEDIUM fix — was previously misdescribed): record-check EXECUTES a command
2731
+ * ON THE AGENT'S BEHALF, in-process, right here — it is not an observer. This is a materially
2732
+ * DIFFERENT trust posture than scripts/hooks/evidence-capture.js, which never executes anything
2733
+ * itself; it only OBSERVES a host tool_response that some other, already-executed tool call
2734
+ * produced (a PostToolUse hook). record-check's exitCode/observedResult classification mirrors
2735
+ * evidence-capture.js's observeResult() heuristic (a clean integer exit code is authoritative),
2736
+ * but the EXECUTION itself is this function's own doing, under this process's privileges — an
2737
+ * agent invoking record-check is asking this CLI to run a command for it, not merely to attest to
2738
+ * something that already ran. Callers and reviewers should weigh that accordingly: record-check
2739
+ * is a convenience that collapses "run a command" + "record its result" into one step, not a
2740
+ * passive-observation capture path.
2741
+ *
2742
+ * Syntax: `workflow-sidecar record-check <artifact-dir> -- <command...>` (argv after the FIRST
2743
+ * literal `--` token is the command to execute verbatim, split by main() before parseArgs — see
2744
+ * main()'s pre-split below) or `--command "<shell string>"` for parity with record-gate-claim
2745
+ * when the caller already has a single shell string rather than an argv array.
2746
+ *
2747
+ * Captures { exitCode, observedResult } the same way evidence-capture.js's observeResult() does:
2748
+ * a clean integer exit code drives observedResult (0 => pass, nonzero => fail). Records a
2749
+ * kind:"command" check with a real execution.label (the executed command), composed losslessly
2750
+ * through the same readBundleState + mergeChecksById + writeTrustBundle path every other writer
2751
+ * in this file uses — record-check is the compose-safe pattern PLUS an execution step in front
2752
+ * of it, not a parallel bundle-writing implementation.
2753
+ *
2754
+ * The captured stdout+stderr is hashed (sha256) and the digest — never the raw output — is
2755
+ * persisted onto the resulting claim's metadata.output_digest (see buildTrustBundle's
2756
+ * outputDigestMeta) so a later reviewer can confirm two independent runs produced byte-identical
2757
+ * output without the trust.bundle itself ever carrying raw command output (secret-safe by
2758
+ * construction).
2759
+ *
2760
+ * A non-zero exit records status "fail" (never silently swallowed) AND this command itself exits
2761
+ * non-zero — a check that failed to run correctly must be loud, not silently recorded as if
2762
+ * nothing happened.
2763
+ */
2764
+ async function recordCheck(p, commandArgv) {
2765
+ const dir = artifactDirFrom(p.positional[0] || die("artifact directory is required"));
2766
+ const slug = taskSlugFor(dir, opt(p, "task-slug"));
2767
+ const ts = opt(p, "timestamp", now());
2768
+ const commandString = opt(p, "command");
2769
+ if (!commandArgv?.length && !commandString)
2770
+ die('record-check requires a command: either `record-check <dir> -- <command...>` or `--command "<shell string>"`');
2771
+ if (commandArgv?.length && commandString)
2772
+ die("record-check: pass the command via EITHER `-- <command...>` OR --command, not both");
2773
+ const repoRoot = findRepoRootFromDir(dir);
2774
+ let displayCommand;
2775
+ let exitCode;
2776
+ let stdout = "";
2777
+ let stderr = "";
2778
+ try {
2779
+ if (commandArgv?.length) {
2780
+ displayCommand = commandArgv.join(" ");
2781
+ const out = execFileSync(commandArgv[0], commandArgv.slice(1), { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 600000 });
2782
+ stdout = out;
2783
+ exitCode = 0;
2784
+ }
2785
+ else {
2786
+ // #412: a --command shell string is validated the same way record-gate-claim's --command
2787
+ // is (single-sourced isRunnableCommandText) — prose does not belong here either.
2788
+ const { isRunnableCommandText } = loadRunnableCommandHelper();
2789
+ if (!isRunnableCommandText(commandString))
2790
+ die(`record-check --command "${commandString}" is not a runnable shell command.`);
2791
+ displayCommand = commandString;
2792
+ const out = execFileSync("bash", ["-lc", commandString], { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 600000 });
2793
+ stdout = out;
2794
+ exitCode = 0;
2795
+ }
2796
+ }
2797
+ catch (err) {
2798
+ const e = err;
2799
+ exitCode = typeof e.status === "number" ? e.status : null;
2800
+ stdout = typeof e.stdout === "string" ? e.stdout : "";
2801
+ stderr = typeof e.stderr === "string" ? e.stderr : (e.message ?? "");
2802
+ displayCommand = commandArgv?.length ? commandArgv.join(" ") : commandString;
2803
+ }
2804
+ // Mirror evidence-capture.js's observeResult(): a clean integer exit code is authoritative
2805
+ // (0 => pass, nonzero => fail); this path always HAS a clean integer exit code because it ran
2806
+ // the command itself (unlike the host-observation path, which sometimes only has failure
2807
+ // indicators). See scripts/hooks/evidence-capture.js's observeResult()/cleanExitCode().
2808
+ //
2809
+ // #362 (Wave 3, AC6): the SAME narrow, two-binary carve-out `runBackstop`/`readCommandLog`
2810
+ // (stop-goal-fit.js) and `observeResult` (evidence-capture.js) already apply — a bare
2811
+ // (non-negated, non-count-asserted, non-chained) `grep`/`diff` invocation that exits EXACTLY
2812
+ // 1 is exit-code-ambiguous (zero matches/no diff could be the author's intended PASS for an
2813
+ // absence check, or an unintended miss for a presence check) — is applied HERE at record time
2814
+ // too, since record-check is the most direct match to the issue's own AC12 field evidence: it
2815
+ // executes the command itself and stamps the resulting status. Exit codes >= 2 are untouched
2816
+ // (still "fail", a real tool error) — the carve-out is exit-code-1-only, never widened.
2817
+ //
2818
+ // There is no "ambiguous" value in the check-status enum (`checkStatuses`,
2819
+ // schemas/workflow-acceptance.schema.json's criteria[].status enum) and none is added here —
2820
+ // per the plan (and ADR 0008/0010 consume-never-fork), the ambiguous case maps onto the
2821
+ // EXISTING "not_verified" status rather than inventing a new enum value that every consumer of
2822
+ // that enum would need auditing for. The distinction from a hard "fail" is carried in the
2823
+ // stderr note and the check summary text, not a new status value.
2824
+ const { isAmbiguousAbsenceCommand } = loadRunnableCommandHelper();
2825
+ const ambiguous = exitCode === 1 && isAmbiguousAbsenceCommand(displayCommand ?? "");
2826
+ const status = exitCode === 0 ? "pass" : (ambiguous ? "not_verified" : "fail");
2827
+ // #270 MEDIUM fix: hash the captured (clamped) output — the digest itself is what gets
2828
+ // persisted onto claim.metadata (below, via buildTrustBundle), NEVER the raw output. This is
2829
+ // secret-safe by construction: even if the executed command's stdout/stderr contained a
2830
+ // credential or token, only its sha256 hex digest ever reaches the trust.bundle (which is
2831
+ // frequently committed/shared), not the text itself. The previous `_output_digest` field held
2832
+ // the raw clamped text under a misleading "digest" name and was never actually persisted
2833
+ // anywhere (dead code) — this replaces it with a REAL digest that IS persisted.
2834
+ const capturedOutput = clampOutput(`${stdout}${stderr ? `
2835
+ ${stderr}` : ""}`.trim());
2836
+ const outputSha256 = capturedOutput ? createHash("sha256").update(capturedOutput, "utf8").digest("hex") : null;
2837
+ const checkIdRaw = opt(p, "id") || displayCommand;
2838
+ const checkId = checkIdRaw.replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80) || "record-check";
2839
+ const summary = opt(p, "summary", `record-check: ${displayCommand}${exitCode !== null ? ` (exit ${exitCode})` : ""}${ambiguous ? " — AMBIGUOUS (bare grep/diff exit 1): NOT_VERIFIED, not silently pass/fail" : ""}`);
2840
+ // #270 follow-up fix (iteration 5, narrowed iteration 6): read the bundle's CURRENT check ids
2841
+ // (and stamp status) BEFORE normalizeCheck runs so a correction of an UNSTAMPED wedged id is
2842
+ // exempted from the reserved gate-claim- prefix rejection, while a brand-new mint of that
2843
+ // shape, OR supersession of a STAMPED (live) gate claim, is still rejected. Reused below (not
2844
+ // re-read) for the compose-safe merge — one readBundleState call.
2845
+ const _existingState = readBundleState(dir);
2846
+ const _existingCheckStampById = existingCheckStampMap(_existingState.checks);
2847
+ // kind:"command" + a real `command` string already derives evidenceType "test_output" via
2848
+ // classifyEvidence in buildTrustBundle — no separate evidenceType input is consumed there.
2849
+ const check = normalizeCheck({
2850
+ id: checkId,
2851
+ kind: "command",
2852
+ status,
2853
+ summary,
2854
+ command: displayCommand,
2855
+ }, false, _existingCheckStampById);
2856
+ if (outputSha256)
2857
+ check._output_sha256 = outputSha256;
2858
+ const _mergedChecks = mergeChecksById(_existingState.checks, [check]);
2859
+ assertBundleWritten(await writeTrustBundle(dir, slug, ts, _mergedChecks, _existingState.criteria, _existingState.critiques));
2860
+ if (ambiguous) {
2861
+ // #362 (AC6): never silent-pass, never hard-fail — a bare grep/diff exit 1 is recorded
2862
+ // "not_verified" (above) and this is surfaced loudly on stderr, but record-check itself
2863
+ // still exits 0: the command DID run (this is not a tool/execution error), and the operator
2864
+ // needs an actionable nudge, not a blocked pipeline. Exit codes >= 2 for grep/diff remain a
2865
+ // hard "fail" via the branch below, unchanged.
2866
+ process.stderr.write(`[record-check] command "${displayCommand}" exited 1 — for bare grep/diff this may mean zero matches/no differences (PASS for an absence check) or an unintended miss (FAIL for a presence check); recorded status: not_verified (ambiguous), not silently pass or fail. Re-record this check as a ${AMBIGUOUS_REMEDIATION_ADVICE} to remove the ambiguity.\n`);
2867
+ return 0;
2868
+ }
2869
+ if (status === "fail") {
2870
+ process.stderr.write(`[record-check] command failed (exit ${exitCode ?? "unknown"}): ${displayCommand}\n${stderr ? `${stderr}\n` : ""}`);
2871
+ return 1;
2872
+ }
2873
+ return 0;
2874
+ }
2053
2875
  function diagnostic(dir, code, summary) {
2054
2876
  const payload = { timestamp: now(), code, summary };
2055
2877
  appendJsonl(path.join(dir, "transition-diagnostics.jsonl"), payload);
@@ -2063,6 +2885,7 @@ function diagnostic(dir, code, summary) {
2063
2885
  * --status <pass|fail|not_verified> (required)
2064
2886
  * --summary <text> (required)
2065
2887
  * --expectation <id> (optional; auto-resolved when the gate has one entry)
2888
+ * --route-reason <classifier> (optional; fail only, interpreted by Flow)
2066
2889
  * --evidence-json <json> (optional; structured evidence refs)
2067
2890
  *
2068
2891
  * The producer emits a check of kind="external" targeting the gate expectation's declared
@@ -2090,6 +2913,11 @@ async function recordGateClaim(p) {
2090
2913
  die("--status must be one of: pass, fail, not_verified");
2091
2914
  const summary = opt(p, "summary") || die("--summary is required");
2092
2915
  const expectationId = opt(p, "expectation");
2916
+ const routeReason = opt(p, "route-reason");
2917
+ if (routeReason && statusVal !== "fail")
2918
+ die("--route-reason is only valid with --status fail");
2919
+ if (routeReason && !/^[a-z][a-z0-9_-]*$/.test(routeReason))
2920
+ die("--route-reason must be a lowercase classifier identifier");
2093
2921
  // Resolve the active flow step from current.json. #291 Wave 2 Task 2.1 (§7)/Task 2.2: resolve
2094
2922
  // the CALLING actor's own current-pointer (per-actor-first, legacy-fallback) rather than an
2095
2923
  // unconditional legacy-only read — this is the fix for record-gate-claim's pre-existing (#291
@@ -2100,6 +2928,9 @@ async function recordGateClaim(p) {
2100
2928
  const activeStep = resolveActiveFlowStep(flowAgentsDir, gateClaimActorKey);
2101
2929
  if (!activeStep)
2102
2930
  die("record-gate-claim requires an active flow step in current.json (set via ensure-session --flow-id or advance-state --flow-definition)");
2931
+ if (routeReason && !activeStep.routeBackReasons.includes(routeReason)) {
2932
+ die(`--route-reason "${routeReason}" is not declared by gate "${activeStep.gateId}". Available: ${activeStep.routeBackReasons.join(", ") || "none"}`);
2933
+ }
2103
2934
  const expects = activeStep.gateExpects;
2104
2935
  if (expects.length === 0)
2105
2936
  die(`record-gate-claim: active step "${activeStep.stepId}" gate "${activeStep.gateId}" has no expects[] entries`);
@@ -2131,20 +2962,41 @@ async function recordGateClaim(p) {
2131
2962
  status: statusVal,
2132
2963
  summary,
2133
2964
  _gate_claim_expectation_id: targetExpectation.id,
2965
+ ...(routeReason ? { _gate_claim_route_reason: routeReason } : {}),
2134
2966
  };
2135
2967
  // Include structured evidence refs if provided
2136
2968
  const evidenceRefs = opts(p, "evidence-ref-json").map((v) => validateEvidenceRef(parseJson(v, "--evidence-ref-json"), "--evidence-ref-json"));
2137
2969
  if (evidenceRefs.length > 0) {
2138
2970
  check.artifact_refs = evidenceRefs;
2139
2971
  }
2140
- const checkNormalized = normalizeCheck(check);
2972
+ // #270(b)/#412: --command gives a gate claim a real, runnable execution.label distinct from
2973
+ // the human --summary prose, so stop-goal-fit.js's bundleClaimedPassCommandChecks section (B)
2974
+ // finds a real command to re-run instead of falling back to fieldOrBehavior (the --summary
2975
+ // prose itself), which it would otherwise execute as a shell command under
2976
+ // FLOW_AGENTS_GOAL_FIT_RECHECK. Validated at record time with the same isRunnableCommandText
2977
+ // heuristic the Stop-hook backstop uses (single-sourced — see loadRunnableCommandHelper).
2978
+ const gateCommand = opt(p, "command");
2979
+ if (gateCommand) {
2980
+ const { isRunnableCommandText } = loadRunnableCommandHelper();
2981
+ if (!isRunnableCommandText(gateCommand))
2982
+ die(`record-gate-claim --command "${gateCommand}" is not a runnable shell command — prose belongs in --summary, which is never executed.`);
2983
+ check.command = gateCommand;
2984
+ }
2985
+ const checkNormalized = normalizeCheck(check, /* allowGateClaimPrefix */ true);
2141
2986
  // WS8 (ADR 0020): honor the accepted-gap waiver flags for a gate claim too.
2142
2987
  const gateWaiver = parseWaiver(p, ts);
2143
2988
  if (gateWaiver)
2144
2989
  checkNormalized._waiver = gateWaiver;
2145
2990
  // Log the targeted gate expectation for transparency (goes to stderr only)
2146
2991
  process.stderr.write(`[record-gate-claim] targeting ${activeStep.stepId}/${activeStep.gateId}/${targetExpectation.id} → claimType=${claimType} subjectType=${subjectType}${gateWaiver ? " (WAIVED accepted_gap)" : ""}\n`);
2147
- assertBundleWritten(await writeTrustBundle(dir, slug, ts, [checkNormalized], [], [], gateClaimActorKey));
2992
+ // #270: accumulate into the FULL existing bundle state (checks/criteria/critiques) instead of
2993
+ // the prior [checkNormalized], [], [] call, which clobbered every other check/criterion/critique
2994
+ // in the bundle on every gate-claim write (the 21-claims-to-1 wipe). A gate claim against the
2995
+ // SAME expectation id supersedes the earlier check for that expectation (mergeChecksById); a
2996
+ // gate claim against a different expectation is additive.
2997
+ const _existingState = readBundleState(dir);
2998
+ const _mergedChecks = mergeChecksById(_existingState.checks, [checkNormalized]);
2999
+ assertBundleWritten(await writeTrustBundle(dir, slug, ts, _mergedChecks, _existingState.criteria, _existingState.critiques, gateClaimActorKey));
2148
3000
  return 0;
2149
3001
  }
2150
3002
  /**
@@ -2224,7 +3076,17 @@ async function promote(p) {
2224
3076
  // Optionally republish so delivery/trust.bundle carries the promotion claim for CI.
2225
3077
  if (p.flags.has("publish")) {
2226
3078
  const publishRepoRoot = opt(p, "publish-repo-root") ? path.resolve(opt(p, "publish-repo-root")) : findRepoRootFromDirStrict(dir);
3079
+ // #356 AC6: an InvalidBundleShapeError refusal must be LOUD (rethrown, so `promote`
3080
+ // itself fails/exits non-zero) — it is NOT one of the best-effort failure modes (missing
3081
+ // kits/ ancestor, I/O) this catch otherwise tolerates. A `.catch(() => {})`-style swallow
3082
+ // here would silently defeat the whole preflight for the --publish path.
2227
3083
  await publishDelivery(dir, publishRepoRoot).catch((err) => {
3084
+ if (err instanceof InvalidBundleShapeError)
3085
+ throw err;
3086
+ if (err instanceof NotFreshHolderError)
3087
+ throw err;
3088
+ if (err instanceof RepoHeadMismatchError)
3089
+ throw err;
2228
3090
  process.stderr.write(`[promote] WARNING: publish-delivery failed: ${err instanceof Error ? err.message : String(err)}\n`);
2229
3091
  });
2230
3092
  }
@@ -2284,7 +3146,7 @@ async function advanceState(p) {
2284
3146
  // call site ALSO dual-writes the per-actor projection, not only ensure-session's call site —
2285
3147
  // otherwise a session that only ever calls advance-state (never re-running ensure-session)
2286
3148
  // would never get a per-actor current.json mirror for its own FlowDefinition routing keys.
2287
- writeCurrent(root, dir, timestamp, "workflow-sidecar", "advance-state", flow, stepId, undefined, resolveReadActorKey(p));
3149
+ writeCurrent(root, dir, timestamp, "workflow-sidecar", "advance-state", flow, stepId, resolveReadActorKey(p));
2288
3150
  }
2289
3151
  }
2290
3152
  livenessLifecycle(dir, slug, LIVENESS_TERMINAL.has(status) ? "release" : "heartbeat", timestamp);
@@ -2296,8 +3158,18 @@ async function advanceState(p) {
2296
3158
  // publishDelivery below. An explicit --repo-root (e.g. for a scratch/test artifact dir
2297
3159
  // with no kits/ ancestor of its own) always wins, matching publishDeliveryCmd. Failures
2298
3160
  // are visible (stderr warning), not silently swallowed.
3161
+ // #356 AC6: an InvalidBundleShapeError refusal is NOT one of those best-effort failure
3162
+ // modes — it must be LOUD and cause advance-state itself to fail (rethrown here so the
3163
+ // outer command surfaces a non-zero exit), never silently swallowed alongside a genuine
3164
+ // repo-root-resolution/I-O failure.
2299
3165
  const publishRepoRoot = opt(p, "repo-root") ? path.resolve(opt(p, "repo-root")) : findRepoRootFromDirStrict(dir);
2300
3166
  await publishDelivery(dir, publishRepoRoot).catch((err) => {
3167
+ if (err instanceof InvalidBundleShapeError)
3168
+ throw err;
3169
+ if (err instanceof NotFreshHolderError)
3170
+ throw err;
3171
+ if (err instanceof RepoHeadMismatchError)
3172
+ throw err;
2301
3173
  process.stderr.write(`[advance-state] WARNING: publish-delivery failed: ${err instanceof Error ? err.message : String(err)}\n`);
2302
3174
  });
2303
3175
  }
@@ -2338,10 +3210,13 @@ async function recordCritique(p) {
2338
3210
  return e;
2339
3211
  });
2340
3212
  const critiques = [..._mergedCritiques, critique];
2341
- // Phase 4c: build bundle from raw inputs; read checks from trust.bundle (evidence.json no longer written).
2342
- const _critiqueEvChecks = checksFromBundle(dir);
2343
- const _critiqueAccCriteria = Array.isArray(loadJson(path.join(dir, "acceptance.json")).criteria) ? loadJson(path.join(dir, "acceptance.json")).criteria : [];
2344
- assertBundleWritten(await writeTrustBundle(dir, slug, critique.reviewed_at, _critiqueEvChecks, _critiqueAccCriteria, critiques));
3213
+ // Phase 4c: build bundle from raw inputs; read checks/criteria via the shared compose-safe
3214
+ // readBundleState path (#270 LOW consolidation) instead of hand-rolling the identical
3215
+ // checksFromBundle + acceptance.json read inline this is the exact pattern readBundleState
3216
+ // already exists to share; recordLearning uses it directly (see below) and recordCritique
3217
+ // previously duplicated it by hand for no reason.
3218
+ const _critiqueState = readBundleState(dir);
3219
+ assertBundleWritten(await writeTrustBundle(dir, slug, critique.reviewed_at, _critiqueState.checks, _critiqueState.criteria, critiques));
2345
3220
  return 0;
2346
3221
  }
2347
3222
  function frontmatter(text, key) {
@@ -2393,8 +3268,18 @@ async function recordRelease(p) {
2393
3268
  // publishDelivery below. An explicit --repo-root (e.g. for a scratch/test artifact dir with
2394
3269
  // no kits/ ancestor of its own) always wins, matching publishDeliveryCmd. Failures are
2395
3270
  // visible (stderr warning), not silently swallowed.
3271
+ // #356 AC6: an InvalidBundleShapeError refusal is NOT best-effort — rethrow so record-release
3272
+ // itself fails loudly (non-zero exit) rather than silently publishing nothing while reporting
3273
+ // success. This is the crux of AC6: record-release is one of the auto-publish paths that must
3274
+ // never let a shape-invalid bundle slip past unnoticed.
2396
3275
  const publishRepoRoot = opt(p, "repo-root") ? path.resolve(opt(p, "repo-root")) : findRepoRootFromDirStrict(dir);
2397
3276
  await publishDelivery(dir, publishRepoRoot).catch((err) => {
3277
+ if (err instanceof InvalidBundleShapeError)
3278
+ throw err;
3279
+ if (err instanceof NotFreshHolderError)
3280
+ throw err;
3281
+ if (err instanceof RepoHeadMismatchError)
3282
+ throw err;
2398
3283
  process.stderr.write(`[record-release] WARNING: publish-delivery failed: ${err instanceof Error ? err.message : String(err)}\n`);
2399
3284
  });
2400
3285
  return 0;
@@ -2596,6 +3481,799 @@ async function sealCheckpoint(p) {
2596
3481
  }
2597
3482
  return 0;
2598
3483
  }
3484
+ // ─── Reconcile Preflight (#356) ───────────────────────────────────────────────
3485
+ // Local, pre-push shape-only preflight for a session's trust.bundle, reusing
3486
+ // scripts/lib/reconcile-shape.js (WS8/#356 extraction) and scripts/ci/trust-reconcile.js's
3487
+ // own exported manifest resolver — never a forked reimplementation, so this can never
3488
+ // silently drift from what the CI trust-reconcile job actually enforces. Deliberately
3489
+ // shape-only: it never spawns a fresh manifest/CI command (AC5) — only the already-cheap
3490
+ // `run-baseline.sh --manifest-json` static registry emit, which prints the manifest, not
3491
+ // test results.
3492
+ /**
3493
+ * Delegate to the shared pure-CJS bundle-shape module (scripts/lib/reconcile-shape.js),
3494
+ * mirroring the createRequire pattern used by loadActorIdentityHelper()/
3495
+ * loadLivenessWriteHelper() above — the one repo/runtime boundary #356's plan flagged as
3496
+ * worth double-checking (workflow-sidecar.ts is TS→ESM-compiled-to-CJS-compatible-output;
3497
+ * scripts/lib/reconcile-shape.js is plain CommonJS). Verified clean via `npm run build`
3498
+ * + a require() smoke against build/src/cli/workflow-sidecar.js before this was wired in.
3499
+ */
3500
+ function loadReconcileShapeHelper() {
3501
+ const _req = createRequire(import.meta.url);
3502
+ const helperPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/lib/reconcile-shape.js");
3503
+ return _req(helperPath);
3504
+ }
3505
+ /**
3506
+ * Delegate to scripts/ci/trust-reconcile.js's own EXPORTED pure helpers (manifest
3507
+ * resolution + the git-ancestor primitive) — same createRequire idiom as
3508
+ * loadReconcileShapeHelper() above. trust-reconcile.js is CommonJS; these exports were
3509
+ * added alongside `runTrustReconcile` specifically so a local caller (this preflight)
3510
+ * never needs a second implementation of "how the manifest is resolved" (Q1/AC5).
3511
+ */
3512
+ function loadTrustReconcileHelper() {
3513
+ const _req = createRequire(import.meta.url);
3514
+ const helperPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/ci/trust-reconcile.js");
3515
+ return _req(helperPath);
3516
+ }
3517
+ /**
3518
+ * Shell to scripts/ci/derive-claim-status.mjs exactly as trust-reconcile.js's own
3519
+ * deriveClaimStatuses() does (Q1's recommendation: full status-misassertion/unwaived-assumed
3520
+ * parity with CI, at the cost of one cheap local-only spawn — no CI command execution, just
3521
+ * Surface's pure deriveClaimStatus over the bundle's own evidence/events/policies). Returns
3522
+ * null when re-derivation is unavailable (Surface could not load / helper failed) — callers
3523
+ * degrade to reconcile-shape.js's documented reduced-coverage mode, they do not fail the
3524
+ * whole preflight over this.
3525
+ */
3526
+ function derivePreflightClaimStatuses(bundlePath, repoRoot) {
3527
+ const helper = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../scripts/ci/derive-claim-status.mjs");
3528
+ if (!fs.existsSync(helper))
3529
+ return null;
3530
+ let stdout;
3531
+ try {
3532
+ stdout = execFileSync(process.execPath, [helper, bundlePath], { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 60000 });
3533
+ }
3534
+ catch {
3535
+ return null;
3536
+ }
3537
+ if (!stdout)
3538
+ return null;
3539
+ try {
3540
+ const obj = JSON.parse(stdout);
3541
+ const m = new Map();
3542
+ for (const [k, v] of Object.entries(obj))
3543
+ m.set(k, v);
3544
+ return m;
3545
+ }
3546
+ catch {
3547
+ return null;
3548
+ }
3549
+ }
3550
+ /**
3551
+ * Distinct, identifiable error for a shape-invalid trust.bundle — NOT a generic Error, so
3552
+ * every publishDelivery() call site (advanceState/recordRelease/promote/publishDeliveryCmd)
3553
+ * can positively distinguish "refuses to publish an invalid bundle" (must be LOUD, fail
3554
+ * closed, AC6) from the other failure modes those call sites already tolerate as best-effort
3555
+ * (missing kits/ ancestor for a scratch dir, I/O errors, etc — see each catch's own comment).
3556
+ * A bare `instanceof Error` check would not suffice since every thrown failure in this file is
3557
+ * already an Error; `code` is the recognizable, grep-stable discriminator.
3558
+ */
3559
+ export class InvalidBundleShapeError extends Error {
3560
+ code = "RECONCILE_PREFLIGHT_INVALID_SHAPE";
3561
+ issues;
3562
+ constructor(issues) {
3563
+ super(`trust.bundle failed the reconcile-preflight shape check (${issues.length} issue(s)) — see .issues for the full report`);
3564
+ this.name = "InvalidBundleShapeError";
3565
+ this.issues = issues;
3566
+ }
3567
+ }
3568
+ /**
3569
+ * Distinct, identifiable error for a publish attempt by an actor who is NOT the fresh,
3570
+ * non-superseded holder of the subject (issue #293, ADR 0021 §3) — NOT a generic Error and NOT
3571
+ * `InvalidBundleShapeError` (#356), so every publishDelivery() call site can positively
3572
+ * distinguish "refuses to publish because the bundle shape is invalid" from "refuses to publish
3573
+ * because this actor no longer holds the subject" — two genuinely distinct fail-closed tiers
3574
+ * that must never be conflated in a catch handler (a worker fixing a shape issue must not be
3575
+ * told to "re-record evidence" when the real problem is a stale/superseded claim, and vice
3576
+ * versa). Mirrors `InvalidBundleShapeError`'s shape exactly: same `extends Error` base, same
3577
+ * `readonly code` discriminator convention, same doc-comment structure — only the payload
3578
+ * differs (the effective-state/holder/reason/guidance `runVerifyHold()` computed, rather than a
3579
+ * shape-issue list).
3580
+ */
3581
+ export class NotFreshHolderError extends Error {
3582
+ code = "VERIFY_HOLD_NOT_FRESH_HOLDER";
3583
+ effective_state;
3584
+ holder;
3585
+ reason;
3586
+ guidance;
3587
+ constructor(result) {
3588
+ super(`verify-hold refused publish — not the fresh holder of this subject (${result.reason}) — see .guidance for reconcile steps`);
3589
+ this.name = "NotFreshHolderError";
3590
+ this.effective_state = result.effective_state;
3591
+ this.holder = result.holder;
3592
+ this.reason = result.reason;
3593
+ this.guidance = result.guidance;
3594
+ }
3595
+ }
3596
+ /**
3597
+ * Distinct, identifiable error for a publish attempt whose resolved `repoRoot` does not
3598
+ * positively confirm the session's sealed `trust.checkpoint.json` `commit_sha` — a FOURTH,
3599
+ * distinct fail-closed tier (#413 Facet A), never conflated with `InvalidBundleShapeError`
3600
+ * (bundle shape) or `NotFreshHolderError` (actor hold). This is the "refuse loudly when the cwd
3601
+ * repo does not match the sealed checkpoint commit_sha" fallback the issue itself proposed:
3602
+ * `publishDelivery`'s `repoRoot` is resolved by walking up from the ARTIFACT directory
3603
+ * (findRepoRootFromDirStrict), which always physically lives under the primary checkout even
3604
+ * when invoked from an unrelated worktree/repo — so a positively-confirmed mismatch here is the
3605
+ * signal that this resolved repoRoot is NOT the repo the sealed checkpoint was produced against,
3606
+ * and publishing into it would silently write to the wrong tree.
3607
+ *
3608
+ * #413 iteration-2 Fix 4: thrown for the ONE positively-determinable `mismatchKind` (see
3609
+ * checkpointHeadAncestry's doc comment) — `"positive"` (repoRoot's HEAD is confirmed NOT an
3610
+ * ancestor-or-equal of commit_sha; `headSha` is a real sha). It is intentionally NEVER thrown for
3611
+ * `"undeterminable-shallow"` (e.g. a shallow clone missing the commit object) — that case only
3612
+ * warns and allows the publish (see publishDelivery's own gate). A non-git `repoRoot` classifies
3613
+ * as `mismatchKind === "none"` (no opinion — allow; see checkpointHeadAncestry's doc comment for
3614
+ * why the iteration-2 Fix 5 refusal here was reverted in iteration-3) and never throws this error
3615
+ * either.
3616
+ */
3617
+ export class RepoHeadMismatchError extends Error {
3618
+ code = "PUBLISH_DELIVERY_REPO_HEAD_MISMATCH";
3619
+ repoRoot;
3620
+ commitSha;
3621
+ headSha;
3622
+ constructor(repoRoot, commitSha, headSha) {
3623
+ super(`publish-delivery refused — resolved repoRoot '${repoRoot}' HEAD '${headSha}' is not an ancestor-or-equal of the sealed trust.checkpoint.json commit_sha '${commitSha}'. This usually means repoRoot was resolved to the wrong checkout (e.g. invoked from a worktree whose artifact dir physically lives under a different primary checkout), or repoRoot is not a valid git working tree at all. Pass --repo-root explicitly naming the checkout whose HEAD matches '${commitSha}', or re-seal the checkpoint (seal-checkpoint) against this repoRoot's current HEAD if this really is the intended target.`);
3624
+ this.name = "RepoHeadMismatchError";
3625
+ this.repoRoot = repoRoot;
3626
+ this.commitSha = commitSha;
3627
+ this.headSha = headSha;
3628
+ }
3629
+ }
3630
+ /**
3631
+ * Human-actionable fix text per divergence type (Q2: unwaived-assumed's message always
3632
+ * carries the "waiver voided by a mixed record-evidence call" root-cause hint — shape #5 is
3633
+ * NOT a distinct predicate, it is #2 enriched, per the plan's Q2 resolution).
3634
+ */
3635
+ function preflightFixHint(type) {
3636
+ switch (type) {
3637
+ case "unwaived-assumed":
3638
+ return "FIX: make it pass for real, or re-record with --accepted-gap-reason/--waived-by on a SEPARATE record-evidence call — a command-backed check in the SAME call voids/rejects the waiver (see the command-backed-waiver guard in workflow-sidecar.ts's recordEvidence).";
3639
+ case "waiver-on-command-check":
3640
+ return "FIX: a command-backed (test_output) check cannot be waived — either drop the waiver metadata and let it reconcile against the manifest for real, or record it as a session-local (non-command) claim if it genuinely cannot be re-run.";
3641
+ case "not-run":
3642
+ return "FIX: fold this into a non-command summary (session-local claim, no execution.label), or name the EXACT verbatim manifest command in evidence.execution.label so it reconciles.";
3643
+ case "laundering":
3644
+ return "FIX: remove the exit-code-laundering operator (||, ; true, ; exit 0, etc.) from the command — a laundered command cannot be trusted to reconcile.";
3645
+ case "session-local-failed":
3646
+ return "FIX: a disputed/failing claim always blocks reconcile. Document a disjoint pre-existing failure as prose in a WAIVED non-command summary, not as a standalone claim.";
3647
+ case "status-misassertion":
3648
+ return "FIX: the claim's asserted status does not match what Surface re-derives from the bundle's own evidence/events/policies — re-record evidence so the bundle's own data supports the asserted status; do not hand-edit status.";
3649
+ case "status-underivable":
3650
+ return "FIX: CI-side status re-derivation failed for this claim — ensure @kontourai/surface is installed/resolvable and the claim's evidence/events are well-formed, then re-record.";
3651
+ case "unwaived-session-local":
3652
+ return "FIX: this claim asserts pass but has neither a waiver nor a CI-re-derived 'verified' status — add a waiver (--accepted-gap-reason/--waived-by) or resolve it so Surface derives 'verified'.";
3653
+ default:
3654
+ return "FIX: see the divergence message above for the specific shape defect.";
3655
+ }
3656
+ }
3657
+ /**
3658
+ * Callable core shared by BOTH the `reconcile-preflight` CLI handler and
3659
+ * publishDelivery()'s fail-closed gate (#356 Wave 3) — one implementation, not two entry
3660
+ * points that could drift. SHAPE-only: never spawns a fresh manifest/CI command (AC5) — the
3661
+ * only subprocess calls here are the already-cheap run-baseline.sh --manifest-json static
3662
+ * registry emit (inside resolveManifest, reused unchanged from trust-reconcile.js) and the
3663
+ * local-only derive-claim-status.mjs re-derivation (no CI command execution either).
3664
+ *
3665
+ * @param dir artifact/session directory containing trust.bundle
3666
+ * @param repoRoot repo root used for manifest resolution + the optional ancestor warning
3667
+ * @param manifestOverride optional --manifest JSON string (CLI passthrough)
3668
+ */
3669
+ /**
3670
+ * #413 Facet A: best-effort single-direction ancestor check scoped to the specific needs of
3671
+ * checkpointHeadAncestry's hard-refuse gate — is `ancestorSha` positively determinable as an
3672
+ * ancestor of (or equal to) `descendantSha` in `repoRoot`, OR positively determinable as NOT an
3673
+ * ancestor, OR is the question simply UNDETERMINABLE here (shallow clone missing the object,
3674
+ * unknown/garbage sha, git itself unusable, etc.)? This is intentionally a SEPARATE, local
3675
+ * classification from `trust-reconcile.js`'s shared `isAncestorCommit()` (which the rest of the
3676
+ * repo, including checkpointStalenessWarning's own non-blocking warning below, correctly keeps
3677
+ * as a simple best-effort boolean that "fails toward false/stale" for every non-CI caller) —
3678
+ * that collapsed boolean is exactly right for a WARNING, but wrong for a HARD REFUSE gate: a
3679
+ * shallow clone's git-object-missing failure and a genuine cross-repo mismatch both surface as
3680
+ * `false` there, yet only the second is real harm (#413 iteration-2 Fix 4). `git merge-base
3681
+ * --is-ancestor` itself already distinguishes these at the exit-code level (0 = ancestor, 1 =
3682
+ * positively NOT an ancestor, anything else / a spawn failure = underivable), so this reuses
3683
+ * that primitive directly rather than duplicating trust-reconcile.js's collapsed wrapper.
3684
+ */
3685
+ function classifyAncestry(repoRoot, ancestorSha, descendantSha) {
3686
+ if (!ancestorSha || !descendantSha)
3687
+ return "undeterminable";
3688
+ try {
3689
+ const res = spawnSync("git", ["merge-base", "--is-ancestor", ancestorSha, descendantSha], {
3690
+ cwd: repoRoot,
3691
+ stdio: "ignore",
3692
+ });
3693
+ if (!res || res.error)
3694
+ return "undeterminable";
3695
+ if (res.status === 0)
3696
+ return "ancestor";
3697
+ if (res.status === 1)
3698
+ return "not-ancestor";
3699
+ return "undeterminable"; // e.g. 128 (unknown commit, shallow clone missing the object, etc.)
3700
+ }
3701
+ catch {
3702
+ return "undeterminable";
3703
+ }
3704
+ }
3705
+ /**
3706
+ * #413 Facet A: read `trust.checkpoint.json`'s `commit_sha` (if the checkpoint exists and
3707
+ * carries one) and resolve `git rev-parse HEAD` with an EXPLICIT `{ cwd: repoRoot }` (never the
3708
+ * bare no-cwd pattern `resolveCommitSha()` uses — see that function's own doc comment for why
3709
+ * that variant is intentionally cwd-inheriting for the seal-checkpoint path, and must not be
3710
+ * reused here). Returns `{ commitSha: null }` when there is no checkpoint or no commit_sha yet
3711
+ * (a session with nothing sealed has nothing to compare against — callers must treat this as
3712
+ * "no opinion", never as a mismatch). Returns `{ commitSha, headSha, isAncestor }` when both
3713
+ * shas are resolvable. This is the ONE shared comparison both `checkpointStalenessWarning`
3714
+ * (non-blocking) and `publishDelivery`'s hard refuse gate (fail-closed) call — never a second,
3715
+ * independently-drifting git shell-out.
3716
+ *
3717
+ * #413 iteration-2 Fix 4 (scoped to the hard-refuse tier ONLY — checkpointStalenessWarning's
3718
+ * non-blocking warning is intentionally unaffected, see its own doc comment): the returned
3719
+ * `isAncestor` stays a simple boolean (`true` unless POSITIVELY determined false) for backward
3720
+ * compatibility with that warning caller, but the `mismatchKind` field lets publishDelivery's
3721
+ * hard gate distinguish these cases precisely:
3722
+ * - "none": no checkpoint, no commit_sha, `repoRoot` is not a git working tree at all (or is a
3723
+ * freshly-initialized repo with no resolvable HEAD), or the commit_sha IS an
3724
+ * ancestor-or-equal of HEAD — never refuse. A non-git `repoRoot` is a SUPPORTED flow (e.g.
3725
+ * checkpoint-signing against a bare scratch dir — see evals/integration/test_checkpoint_signing.sh
3726
+ * TEST 2), not a mismatch signal: there is no HEAD to compare against, so this is "no
3727
+ * opinion", exactly like the no-checkpoint case above.
3728
+ * - "positive": repoRoot is a real git working tree, HEAD resolves, AND commit_sha is
3729
+ * POSITIVELY determined to NOT be an ancestor of HEAD (`git merge-base --is-ancestor` exits
3730
+ * 1, a real answer, not a failure) — the genuine wrong-tree harm case; hard refuse.
3731
+ * - "undeterminable-shallow": repoRoot is a real git working tree, HEAD resolves, but whether
3732
+ * commit_sha is an ancestor of HEAD could not be determined (e.g. a shallow clone missing
3733
+ * the commit_sha object) — must NOT hard-refuse a legitimate publish from a shallow clone;
3734
+ * warn loudly and allow (the shape + verify-hold gates still stand).
3735
+ *
3736
+ * #413 iteration-2 Fix 5 (reverted, iteration-3): a prior pass hard-refused here when `repoRoot`
3737
+ * was not a git working tree at all but a sealed commit_sha existed ("a sealed delivery implies
3738
+ * the target should be a real git repo"). That premise is false — publishing against a non-git
3739
+ * `repoRoot` is a supported scratch/checkpoint-signing flow, and the refusal regressed
3740
+ * `evals/integration/test_checkpoint_signing.sh` TEST 2. The accepted residual: a non-git
3741
+ * `repoRoot` with a sealed checkpoint is ALLOWED here; wrong-tree protection for a REAL git
3742
+ * repoRoot relies on this function's ancestry (HEAD-vs-commit_sha) check plus the shape-check and
3743
+ * verify-hold gates in publishDelivery, all of which correctly no-op (allow) when there is no git
3744
+ * HEAD to compare against.
3745
+ */
3746
+ function checkpointHeadAncestry(dir, repoRoot) {
3747
+ try {
3748
+ const checkpointPath = path.join(dir, "trust.checkpoint.json");
3749
+ if (!fs.existsSync(checkpointPath))
3750
+ return { commitSha: null, headSha: null, isAncestor: true, mismatchKind: "none" };
3751
+ const checkpoint = loadJson(checkpointPath);
3752
+ const commitSha = checkpoint && typeof checkpoint === "object" ? checkpoint.commit_sha : undefined;
3753
+ if (typeof commitSha !== "string" || !commitSha)
3754
+ return { commitSha: null, headSha: null, isAncestor: true, mismatchKind: "none" };
3755
+ let headSha = "";
3756
+ try {
3757
+ headSha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
3758
+ }
3759
+ catch {
3760
+ headSha = "";
3761
+ }
3762
+ // repoRoot is not a git working tree at all (non-git scratch dir) or is a freshly-initialized
3763
+ // repo with no resolvable HEAD yet — "no opinion", never a mismatch (see doc comment above).
3764
+ if (!headSha)
3765
+ return { commitSha, headSha: null, isAncestor: true, mismatchKind: "none" };
3766
+ const classification = classifyAncestry(repoRoot, commitSha, headSha);
3767
+ const isAncestor = classification !== "not-ancestor";
3768
+ const mismatchKind = classification === "ancestor" ? "none" : classification === "not-ancestor" ? "positive" : "undeterminable-shallow";
3769
+ return { commitSha, headSha, isAncestor, mismatchKind };
3770
+ }
3771
+ catch {
3772
+ // best-effort only — a resolution failure must never be misread as a mismatch.
3773
+ return { commitSha: null, headSha: null, isAncestor: true, mismatchKind: "none" };
3774
+ }
3775
+ }
3776
+ /**
3777
+ * F4 (iteration-1): extracted from runReconcilePreflight so the main function stays under
3778
+ * the 50-line guideline. Q3 (optional, non-blocking): warn if the checkpoint's commit_sha is
3779
+ * not yet an ancestor of local HEAD — never affects ok/exit code, best-effort only. Delegates
3780
+ * to checkpointHeadAncestry (the shared comparison helper #413 Facet A's hard gate also uses)
3781
+ * so the warning path and the hard-refuse path can never independently drift. #413 iteration-2:
3782
+ * intentionally keeps using the plain `isAncestor` boolean (never `mismatchKind`) — a shallow
3783
+ * clone's undeterminable case still deserves this SAME staleness-flavored warning text, it just
3784
+ * must never become a hard refuse (see publishDelivery's own gate for that distinction).
3785
+ */
3786
+ function checkpointStalenessWarning(dir, repoRoot) {
3787
+ const warnings = [];
3788
+ const { commitSha, headSha, isAncestor } = checkpointHeadAncestry(dir, repoRoot);
3789
+ if (commitSha && headSha && !isAncestor) {
3790
+ warnings.push(`NON-BLOCKING: trust.checkpoint.json commit_sha '${commitSha}' is not an ancestor of local HEAD '${headSha}' — the checkpoint may be stale (e.g. after an amend/rebase). Consider re-sealing (seal-checkpoint) before publishing. This is a warning only — see #335 for the full checkpoint-staleness ownership check.`);
3791
+ }
3792
+ return warnings;
3793
+ }
3794
+ export function runReconcilePreflight(dir, repoRoot, manifestOverride) {
3795
+ const bundlePath = path.join(dir, "trust.bundle");
3796
+ if (!fs.existsSync(bundlePath)) {
3797
+ // A preflight with nothing to check is a usage error, not a soft pass — an agent must
3798
+ // never read "no bundle" as "bundle is valid" (see reconcilePreflightCmd for the CLI-side
3799
+ // die()). The library entrypoint throws too, since publishDelivery() itself already has
3800
+ // its OWN, separate, pre-existing fail-soft branch for bundle-absence (guarded before this
3801
+ // function is ever called there) — this function is never invoked without a bundle.
3802
+ throw new Error(`reconcile-preflight: no trust.bundle found at ${bundlePath} — nothing to check. This is a usage error, not a soft pass.`);
3803
+ }
3804
+ const bundle = loadJson(bundlePath);
3805
+ const shape = loadReconcileShapeHelper();
3806
+ const tr = loadTrustReconcileHelper();
3807
+ // Resolve the SAME canonical (fresh-verify) commands CI would fall back to feeding into
3808
+ // resolveManifest's legacy tier (tier 5), for genuine parity on that fallback path too —
3809
+ // CLI --commands is not a preflight concept, so only the TRUST_RECONCILE_COMMANDS env /
3810
+ // package.json trust-reconcile-verify tiers apply locally; a repo with neither and no
3811
+ // manifest source resolves to the same empty legacy fallback CI itself would in that case.
3812
+ const canonicalCommands = tr.resolveCanonicalCommands({ commands: [] }, repoRoot) ?? [];
3813
+ const manifestResolution = tr.resolveManifest({ manifest: manifestOverride ?? null }, repoRoot, canonicalCommands);
3814
+ const manifestByCmd = new Map();
3815
+ for (const e of manifestResolution.entries)
3816
+ manifestByCmd.set(tr.normalizeCmd(e.command), e);
3817
+ const derivedStatus = derivePreflightClaimStatuses(bundlePath, repoRoot);
3818
+ const { reconcilable, sessionLocal, noEvidenceCommand, waiverOnCommand } = shape.classifyBundleClaims(bundle);
3819
+ const issues = [];
3820
+ issues.push(...shape.waiverOnCommandIssues(waiverOnCommand));
3821
+ issues.push(...shape.noEvidenceCommandIssues(noEvidenceCommand));
3822
+ const { issues: manifestIssues } = shape.reconcilableManifestIssues(reconcilable, manifestByCmd);
3823
+ issues.push(...manifestIssues);
3824
+ // iteration-1 F1: the local preflight explicitly opts into reduced-coverage degradation
3825
+ // when re-derivation is unavailable (Surface not installed, spawn failure, etc.) — CI's
3826
+ // trust-reconcile.js does NOT opt in and stays fail-closed on the same condition (see
3827
+ // reconcile-shape.js's sessionLocalShapeIssues docstring for the full mode contract).
3828
+ const { issues: sessionLocalIssues } = shape.sessionLocalShapeIssues(sessionLocal, derivedStatus, { onUnderivable: "reduce" });
3829
+ issues.push(...sessionLocalIssues);
3830
+ const report = issues.map((i) => `${i.message} — ${preflightFixHint(i.type)}`);
3831
+ const warnings = checkpointStalenessWarning(dir, repoRoot);
3832
+ return { ok: report.length === 0, issues: report, warnings };
3833
+ }
3834
+ /**
3835
+ * reconcile-preflight <artifact-dir> [--manifest <json>] [--repo-root <path>]
3836
+ *
3837
+ * Local, pre-push shape-only check of the session's trust.bundle — reuses
3838
+ * scripts/lib/reconcile-shape.js and scripts/ci/trust-reconcile.js's own exported
3839
+ * classification/manifest-resolution so this can never silently drift from what CI's
3840
+ * Trust Reconcile job enforces. Prints every divergence with the claim id, divergence
3841
+ * type, and a human fix instruction; exits 0 with zero issues, 1 otherwise. Never spawns a
3842
+ * fresh manifest/CI command re-run (AC5) — resolves the manifest and re-derives status
3843
+ * (both local-only, no CI command execution) but never re-runs a manifest command itself.
3844
+ *
3845
+ * Usage: workflow-sidecar reconcile-preflight <artifactDir> [--manifest <json>] [--repo-root <path>]
3846
+ */
3847
+ async function reconcilePreflightCmd(p) {
3848
+ if (p.flags.has("help") || (!p.positional[0] && !p.opts["help"])) {
3849
+ if (p.flags.has("help")) {
3850
+ console.log("Usage: workflow-sidecar reconcile-preflight <artifactDir> [--manifest <json>] [--repo-root <path>]");
3851
+ console.log("Local, pre-push shape-only check of <artifactDir>/trust.bundle. Exits 0 with no issues, 1 otherwise.");
3852
+ return 0;
3853
+ }
3854
+ }
3855
+ const dir = artifactDirFrom(p.positional[0] || die("artifact directory is required"));
3856
+ const repoRoot = opt(p, "repo-root") ? path.resolve(opt(p, "repo-root")) : findRepoRootFromDirStrict(dir);
3857
+ if (!repoRoot)
3858
+ die(`reconcile-preflight: no kits/ ancestor found from ${dir}; pass --repo-root explicitly.`);
3859
+ const manifestOverride = p.opts["manifest"]?.at(-1) ?? null;
3860
+ const bundlePath = path.join(dir, "trust.bundle");
3861
+ if (!fs.existsSync(bundlePath)) {
3862
+ die(`reconcile-preflight: no trust.bundle at ${bundlePath} — a preflight with nothing to check is a usage error, not a soft pass. Record evidence first (record-evidence) before running reconcile-preflight.`);
3863
+ }
3864
+ const result = runReconcilePreflight(dir, repoRoot, manifestOverride);
3865
+ for (const w of result.warnings) {
3866
+ process.stderr.write(`[reconcile-preflight] ${w}\n`);
3867
+ }
3868
+ if (result.ok) {
3869
+ console.log(`[reconcile-preflight] OK — no shape issues found in ${bundlePath}`);
3870
+ return 0;
3871
+ }
3872
+ process.stderr.write(`[reconcile-preflight] FAILED — ${result.issues.length} shape issue(s) found in ${bundlePath}:\n`);
3873
+ for (const issue of result.issues) {
3874
+ process.stderr.write(`[reconcile-preflight] - ${issue}\n`);
3875
+ }
3876
+ return 1;
3877
+ }
3878
+ /**
3879
+ * The ONE hard-stop gate (issue #293, ADR 0021 §3): "is my actor the fresh, non-superseded
3880
+ * holder of this subject (or is the subject free/self-held)?" Reuses the SAME assignment ⋈
3881
+ * liveness join #290/#291 already built (`computeEffectiveState` + `readLocalAssignmentStatus`
3882
+ * + `readLivenessEvents`/`freshHolders`) — no second computation is invented here. This is the
3883
+ * mirror-image check, at the OTHER end of the session lifecycle, of
3884
+ * `enforceEnsureSessionOwnership`'s pre-entry guard above: that guard decides whether entry
3885
+ * should claim/supersede/refuse; this gate decides whether PUBLISH should proceed, with a
3886
+ * different (new) per-effective-state mapping — the ownership guard's "claim"/"supersede"
3887
+ * actions are wrong at publish time, so this is new interpretation of the existing join output,
3888
+ * not a new join and not a new `EffectiveState` value (there is no literal `"superseded"` state
3889
+ * — a superseded-away actor's own re-check naturally resolves to `held`(holder=successor) or
3890
+ * `reclaimable`, never `self_is_holder`; see assignment-provider.ts's `computeEffectiveState`).
3891
+ *
3892
+ * Effective-state -> publish-decision mapping (the operative spec, from the plan's table).
3893
+ * IMPORTANT (bug fix, #397): this gate fences the durable ASSIGNMENT hold, not ambient
3894
+ * liveness — liveness is advisory everywhere else in the system, and this is the ONE hard
3895
+ * gate, so it must never false-block on liveness alone. A subject with fresh liveness by
3896
+ * another actor but NO durable assignment record (`held`, reason
3897
+ * `liveness_claim_present_assignment_lagging`) therefore PASSES, not BLOCKs — there is no
3898
+ * durable ownership conflict to protect, only ambient presence. This does NOT weaken zombie
3899
+ * protection: a superseded zombie always has an assignment record (either its own stale
3900
+ * assignment — `reclaimable` — or the successor's assignment-backed `held`/
3901
+ * `fresh_liveness_heartbeat`), both of which still BLOCK below.
3902
+ * - `free` (no assignment ever recorded) -> PASS (never false-block an untracked subject)
3903
+ * - `held`, reason `self_is_holder` -> PASS (the caller IS the current holder)
3904
+ * - `held`, reason `liveness_claim_present_assignment_lagging`
3905
+ * (fresh liveness by another actor, NO durable assignment record) -> PASS (liveness alone
3906
+ * is never a durable ownership conflict — see #397 fix note above)
3907
+ * - `held`, reason `fresh_liveness_heartbeat`
3908
+ * (durable assignment held by another actor + fresh liveness) -> BLOCK (a different
3909
+ * actor durably holds this subject and is demonstrably still live)
3910
+ * - `reclaimable` (assignment present, stale/absent liveness) -> BLOCK (not proof of
3911
+ * self — safe default blocks; a durable assignment record exists)
3912
+ * - `human-held` -> BLOCK (never publish over a human assignee)
3913
+ * - no resolvable join at all (non-local-file provider
3914
+ * with no --effective-state-json) -> `not_evaluated`, PASS (documented scope
3915
+ * boundary, loud stderr note, never a silent block)
3916
+ *
3917
+ * Actor resolution mirrors `enforceEnsureSessionOwnership` EXACTLY: the bare
3918
+ * `resolveActor(env).actor` / branchActorKey string, NEVER `serializeActor(actorStruct)`'s
3919
+ * triple — the #291 flat-vs-triple seam. `opts.actorKey` (the CLI's --actor / FLOW_AGENTS_ACTOR
3920
+ * override, already sanitized by the caller) takes precedence when provided.
3921
+ *
3922
+ * Slug/artifactRoot derivation matches `publishDelivery()`'s own `slug =
3923
+ * path.basename(path.resolve(dir))` byte-for-byte (both must resolve the SAME assignment
3924
+ * record) and the `artifactRoot = path.dirname(dir)` pattern already used elsewhere in this
3925
+ * file for a `dir`-only consumer.
3926
+ *
3927
+ * github provider: read-only precomputed `--effective-state-json` escape hatch, matching
3928
+ * `enforceEnsureSessionOwnership`'s existing github branch precedent exactly (render-don't-
3929
+ * execute — assignment-provider.ts never calls `gh` directly from this CLI).
3930
+ *
3931
+ * Every interpolated actor/holder/reason string is sanitized via
3932
+ * `stripControlCharsForDisplay(...).slice(0, 64)` — reusing the exact top-level helper, never a
3933
+ * second sanitizer (AC7).
3934
+ *
3935
+ * SECOND CI-blocking false-block fix (this iteration): the hard gate above enforces ONLY for a
3936
+ * STABLY-identified actor. A caller's identity is STABLE when it comes from an explicit
3937
+ * `opts.actorKey` (a caller that hands in an actor key is asserting a stable identity — e.g. the
3938
+ * CLI's --actor / FLOW_AGENTS_ACTOR override, or the github skill's precomputed path), from
3939
+ * `FLOW_AGENTS_ACTOR` (`resolveActor` source `"explicit-override"`), or from a runtime-native
3940
+ * session id (`resolveActor` source `` `runtime-session-id:${runtime}` ``, e.g. Claude Code's
3941
+ * `CLAUDE_CODE_SESSION_ID`). It is UNSTABLE when `resolveActor` falls all the way through to the
3942
+ * process-ancestry fallback (source `"process-ancestry"`) or fails to resolve at all (source
3943
+ * `"unresolved"` / `isUnresolvedActor(actor)`). This mirrors `enforceEnsureSessionOwnership`'s
3944
+ * Design Decision 4 (never hard-fail on actor ambiguity): a session that cannot stably
3945
+ * self-identify cannot be meaningfully fenced against a durable assignment record, so hard-
3946
+ * blocking it produces exactly the false-block CI hit (no `FLOW_AGENTS_ACTOR`/runtime session id
3947
+ * in CI -> ancestry fallback -> a DIFFERENT ancestry-derived actor string than the one that
3948
+ * created the claim -> `reclaimable`/not-self -> hard BLOCK of a legitimate self-publish). A
3949
+ * real coordination participant always has a stable identity (explicit override or runtime
3950
+ * session id), so zombie protection under a stable actor is completely unaffected — this only
3951
+ * changes behavior for a caller that was never fenceable in the first place. When the resolved
3952
+ * actor identity is UNSTABLE, this function short-circuits to `{ ok: true, effective_state:
3953
+ * "not_evaluated", reason: "actor-identity-unstable-advisory-only" }` (holder included, sanitized,
3954
+ * when one exists) BEFORE running the assignment ⋈ liveness join at all, with one loud stderr
3955
+ * note — the gate degrades to advisory-only rather than ever false-blocking an unstable identity.
3956
+ * When the actor identity IS stable, the effective-state -> publish-decision mapping above
3957
+ * applies exactly as documented, unchanged.
3958
+ */
3959
+ export function runVerifyHold(dir, repoRoot, opts) {
3960
+ // repoRoot is accepted (not derived) for signature symmetry with runReconcilePreflight(dir,
3961
+ // repoRoot, ...) / publishDelivery(dir, repoRoot) — the local-file join below only needs
3962
+ // artifactRoot/slug, but a future non-local-file provider branch that resolves a live
3963
+ // repo-relative fixture would need it, so the parameter stays part of the public contract.
3964
+ void repoRoot;
3965
+ const sanitize = (value) => stripControlCharsForDisplay(value).slice(0, 64);
3966
+ const slug = path.basename(path.resolve(dir));
3967
+ const artifactRoot = path.dirname(path.resolve(dir));
3968
+ const nowMs = opts?.now ?? Date.now();
3969
+ const assignmentProviderKind = opts?.assignmentProviderKind || "local-file";
3970
+ const helper = loadActorIdentityHelper();
3971
+ // Stability check (SECOND CI-blocking false-block fix, this iteration): an explicitly-provided
3972
+ // opts.actorKey is treated as stable outright (the caller is asserting a stable identity — see
3973
+ // doc comment above). Otherwise resolve BOTH the actor and its source so we can tell an
3974
+ // explicit-override / runtime-session-id actor (stable, enforce as today) apart from a
3975
+ // process-ancestry / unresolved one (unstable, advisory-only — never hard-block).
3976
+ const resolved = opts?.actorKey ? { actor: opts.actorKey, source: "explicit-override" } : helper.resolveActor(process.env);
3977
+ const actorKey = resolved.actor;
3978
+ const isStableActor = !!opts?.actorKey
3979
+ || resolved.source === "explicit-override"
3980
+ || resolved.source.startsWith("runtime-session-id")
3981
+ // #398: a CI-runtime actor is STABLE across every subprocess in a CI job (derived from the
3982
+ // provider's published run/job identifiers), so the verify-hold gate ENFORCES for CI sessions
3983
+ // instead of degrading to advisory — the root fix for the #293 CI false-block workaround.
3984
+ || resolved.source.startsWith("ci-runtime");
3985
+ const guidanceLines = (holderActor) => [
3986
+ "Re-run pull-work/pickup-probe to discover the current holder of this subject and hand off cleanly (learning-review/handoff) rather than publishing over it.",
3987
+ holderActor
3988
+ ? `The current holder appears to be ${sanitize(holderActor)} — confirm with them before proceeding.`
3989
+ : "Confirm with the assigned human before proceeding.",
3990
+ "If a human confirms this session should resume ownership, run `ensure-session --supersede-stale` to explicitly re-claim the subject before retrying publish.",
3991
+ ];
3992
+ let effective = null;
3993
+ if (opts?.effectiveStateJson !== undefined) {
3994
+ const parsed = opts.effectiveStateJson;
3995
+ const candidate = parsed && typeof parsed === "object" ? parsed.effective : undefined;
3996
+ const validStates = new Set(["held", "reclaimable", "human-held", "free"]);
3997
+ if (candidate && typeof candidate.effective_state === "string" && validStates.has(candidate.effective_state)) {
3998
+ effective = candidate;
3999
+ }
4000
+ }
4001
+ else if (assignmentProviderKind === "local-file") {
4002
+ // Same call shape as enforceEnsureSessionOwnership's local-file branch — no second
4003
+ // freshness/ownership computation is invented (see that function's F1 fix comment for why
4004
+ // branchActorKey, not the serialized ActorStruct triple, is the correct selfActor here).
4005
+ const assignment = readLocalAssignmentStatus(artifactRoot, slug);
4006
+ const events = readLivenessEvents(artifactRoot);
4007
+ const freshList = loadLivenessReadHelper().freshHolders(events, slug, actorKey, nowMs);
4008
+ effective = computeEffectiveState(assignment, freshList, actorKey, nowMs);
4009
+ }
4010
+ if (!effective) {
4011
+ // Documented scope boundary (Design Constraint): a non-local-file provider with no
4012
+ // precomputed --effective-state-json cannot be evaluated in-CLI (render-don't-execute — no
4013
+ // live `gh` call from workflow-sidecar.ts). PASS-through, never a silent block, with a loud
4014
+ // stderr note — mirroring enforceEnsureSessionOwnership's existing github branch precedent.
4015
+ process.stderr.write(`[verify-hold] not evaluated: provider "${sanitize(assignmentProviderKind)}" requires --effective-state-json (or use --assignment-provider local-file)\n`);
4016
+ return { ok: true, effective_state: "not_evaluated", reason: "provider_not_evaluated", guidance: [] };
4017
+ }
4018
+ // F1 fix (fix-plan iteration 1, HIGH): sanitize EVERY untrusted string field of
4019
+ // effective.holder before it reaches the returned JSON / NotFreshHolderError.holder — never
4020
+ // spread the raw holder and override only the discriminated field. `last_at` (sourced from
4021
+ // record.claimed_at or a liveness event's `at`, both attacker-writable in the shared
4022
+ // multi-writer liveness/assignment stream) and `actor`/`assignee` are all display strings and
4023
+ // go through the SAME `sanitize` helper (stripControlCharsForDisplay(...).slice(0, 64)) as
4024
+ // enforceEnsureSessionOwnership's equivalent call sites (AC7 injection-discipline parity).
4025
+ // `idle_days` is a `number | null` computed by computeEffectiveState from Date.parse/Math.floor
4026
+ // arithmetic (assignment-provider.ts) — never an attacker-controlled string — so it is passed
4027
+ // through as-is, but defensively re-coerced with `typeof === "number"` so a future shape change
4028
+ // upstream can never smuggle a string through this field.
4029
+ const sanitizeHolder = (holder) => {
4030
+ if (!holder)
4031
+ return undefined;
4032
+ return {
4033
+ actor: holder.actor ? sanitize(holder.actor) : undefined,
4034
+ assignee: holder.assignee ? sanitize(holder.assignee) : holder.assignee,
4035
+ idle_days: typeof holder.idle_days === "number" ? holder.idle_days : undefined,
4036
+ last_at: holder.last_at ? sanitize(holder.last_at) : undefined,
4037
+ };
4038
+ };
4039
+ // SECOND CI-blocking false-block fix (this iteration): an actor identity that cannot stably
4040
+ // self-identify (process-ancestry fallback or unresolved) cannot be meaningfully fenced against
4041
+ // a durable assignment record — hard-blocking it is exactly the CI false-block this fix targets
4042
+ // (see doc comment above). Degrade to advisory-only: never hard-block, regardless of what the
4043
+ // join above computed. This check runs AFTER the join so an existing holder (if any) can still
4044
+ // be surfaced for visibility, but strictly BEFORE the effective-state switch below so no
4045
+ // unstable-actor request can ever reach a `case` that returns `ok: false`.
4046
+ if (!isStableActor) {
4047
+ process.stderr.write("[verify-hold] actor identity is ancestry-derived/unresolved — gate is advisory only for unstable identities; not hard-blocking publish\n");
4048
+ return {
4049
+ ok: true,
4050
+ effective_state: "not_evaluated",
4051
+ reason: "actor-identity-unstable-advisory-only",
4052
+ guidance: [],
4053
+ ...(effective.holder ? { holder: sanitizeHolder(effective.holder) } : {}),
4054
+ };
4055
+ }
4056
+ switch (effective.effective_state) {
4057
+ case "free":
4058
+ return { ok: true, effective_state: "free", reason: effective.reason, guidance: [] };
4059
+ case "held": {
4060
+ const isSelf = effective.reason === "self_is_holder" || (!!effective.holder?.actor && effective.holder.actor === actorKey);
4061
+ if (isSelf)
4062
+ return { ok: true, effective_state: "held", holder: sanitizeHolder(effective.holder), reason: effective.reason, guidance: [] };
4063
+ // Bug fix (#397): `liveness_claim_present_assignment_lagging` means computeEffectiveState
4064
+ // found NO durable assignment record at all — only ambient liveness by another actor
4065
+ // (assignment-provider.ts's `if (!isAssigned) { if (freshHoldersList.length > 0) return
4066
+ // held/liveness_claim_present_assignment_lagging }`). Liveness alone is advisory
4067
+ // everywhere else in this system; this ONE hard gate must fence the durable ASSIGNMENT
4068
+ // hold, not ambient presence, so this case PASSES rather than false-blocking. Every other
4069
+ // `held` reason (`fresh_liveness_heartbeat`) is reached only when an assignment record
4070
+ // DOES exist (assignment-provider.ts's `isAssigned` branch) and the recorded holder is
4071
+ // still fresh-live — a genuine durable-ownership conflict, which still BLOCKs below.
4072
+ if (effective.reason === "liveness_claim_present_assignment_lagging") {
4073
+ return { ok: true, effective_state: "held", holder: sanitizeHolder(effective.holder), reason: effective.reason, guidance: [] };
4074
+ }
4075
+ const holderActor = effective.holder?.actor;
4076
+ return {
4077
+ ok: false,
4078
+ effective_state: "held",
4079
+ holder: sanitizeHolder(effective.holder),
4080
+ reason: `subject ${sanitize(slug)} is currently held by a different, still-live actor (${sanitize(holderActor ?? "unknown")})`,
4081
+ guidance: guidanceLines(holderActor),
4082
+ };
4083
+ }
4084
+ case "reclaimable": {
4085
+ // Stop-short risk (plan): reclaimable is NEVER treated as PASS. A lapsed self-claim looks
4086
+ // reclaimable, not self_is_holder, to a woken zombie's own re-check — the safe default
4087
+ // blocks and asks for reconcile guidance rather than auto-passing a stale self-claim.
4088
+ const holderActor = effective.holder?.actor;
4089
+ return {
4090
+ ok: false,
4091
+ effective_state: "reclaimable",
4092
+ holder: sanitizeHolder(effective.holder),
4093
+ reason: `subject ${sanitize(slug)}'s existing claim (held by ${sanitize(holderActor ?? "unknown")}) is stale/unverified as self — not a confirmed fresh hold`,
4094
+ guidance: guidanceLines(holderActor),
4095
+ };
4096
+ }
4097
+ case "human-held": {
4098
+ const assignee = effective.holder?.assignee;
4099
+ return {
4100
+ ok: false,
4101
+ effective_state: "human-held",
4102
+ holder: sanitizeHolder(effective.holder),
4103
+ reason: `subject ${sanitize(slug)} is assigned to ${assignee ? sanitize(assignee) : "an assigned human"} — never publish over a human assignment without confirmation`,
4104
+ guidance: guidanceLines(undefined),
4105
+ };
4106
+ }
4107
+ default:
4108
+ return { ok: true, effective_state: "not_evaluated", reason: "unrecognized_effective_state", guidance: [] };
4109
+ }
4110
+ }
4111
+ /**
4112
+ * verify-hold <artifact-dir> [--actor <key>] [--now <iso>] [--assignment-provider <kind>]
4113
+ * [--effective-state-json <path|->]
4114
+ *
4115
+ * CLI surface for runVerifyHold() (issue #293). Prints `{ role: "VerifyHoldResult", ... }` JSON
4116
+ * and exits 0 when `ok` (including `not_evaluated` — a documented scope boundary is never a
4117
+ * failure exit), 1 otherwise. NEVER throws at the CLI boundary — matches
4118
+ * `reconcilePreflightCmd`'s existing convention of printing then exiting rather than throwing;
4119
+ * the thrown `NotFreshHolderError` variant is reserved for the LIBRARY call inside
4120
+ * `publishDelivery()`.
4121
+ *
4122
+ * Usage: workflow-sidecar verify-hold <artifactDir> [--actor <key>] [--now <iso>]
4123
+ * [--assignment-provider <kind>] [--effective-state-json <path|->]
4124
+ */
4125
+ async function verifyHoldCmd(p) {
4126
+ if (p.flags.has("help") || (!p.positional[0] && !p.opts["help"])) {
4127
+ if (p.flags.has("help")) {
4128
+ console.log("Usage: workflow-sidecar verify-hold <artifactDir> [--actor <key>] [--now <iso>] [--assignment-provider <kind>] [--effective-state-json <path|->]");
4129
+ console.log("Checks whether the calling actor is the fresh, non-superseded holder of <artifactDir>'s subject. Exits 0 if ok (including not_evaluated), 1 otherwise.");
4130
+ return 0;
4131
+ }
4132
+ }
4133
+ const dir = artifactDirFrom(p.positional[0] || die("artifact directory is required"));
4134
+ const repoRoot = opt(p, "repo-root") ? path.resolve(opt(p, "repo-root")) : findRepoRootFromDirStrict(dir);
4135
+ // SECOND CI-blocking false-block fix (this iteration): only pass an explicit actorKey through
4136
+ // to runVerifyHold when the CALLER explicitly passed --actor — that is the one case where an
4137
+ // actorKey should be treated as an asserted-stable identity (see runVerifyHold's doc comment).
4138
+ // When --actor is omitted, actorKey is left undefined so runVerifyHold performs its OWN
4139
+ // resolveActor(process.env) call internally and can see the real `source` (explicit-override /
4140
+ // runtime-session-id / process-ancestry / unresolved) to decide stability — calling
4141
+ // resolveReadActorKey(p) here first would discard that source and wrongly force every ambient
4142
+ // resolution (including an ancestry fallback) to be treated as an explicit/stable actorKey.
4143
+ const actorKey = opt(p, "actor") ? loadActorIdentityHelper().sanitizeSegment(opt(p, "actor")) : undefined;
4144
+ const nowMs = opt(p, "now") ? Date.parse(opt(p, "now")) : undefined;
4145
+ const assignmentProviderKind = opt(p, "assignment-provider", "local-file");
4146
+ const effectiveStateJsonFlag = opt(p, "effective-state-json");
4147
+ const effectiveStateJson = effectiveStateJsonFlag ? loadJsonInputFile(effectiveStateJsonFlag) : undefined;
4148
+ const result = runVerifyHold(dir, repoRoot, { actorKey, now: nowMs, assignmentProviderKind, effectiveStateJson });
4149
+ printJson({ role: "VerifyHoldResult", ...result });
4150
+ return result.ok ? 0 : 1;
4151
+ }
4152
+ // ─── Takeover Preflight (#294, ADR 0021 §5) ───────────────────────────────────
4153
+ /**
4154
+ * Render (never execute) the takeover protocol for a candidate the skill has selected. Takeover is
4155
+ * RESUMPTION, not restart: when a subject is `reclaimable` (a durable assignment whose incumbent is
4156
+ * no longer heartbeating), a successor must (1) grace-beat — wait one heartbeat interval and re-check,
4157
+ * backing off if the incumbent revives — (2) supersede via `ensure-session --supersede-stale`, and
4158
+ * (3) CONTINUE THE INCUMBENT'S BRANCH (from the incumbent's claim record), never a parallel one, and
4159
+ * re-enter the SAME artifact dir (deterministic slug). This function computes the effective state
4160
+ * (the same assignment ⋈ liveness join verify-hold/ensure-session use) and emits the appropriate
4161
+ * action + the incumbent's `resume_branch`; the skill executes the beat/supersede/git steps.
4162
+ *
4163
+ * Race-safety is CLI-enforced at supersede time, not here: `ensure-session --supersede-stale`
4164
+ * re-computes the state and refuses (dies on `held`) if the incumbent revived during the beat, so a
4165
+ * successor that skipped or lost the grace race still cannot supersede a live incumbent (AC2a).
4166
+ *
4167
+ * ADVISORY, not a gate: the assignment ⋈ liveness JOIN is identical to verify-hold's, but this render
4168
+ * only advises the skill which action to take — the ACTUAL enforcement is `ensure-session
4169
+ * --supersede-stale` (re-check under a subject lock). So it deliberately does NOT replicate
4170
+ * verify-hold's #398 `isStableActor` tiering (which exists there only because verify-hold is a hard
4171
+ * publish BLOCK that must not false-block an unstable/ancestry identity): a wrong self-identification
4172
+ * here yields only a wrong advisory string, never a wrong mutation.
4173
+ *
4174
+ * Ordering note: ADR 0021 §5's literal wording is supersede→grace→maybe-undo; this implements
4175
+ * grace→recheck→supersede (never write until the beat confirms the incumbent stayed stale) — a
4176
+ * deliberate, safer variant that preserves the ADR's intent ("laptop just woke resolves in the
4177
+ * incumbent's favor") without a premature write to walk back.
4178
+ *
4179
+ * All untrusted fields (incumbent actor / branch / last_at, sourced from the shared multi-writer
4180
+ * assignment+liveness stream) pass through `sanitize`/`sanitizeWide` (stripControlCharsForDisplay +
4181
+ * the repo's 64/240 cap tiers — branch uses the 240 free-text tier so a valid long branch is never
4182
+ * truncated into a bad checkout target) — the #287/#320/#293 injection class.
4183
+ */
4184
+ export function runTakeoverPreflight(dir, opts) {
4185
+ const sanitize = (value) => stripControlCharsForDisplay(value).slice(0, 64);
4186
+ // Branch names use the repo's 240-char free-text tier (matching assignment-provider.ts's
4187
+ // sanitizeDisplayField(record.branch, 240)), NOT the 64-char id tier: a realistic
4188
+ // `agent/<actor>/<slug>` branch can exceed 64 chars, and truncating `resume_branch` would hand the
4189
+ // skill a `git checkout <truncated>` target that does not exist — defeating the resume-the-branch
4190
+ // guarantee. Control chars are still stripped (injection), only the cap widens.
4191
+ const sanitizeWide = (value) => stripControlCharsForDisplay(value).slice(0, 240);
4192
+ const slug = path.basename(path.resolve(dir));
4193
+ const artifactRoot = path.dirname(path.resolve(dir));
4194
+ const nowMs = opts?.now ?? Date.now();
4195
+ const helper = loadActorIdentityHelper();
4196
+ const actorKey = opts?.actorKey ? helper.sanitizeSegment(opts.actorKey) : helper.resolveActor(process.env).actor;
4197
+ const graceSeconds = opts?.graceSeconds ?? loadLivenessPolicyHelper().resolveHeartbeatThrottleSeconds(process.env);
4198
+ const assignment = readLocalAssignmentStatus(artifactRoot, slug);
4199
+ const events = readLivenessEvents(artifactRoot);
4200
+ const freshList = loadLivenessReadHelper().freshHolders(events, slug, actorKey, nowMs);
4201
+ const effective = computeEffectiveState(assignment, freshList, actorKey, nowMs);
4202
+ const reason = sanitize(effective.reason);
4203
+ const holderActor = effective.holder?.actor ? sanitize(effective.holder.actor) : undefined;
4204
+ const holderLastAt = effective.holder?.last_at ? sanitize(effective.holder.last_at) : undefined;
4205
+ switch (effective.effective_state) {
4206
+ case "reclaimable": {
4207
+ // The incumbent's branch is the resume target — read it from the pre-supersede record, never
4208
+ // derive a new one (AC1: takeover continues the incumbent's branch, no parallel branch).
4209
+ const resumeBranch = assignment.record?.branch ? sanitizeWide(assignment.record.branch) : undefined;
4210
+ return {
4211
+ ok: true,
4212
+ action: "grace-then-supersede",
4213
+ effective_state: "reclaimable",
4214
+ reason,
4215
+ holder: { actor: holderActor, last_at: holderLastAt },
4216
+ ...(resumeBranch ? { resume_branch: resumeBranch } : {}),
4217
+ grace_seconds: graceSeconds,
4218
+ next_steps: [
4219
+ `Grace beat: wait ${graceSeconds}s (one heartbeat interval) for the incumbent to revive.`,
4220
+ `Re-run \`workflow-sidecar takeover-preflight ${slug}\`; if it now reports action "back-off" the incumbent revived — STOP and reselect.`,
4221
+ `If still "grace-then-supersede", run \`ensure-session --supersede-stale\` to take over (it re-checks and refuses if the incumbent revived), recording the audit trail.`,
4222
+ resumeBranch
4223
+ ? `Continue the incumbent's branch: \`git fetch origin ${resumeBranch} && git checkout ${resumeBranch}\` — NEVER create a new branch. Re-enter the existing artifact dir (deterministic slug); do not restart the plan.`
4224
+ : `Re-enter the existing artifact dir (deterministic slug) and continue the incumbent's branch from state.json.branch — never a new branch; do not restart the plan.`,
4225
+ ],
4226
+ };
4227
+ }
4228
+ case "held": {
4229
+ const selfIsHolder = effective.reason === "self_is_holder";
4230
+ return {
4231
+ ok: selfIsHolder,
4232
+ action: selfIsHolder ? "proceed" : "back-off",
4233
+ effective_state: "held",
4234
+ reason,
4235
+ holder: { actor: holderActor, last_at: holderLastAt },
4236
+ next_steps: selfIsHolder
4237
+ ? ["This subject is already held by you — proceed with your existing session; no takeover needed."]
4238
+ : [`The incumbent is live/revived (held by ${holderActor ?? "another actor"}). Back off — do NOT supersede a live holder — and reselect a different item.`],
4239
+ };
4240
+ }
4241
+ case "human-held": {
4242
+ return {
4243
+ ok: false,
4244
+ action: "ask-first",
4245
+ effective_state: "human-held",
4246
+ reason,
4247
+ holder: { actor: holderActor, last_at: holderLastAt },
4248
+ next_steps: [`A human is assigned (${holderActor ?? "assignee"}). Ask first — never auto-supersede a human assignment (ADR 0021 §6).`],
4249
+ };
4250
+ }
4251
+ case "free":
4252
+ default: {
4253
+ return {
4254
+ ok: true,
4255
+ action: "claim",
4256
+ effective_state: "free",
4257
+ reason,
4258
+ next_steps: ["No durable claim to supersede — this is a normal claim, not a takeover. Run `ensure-session` to claim it."],
4259
+ };
4260
+ }
4261
+ }
4262
+ }
4263
+ async function takeoverPreflightCmd(p) {
4264
+ if (p.flags.has("help")) {
4265
+ console.log("Usage: workflow-sidecar takeover-preflight <artifactDir> [--actor <key>] [--now <iso>] [--grace-seconds <n>]");
4266
+ console.log("Renders the ADR 0021 §5 takeover protocol (grace-then-supersede | back-off | claim | ask-first | proceed) for a reclaimable candidate. Read-only; never mutates.");
4267
+ return 0;
4268
+ }
4269
+ const dir = artifactDirFrom(p.positional[0] || die("artifact directory is required"));
4270
+ const actorKey = opt(p, "actor") ? loadActorIdentityHelper().sanitizeSegment(opt(p, "actor")) : undefined;
4271
+ const nowMs = opt(p, "now") ? Date.parse(opt(p, "now")) : undefined;
4272
+ const graceSeconds = opt(p, "grace-seconds") ? Number(opt(p, "grace-seconds")) : undefined;
4273
+ const result = runTakeoverPreflight(dir, { actorKey, now: nowMs, graceSeconds });
4274
+ printJson({ role: "TakeoverPreflight", ...result });
4275
+ return result.ok ? 0 : 1;
4276
+ }
2599
4277
  // ─── Publish Delivery Bundle ──────────────────────────────────────────────────
2600
4278
  // Copies the session's trust.bundle (+ checkpoint companions) from the gitignored
2601
4279
  // session artifact dir (.kontourai/flow-agents/<slug>/) to the committed delivery/ transport
@@ -2606,52 +4284,47 @@ async function sealCheckpoint(p) {
2606
4284
  // Called automatically from recordRelease and advanceState→delivered (best-effort).
2607
4285
  // Also exposed as the `publish-delivery <artifact-dir>` subcommand for explicit use.
2608
4286
  /**
2609
- * #379 supersede-on-publish cleanup: keep delivery/ bounded by pruning inherited PER-SESSION
2610
- * seal dirs (the growth vector), scoped to avoid any cross-PR conflict.
2611
- *
2612
- * An inherited per-session seal dir (`delivery/<other-slug>/`) is UNIQUELY named, so pruning
2613
- * it can never conflict with a concurrent PR: two branches deleting the same inherited dir is
2614
- * a delete/delete (auto-merges), and each new delivery adds its OWN distinct
2615
- * `delivery/<slug>/`. And it is HARMLESS to leave: trust-reconcile.js's prefer-newest
2616
- * ownership selection always picks THIS session's fresher bundle over an older inherited one.
2617
- * Pruning is therefore purely to stop unbounded accumulation of permanently-superseded dirs.
2618
- *
2619
- * The SHARED FLAT path (`delivery/trust.bundle` + checkpoints) is deliberately NOT pruned
2620
- * here. During the migration window other concurrent PRs may still seal to the flat path;
2621
- * deleting it would produce a modify/delete conflict a DIRTY PR the no-CI failure this
2622
- * whole change fixes. The flat path is a single fixed location (not a growth vector) and the
2623
- * reconciler treats a stale flat bundle as non-owning / older-owning, so leaving it is safe.
2624
- * Removing the flat legacy seals is a one-time cleanup for a dedicated PR once no open PR
2625
- * still seals to it intentionally NOT bundled into every delivery.
4287
+ * #413 Facet B: prune ONLY keepSlug's OWN prior seal — NEVER another session's
4288
+ * `delivery/<other-slug>/` directory.
4289
+ *
4290
+ * This function previously (#379) deleted ANY non-keepSlug directory under delivery/ that
4291
+ * "looked like a seal" (contained a trust.bundle or trust.checkpoint.json), on the theory that
4292
+ * an inherited per-session seal dir is harmless to leave and therefore harmless to delete too.
4293
+ * That theory was correct about harmlessness-if-left but did not follow that deletion was
4294
+ * therefore SAFE: issue #413's own corrected evidence reports this exact cross-slug loop
4295
+ * deleted a DIFFERENT, still-in-flight actor's active seal on a different branch
4296
+ * (`delivery/kontourai-flow-agents-349/`) — a real, observed destructive side effect with no
4297
+ * compensating correctness benefit. trust-reconcile.js's own PREFER-NEWEST doc comment
4298
+ * (resolveDeliveryCandidates, ~line 480-491) already establishes that leaving an
4299
+ * inherited/older seal in place is harmless the reconciler always selects the newest owning
4300
+ * bundle regardless of what else is present so there is no correctness reason to prune
4301
+ * ANOTHER session's seal at all, ever. The safest fix (and the one issue #413's own corrected
4302
+ * comment endorses "never prune another session's active seal", no same-branch carve-out) is
4303
+ * to stop cross-slug pruning entirely, not merely narrow its blast radius.
4304
+ *
4305
+ * The only pruning responsibility that legitimately remains here is keepSlug's OWN prior seal:
4306
+ * publishDelivery() is about to freshly (re)write `delivery/<keepSlug>/trust.bundle` and its
4307
+ * companions, but `fs.copyFileSync` only overwrites files that exist in the CURRENT session dir
4308
+ * — a companion that existed in a PRIOR publish of this exact slug (e.g.
4309
+ * trust.checkpoint.sig.json) but is absent from this publish would otherwise linger stale
4310
+ * alongside the freshly-written files. Removing keepSlug's own existing directory before it is
4311
+ * recreated (by the caller, immediately after this call) avoids that same-slug staleness
4312
+ * without touching any OTHER slug's directory.
2626
4313
  *
2627
4314
  * Best-effort: a prune failure is logged, never fatal to the delivery. Never touches
2628
- * README.md, DECLARED, the flat seal files, or any subdir that is not itself a seal dir.
4315
+ * README.md, DECLARED, the flat seal files (delivery/trust.bundle at the shared flat path,
4316
+ * deliberately untouched — see the historical #379 rationale on the flat-path migration
4317
+ * window), or any directory other than keepSlug's own.
2629
4318
  */
2630
4319
  function pruneSupersededSeals(deliveryDir, keepSlug) {
2631
- let entries = [];
4320
+ const ownDir = path.join(deliveryDir, keepSlug);
4321
+ if (!fs.existsSync(ownDir))
4322
+ return; // nothing to prune yet — first publish for this slug.
2632
4323
  try {
2633
- entries = fs.readdirSync(deliveryDir, { withFileTypes: true });
4324
+ fs.rmSync(ownDir, { recursive: true, force: true });
2634
4325
  }
2635
- catch {
2636
- entries = [];
2637
- }
2638
- for (const entry of entries) {
2639
- if (!entry.isDirectory() || entry.name === keepSlug)
2640
- continue;
2641
- const subdir = path.join(deliveryDir, entry.name);
2642
- // Only prune dirs that actually look like a seal dir (contain a trust.bundle or
2643
- // trust.checkpoint.json) — never an unrelated directory a human placed under delivery/.
2644
- const looksLikeSeal = fs.existsSync(path.join(subdir, "trust.bundle")) ||
2645
- fs.existsSync(path.join(subdir, "trust.checkpoint.json"));
2646
- if (!looksLikeSeal)
2647
- continue;
2648
- try {
2649
- fs.rmSync(subdir, { recursive: true, force: true });
2650
- process.stderr.write(`[publish-delivery] #379: pruned superseded per-session seal delivery/${entry.name}/ (older-owning/stale; the reconciler selects the newest bundle regardless)\n`);
2651
- }
2652
- catch (err) {
2653
- process.stderr.write(`[publish-delivery] #379: could not prune per-session seal delivery/${entry.name}/ (non-fatal): ${err instanceof Error ? err.message : String(err)}\n`);
2654
- }
4326
+ catch (err) {
4327
+ process.stderr.write(`[publish-delivery] #413: could not prune this session's own prior seal delivery/${keepSlug}/ before rewriting it (non-fatal, publish continues): ${err instanceof Error ? err.message : String(err)}\n`);
2655
4328
  }
2656
4329
  }
2657
4330
  /**
@@ -2679,6 +4352,55 @@ function pruneSupersededSeals(deliveryDir, keepSlug) {
2679
4352
  * evals/integration/test_checkpoint_signing.sh TEST 2 and the WS5 session findings at
2680
4353
  * .kontourai/flow-agents/ws5-governance-kit-slice1 for the root cause this fixes).
2681
4354
  * Idempotent: overwrites on re-delivery to the same slug.
4355
+ *
4356
+ * #356 Wave 3 (AC6): Fail-CLOSED on bundle SHAPE. After the fail-soft absence guard below,
4357
+ * runs the SAME reconcile-preflight shape check (runReconcilePreflight) the
4358
+ * `reconcile-preflight` CLI subcommand exposes, BEFORE copying anything into delivery/. A
4359
+ * shape-invalid bundle throws InvalidBundleShapeError (a distinct, identifiable error — see
4360
+ * its own doc comment) rather than silently publishing a bundle CI's Trust Reconcile job
4361
+ * would reject anyway. This is intentionally a NEW, additive fail-closed branch — it must
4362
+ * never be conflated with the pre-existing fail-soft absence/repo-root branches above/below,
4363
+ * which stay exactly as before (see each publishDelivery call site's catch handler for how
4364
+ * the distinction is preserved end-to-end).
4365
+ *
4366
+ * #293 (THIRD, DISTINCT fail-closed gate): immediately after the shape check above and BEFORE
4367
+ * writing anything into delivery/, runs `runVerifyHold()` — the assignment ⋈ liveness join
4368
+ * asking "is the calling actor the fresh, non-superseded holder of this subject (or is it
4369
+ * free/self-held)?" A not-fresh-holder result throws `NotFreshHolderError` (distinct from
4370
+ * `InvalidBundleShapeError` — a different `code`, a different failure mode: actor hold vs
4371
+ * bundle shape).
4372
+ *
4373
+ * #413 Facet A (FOURTH, DISTINCT fail-closed gate): immediately after the verify-hold gate and
4374
+ * BEFORE writing anything into delivery/, compares the resolved `repoRoot`'s `git rev-parse
4375
+ * HEAD` against the session's sealed `trust.checkpoint.json` `commit_sha` (via the shared
4376
+ * checkpointHeadAncestry() helper — the SAME ancestor-check checkpointStalenessWarning already
4377
+ * used as a non-blocking warning). Throws `RepoHeadMismatchError` (distinct from both other
4378
+ * error tiers) instead of silently publishing into what is very likely the WRONG repo (e.g.
4379
+ * `repoRoot` resolved to the primary checkout via findRepoRootFromDirStrict's artifact-dir
4380
+ * walk, even though this session's checkpoint was sealed against a DIFFERENT worktree's HEAD).
4381
+ * A session with no checkpoint yet, or a checkpoint with no commit_sha, has nothing to compare
4382
+ * against and is unaffected (scoped strictly to the mismatch case, never a spurious refusal).
4383
+ *
4384
+ * #413 iteration-2 Fix 4 (see checkpointHeadAncestry's own doc comment for the full
4385
+ * `mismatchKind` classification this gate reads): only `mismatchKind === "positive"` (a
4386
+ * POSITIVELY-DETERMINABLE ancestry mismatch — the real wrong-tree harm case) hard refuses here.
4387
+ * `"undeterminable-shallow"` (e.g. a local shallow clone missing the commit_sha object) must
4388
+ * NEVER hard-refuse a legitimate publish — this branch only WARNS loudly and lets the shape +
4389
+ * verify-hold gates above continue to stand guard. A non-git `repoRoot` classifies as
4390
+ * `mismatchKind === "none"` (allow) — iteration-2's Fix 5 hard-refused this case too, but that
4391
+ * regressed the SUPPORTED non-git-repoRoot scratch/checkpoint-signing flow (see
4392
+ * evals/integration/test_checkpoint_signing.sh TEST 2) and was reverted in iteration-3. Wrong-tree
4393
+ * protection for that case relies on the shape-check and verify-hold gates above, which correctly
4394
+ * no-op (allow) when there is no git repo to inspect, same as this gate.
4395
+ *
4396
+ * There are now FOUR fail-closed/fail-soft TIERS in this function, and they must never be
4397
+ * conflated in prose or in a call site's catch handler: (1) fail-SOFT bundle absence /
4398
+ * repo-root resolution (silent no-op / visible warning, unchanged from before #356), (2)
4399
+ * fail-CLOSED bundle shape (#356, `InvalidBundleShapeError`), (3) fail-CLOSED verify-hold (#293,
4400
+ * `NotFreshHolderError`), (4) fail-CLOSED repo-HEAD-vs-checkpoint mismatch (#413 Facet A,
4401
+ * `RepoHeadMismatchError`) — see this tier's own gate below for the undeterminable-shallow
4402
+ * carve-out. Tiers run in this fixed order (shape, then verify-hold, then HEAD-mismatch); a
4403
+ * bundle that fails an earlier tier throws that tier's error specifically, never a later one's.
2682
4404
  */
2683
4405
  export async function publishDelivery(dir, repoRoot) {
2684
4406
  const bundleSrc = path.join(dir, "trust.bundle");
@@ -2688,6 +4410,39 @@ export async function publishDelivery(dir, repoRoot) {
2688
4410
  process.stderr.write(`[publish-delivery] WARNING: no kits/ ancestor found from ${dir}; skipping publish. Refusing to fall back to process.cwd() to avoid clobbering an unrelated repo's delivery/ seal. Pass --repo-root explicitly if this session dir is intentionally outside a repo checkout.\n`);
2689
4411
  return;
2690
4412
  }
4413
+ // #356 AC6: fail-CLOSED on shape-invalidity — TIER 2 (see this function's doc comment above
4414
+ // for the full tier ordering). Throws InvalidBundleShapeError (never a generic Error).
4415
+ const preflight = runReconcilePreflight(dir, repoRoot);
4416
+ if (!preflight.ok) {
4417
+ process.stderr.write(`[publish-delivery] REFUSING to publish — trust.bundle failed the reconcile-preflight shape check (${preflight.issues.length} issue(s)):\n`);
4418
+ for (const issue of preflight.issues) {
4419
+ process.stderr.write(`[publish-delivery] - ${issue}\n`);
4420
+ }
4421
+ throw new InvalidBundleShapeError(preflight.issues);
4422
+ }
4423
+ // #293: fail-CLOSED verify-hold — TIER 3 (see this function's doc comment above). Throws
4424
+ // NotFreshHolderError (never conflated with InvalidBundleShapeError).
4425
+ const holdCheck = runVerifyHold(dir, repoRoot);
4426
+ if (!holdCheck.ok) {
4427
+ process.stderr.write(`[publish-delivery] REFUSING to publish — verify-hold gate: ${holdCheck.reason}\n`);
4428
+ for (const line of holdCheck.guidance)
4429
+ process.stderr.write(`[publish-delivery] - ${line}\n`);
4430
+ throw new NotFreshHolderError(holdCheck);
4431
+ }
4432
+ // #413 Facet A: FOURTH, DISTINCT fail-closed gate (see this function's doc comment above for
4433
+ // the full four-tier ordering, and checkpointHeadAncestry's doc comment for the
4434
+ // Fix 4 mismatchKind classification this reads).
4435
+ const ancestry = checkpointHeadAncestry(dir, repoRoot);
4436
+ if (ancestry.mismatchKind === "positive" && ancestry.commitSha && ancestry.headSha) {
4437
+ process.stderr.write(`[publish-delivery] REFUSING to publish — resolved repoRoot '${repoRoot}' HEAD '${ancestry.headSha}' is not an ancestor-or-equal of the sealed trust.checkpoint.json commit_sha '${ancestry.commitSha}'. This resolved repoRoot is very likely the WRONG checkout for this session (e.g. invoked from a worktree whose artifact dir physically lives under a different primary checkout). Pass --repo-root explicitly, or re-seal the checkpoint against this repoRoot if it really is the intended target.\n`);
4438
+ throw new RepoHeadMismatchError(repoRoot, ancestry.commitSha, ancestry.headSha);
4439
+ }
4440
+ if (ancestry.mismatchKind === "undeterminable-shallow" && ancestry.commitSha && ancestry.headSha) {
4441
+ // #413 iteration-2 Fix 4: NEVER hard-refuse here — a shallow clone (or any other case where
4442
+ // git cannot positively determine ancestry) must not spuriously block a legitimate publish.
4443
+ // The shape + verify-hold gates above already ran and passed; this is warn-and-allow only.
4444
+ process.stderr.write(`[publish-delivery] WARNING: could not determine whether trust.checkpoint.json commit_sha '${ancestry.commitSha}' is an ancestor of repoRoot '${repoRoot}' HEAD '${ancestry.headSha}' (e.g. a shallow clone missing the commit object) — allowing the publish since this is UNDETERMINABLE, not a positively-confirmed mismatch. The shape and verify-hold gates already passed.\n`);
4445
+ }
2691
4446
  const deliveryDir = path.join(repoRoot, "delivery");
2692
4447
  // #379: slug is the session artifact dir's basename — the same human-meaningful id used
2693
4448
  // throughout the session (.kontourai/flow-agents/<slug>/). The per-session dir NAME is only
@@ -2695,7 +4450,8 @@ export async function publishDelivery(dir, repoRoot) {
2695
4450
  const slug = path.basename(path.resolve(dir));
2696
4451
  const sessionDeliveryDir = path.join(deliveryDir, slug);
2697
4452
  fs.mkdirSync(deliveryDir, { recursive: true });
2698
- // Supersede inherited/flat seals BEFORE writing this session's dir (keepSlug = our own).
4453
+ // #413 Facet B: prune only THIS session's own prior seal (never another slug's) before
4454
+ // freshly rewriting delivery/<slug>/ below.
2699
4455
  pruneSupersededSeals(deliveryDir, slug);
2700
4456
  fs.mkdirSync(sessionDeliveryDir, { recursive: true });
2701
4457
  // Required: trust.bundle (the CI anchor)
@@ -2801,12 +4557,13 @@ async function recordLearning(p) {
2801
4557
  die("learning status learned requires every record to include correction.needed");
2802
4558
  writeJson(path.join(dir, "learning.json"), { ...sidecarBase(slug), status, updated_at: timestamp, records });
2803
4559
  writeState(dir, slug, "accepted", "learning", timestamp, opt(p, "summary"));
2804
- // Phase 4c: build bundle from raw inputs; read checks/critiques from trust.bundle (bespoke sidecars no longer written).
4560
+ // Phase 4c: build bundle from raw inputs; read checks/criteria/critiques via the shared
4561
+ // compose-safe readBundleState path (#270 LOW consolidation — this was the literal inline
4562
+ // pattern readBundleState was extracted FROM; using the shared helper directly keeps the two
4563
+ // from silently drifting apart in the future).
2805
4564
  // #268/#344: declared builder.* claims survive the round-trip via their authoritative origin stamp.
2806
- const _learningChecks = checksFromBundle(dir);
2807
- const _learningCriteria = Array.isArray(loadJson(path.join(dir, "acceptance.json")).criteria) ? loadJson(path.join(dir, "acceptance.json")).criteria : [];
2808
- const _learningCritiques = critiquesFromBundle(dir);
2809
- assertBundleWritten(await writeTrustBundle(dir, slug, timestamp, _learningChecks, _learningCriteria, _learningCritiques));
4565
+ const _learningState = readBundleState(dir);
4566
+ assertBundleWritten(await writeTrustBundle(dir, slug, timestamp, _learningState.checks, _learningState.criteria, _learningState.critiques));
2810
4567
  return 0;
2811
4568
  }
2812
4569
  function evidenceClean(dir) {
@@ -2888,7 +4645,16 @@ async function dogfoodPass(p) {
2888
4645
  assertExistingLearningValid(dir);
2889
4646
  const verdict = opt(p, "verdict");
2890
4647
  if (verdict === "pass") {
2891
- const checks = opts(p, "check-json").map((v) => normalizeCheck(parseJson(v, "--check-json")));
4648
+ // #270 follow-up fix (iteration 5, narrowed iteration 6): dogfood-pass's own pre-validation
4649
+ // normalizeCheck call (before delegating the actual write to recordEvidence below) must apply
4650
+ // the same narrowed existing-unstamped-id exemption recordEvidence/recordCheck do, or a
4651
+ // legitimate correction of a mis-recorded, UNSTAMPED gate-claim-* id would die HERE, before
4652
+ // ever reaching recordEvidence's own (already-fixed) guard — while supersession of a STAMPED
4653
+ // (live) gate claim id must still die here too. readBundleState is safe to call even when
4654
+ // trust.bundle does not yet exist (loadJson falls back to {}), exactly as
4655
+ // recordEvidence/recordCheck rely on.
4656
+ const _dogfoodExistingCheckStampById = existingCheckStampMap(readBundleState(dir).checks);
4657
+ const checks = opts(p, "check-json").map((v) => normalizeCheck(parseJson(v, "--check-json"), false, _dogfoodExistingCheckStampById));
2892
4658
  if (checks.some((c) => c.status !== "pass" && c.status !== "skip"))
2893
4659
  die("clean evidence requires all non-skipped checks to pass");
2894
4660
  // Phase 4c: evidence check reads from trust.bundle (sole verification artifact); legacy evidence.json fallback in evidenceClean.
@@ -3904,9 +5670,27 @@ Available claim ids:
3904
5670
  }
3905
5671
  // ─────────────────────────────────────────────────────────────────────────────
3906
5672
  async function main() {
3907
- const p = parseArgs(process.argv.slice(2));
5673
+ const _rawArgv = process.argv.slice(2);
5674
+ // #380: `record-check <dir> -- <command...>` — argv after the FIRST literal `--` token is the
5675
+ // command to execute verbatim (never option-parsed: a command like `npm test -- --watch`
5676
+ // legitimately contains its OWN `--`, so only the record-check dispatcher's own separator, the
5677
+ // first one, is consumed here). parseArgs() cannot represent this (it treats every `--foo`-
5678
+ // shaped token as an option key, including a bare `--`), so the split happens here, before
5679
+ // parseArgs ever sees the command's own argv.
5680
+ let _commandArgv = null;
5681
+ let _argvForParse = _rawArgv;
5682
+ if (_rawArgv[0] === "record-check") {
5683
+ const sepIdx = _rawArgv.indexOf("--");
5684
+ if (sepIdx >= 0) {
5685
+ _argvForParse = _rawArgv.slice(0, sepIdx);
5686
+ _commandArgv = _rawArgv.slice(sepIdx + 1);
5687
+ }
5688
+ }
5689
+ const p = parseArgs(_argvForParse);
3908
5690
  if (!p.command)
3909
5691
  die("workflow-sidecar command is required");
5692
+ if (p.command === "ensure-session")
5693
+ preflightEnsureSession(p);
3910
5694
  // F1 (#166 fix iteration 1): `liveness whoami` is a read-only, lock-free, write-free advisory
3911
5695
  // surface (see the `action === "whoami"` branch inside `liveness()` above) — it must never
3912
5696
  // acquire the workflow-sidecar lock, regardless of whether the artifact root already exists on
@@ -3933,6 +5717,7 @@ async function main() {
3933
5717
  case "init-plan": return initPlan(p);
3934
5718
  case "record-evidence": return recordEvidence(p);
3935
5719
  case "record-gate-claim": return recordGateClaim(p);
5720
+ case "record-check": return recordCheck(p, _commandArgv);
3936
5721
  case "promote": return promote(p);
3937
5722
  case "advance-state": return advanceState(p);
3938
5723
  case "record-critique": return recordCritique(p);
@@ -3948,6 +5733,9 @@ async function main() {
3948
5733
  case "resolve-slug": return resolveSlugCmd(p);
3949
5734
  case "seal-checkpoint": return sealCheckpoint(p);
3950
5735
  case "publish-delivery": return publishDeliveryCmd(p);
5736
+ case "reconcile-preflight": return reconcilePreflightCmd(p);
5737
+ case "verify-hold": return verifyHoldCmd(p);
5738
+ case "takeover-preflight": return takeoverPreflightCmd(p);
3951
5739
  default: die(`unknown command: ${p.command}`);
3952
5740
  }
3953
5741
  });