peaks-loop 4.1.4 → 4.1.6

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 (294) hide show
  1. package/.claude-plugin/marketplace.json +7 -2
  2. package/CHANGELOG.md +148 -0
  3. package/README-en.md +47 -183
  4. package/README.md +24 -188
  5. package/dist/cli/cli-helpers.d.ts +20 -0
  6. package/dist/cli/cli-helpers.js +34 -0
  7. package/dist/cli/commands/_register.js +2 -0
  8. package/dist/cli/commands/best-practice-scan-command.d.ts +11 -6
  9. package/dist/cli/commands/best-practice-scan-command.js +35 -20
  10. package/dist/cli/commands/best-practice-scan-helpers.d.ts +47 -0
  11. package/dist/cli/commands/best-practice-scan-helpers.js +88 -5
  12. package/dist/cli/commands/best-practice-scan-lookup-results.d.ts +13 -0
  13. package/dist/cli/commands/best-practice-scan-lookup-results.js +237 -0
  14. package/dist/cli/commands/code-commands.d.ts +6 -4
  15. package/dist/cli/commands/code-commands.js +6 -4
  16. package/dist/cli/commands/code-gate-command.d.ts +5 -5
  17. package/dist/cli/commands/code-gate-command.js +49 -9
  18. package/dist/cli/commands/code-mode-gate-plan-command.d.ts +1 -1
  19. package/dist/cli/commands/code-mode-gate-plan-command.js +2 -2
  20. package/dist/cli/commands/core/memory-extract-command.js +10 -5
  21. package/dist/cli/commands/dispatch-cli-invocation-check.d.ts +108 -0
  22. package/dist/cli/commands/dispatch-cli-invocation-check.js +87 -0
  23. package/dist/cli/commands/dispatch-cli-invocation-scan.d.ts +66 -0
  24. package/dist/cli/commands/dispatch-cli-invocation-scan.js +162 -0
  25. package/dist/cli/commands/dispatch-command-spec.js +1 -1
  26. package/dist/cli/commands/dispatch-commands.js +12 -5
  27. package/dist/cli/commands/dispatch-isolation-lease.d.ts +1 -1
  28. package/dist/cli/commands/dispatch-isolation-lease.js +6 -53
  29. package/dist/cli/commands/dispatch-preflight.js +46 -0
  30. package/dist/cli/commands/dispatch-prompt-blocks.d.ts +1 -1
  31. package/dist/cli/commands/dispatch-prompt-composition.d.ts +7 -1
  32. package/dist/cli/commands/dispatch-prompt-composition.js +29 -7
  33. package/dist/cli/commands/dispatch-record-write.d.ts +1 -1
  34. package/dist/cli/commands/dispatch-tool-call.d.ts +1 -1
  35. package/dist/cli/commands/doc-commands.js +1 -1
  36. package/dist/cli/commands/feedback-commands-helpers.js +1 -1
  37. package/dist/cli/commands/final-review-prepare-command.js +22 -1
  38. package/dist/cli/commands/gate-commands-enforce.js +3 -3
  39. package/dist/cli/commands/hook-handle.js +41 -20
  40. package/dist/cli/commands/lint-commands.js +3 -1
  41. package/dist/cli/commands/loop-eval-capture-index.js +2 -4
  42. package/dist/cli/commands/openspec-command-shared.js +2 -2
  43. package/dist/cli/commands/perf-audit-commands.js +15 -5
  44. package/dist/cli/commands/project-commands.js +9 -6
  45. package/dist/cli/commands/race-commands.d.ts +15 -0
  46. package/dist/cli/commands/race-commands.js +65 -0
  47. package/dist/cli/commands/race-pilot-gate-record-command.d.ts +3 -0
  48. package/dist/cli/commands/race-pilot-gate-record-command.js +81 -0
  49. package/dist/cli/commands/request-command-options.d.ts +8 -0
  50. package/dist/cli/commands/request-commands.js +2 -0
  51. package/dist/cli/commands/request-init-command.js +67 -12
  52. package/dist/cli/commands/{vm-status-command.d.ts → request-retag-command.d.ts} +1 -1
  53. package/dist/cli/commands/request-retag-command.js +50 -0
  54. package/dist/cli/commands/request-show-command.d.ts +8 -0
  55. package/dist/cli/commands/request-show-command.js +14 -1
  56. package/dist/cli/commands/request-transition-command.js +12 -4
  57. package/dist/cli/commands/request-transition-failures.d.ts +14 -0
  58. package/dist/cli/commands/request-transition-failures.js +76 -7
  59. package/dist/cli/commands/request-transition-preflight.js +1 -1
  60. package/dist/cli/commands/scan-scope-commands.js +2 -2
  61. package/dist/cli/commands/security-audit-commands.js +26 -6
  62. package/dist/cli/commands/slice-decompose-artifacts.js +2 -1
  63. package/dist/cli/commands/verdict-aggregate-command.js +2 -1
  64. package/dist/cli/commands/workflow-gate-commands.js +4 -4
  65. package/dist/cli/commands/worktree-lease-gc-command.js +1 -1
  66. package/dist/cli/program.js +0 -2
  67. package/dist/services/artifacts/artifact-contract-block.d.ts +53 -0
  68. package/dist/services/artifacts/artifact-contract-block.js +231 -0
  69. package/dist/services/artifacts/artifact-prerequisites.d.ts +27 -19
  70. package/dist/services/artifacts/artifact-prerequisites.js +65 -135
  71. package/dist/services/artifacts/artifact-templates.d.ts +1 -1
  72. package/dist/services/artifacts/artifact-templates.js +17 -10
  73. package/dist/services/artifacts/prerequisite-checks.d.ts +87 -0
  74. package/dist/services/artifacts/prerequisite-checks.js +198 -0
  75. package/dist/services/artifacts/prerequisite-transition-event.d.ts +20 -0
  76. package/dist/services/artifacts/prerequisite-transition-event.js +27 -0
  77. package/dist/services/artifacts/rd-transition-gates.d.ts +33 -0
  78. package/dist/services/artifacts/rd-transition-gates.js +71 -0
  79. package/dist/services/artifacts/request-artifact-metadata.d.ts +31 -0
  80. package/dist/services/artifacts/request-artifact-metadata.js +44 -0
  81. package/dist/services/artifacts/request-artifact-service.d.ts +5 -0
  82. package/dist/services/artifacts/request-artifact-service.js +43 -69
  83. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +21 -1
  84. package/dist/services/artifacts/request-artifact-state-helpers.js +34 -8
  85. package/dist/services/artifacts/request-retag-service.d.ts +68 -0
  86. package/dist/services/artifacts/request-retag-service.js +125 -0
  87. package/dist/services/artifacts/request-state-order.d.ts +38 -0
  88. package/dist/services/artifacts/request-state-order.js +99 -0
  89. package/dist/services/artifacts/request-type-demand.d.ts +44 -0
  90. package/dist/services/artifacts/request-type-demand.js +71 -0
  91. package/dist/services/audit/audit-goal-service.d.ts +7 -0
  92. package/dist/services/audit/enforcers/active-skill-resolver.d.ts +18 -0
  93. package/dist/services/audit/enforcers/active-skill-resolver.js +48 -1
  94. package/dist/services/audit/enforcers/code-ban.d.ts +11 -2
  95. package/dist/services/audit/enforcers/code-ban.js +21 -1
  96. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.d.ts +17 -0
  97. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.js +24 -7
  98. package/dist/services/audit-independent/handoff-missing-refusal.d.ts +26 -0
  99. package/dist/services/audit-independent/handoff-missing-refusal.js +109 -0
  100. package/dist/services/audit-independent/handoff-readers.d.ts +37 -0
  101. package/dist/services/audit-independent/handoff-readers.js +81 -0
  102. package/dist/services/audit-independent/index.d.ts +6 -1
  103. package/dist/services/audit-independent/index.js +6 -1
  104. package/dist/services/audit-independent/judged-declaration-build.d.ts +48 -0
  105. package/dist/services/audit-independent/judged-declaration-build.js +73 -0
  106. package/dist/services/audit-independent/judged-declaration-check.d.ts +80 -0
  107. package/dist/services/audit-independent/judged-declaration-check.js +216 -0
  108. package/dist/services/audit-independent/judged-declaration.d.ts +94 -0
  109. package/dist/services/audit-independent/judged-declaration.js +218 -0
  110. package/dist/services/audit-independent/perf-audit-service.js +12 -14
  111. package/dist/services/audit-independent/security-audit-artifact.d.ts +28 -0
  112. package/dist/services/audit-independent/security-audit-artifact.js +90 -0
  113. package/dist/services/audit-independent/security-audit-service.d.ts +6 -53
  114. package/dist/services/audit-independent/security-audit-service.js +34 -178
  115. package/dist/services/capability-guard-runner/contracts/J05.js +60 -14
  116. package/dist/services/codegraph/codegraph-index-integrity.js +2 -0
  117. package/dist/services/context/build-dispatch-system-prompt.d.ts +8 -12
  118. package/dist/services/context/build-dispatch-system-prompt.js +18 -18
  119. package/dist/services/context/collector.js +5 -1
  120. package/dist/services/context/post-compact-reinjection.js +1 -1
  121. package/dist/services/dispatch/active-dispatch-index.d.ts +36 -0
  122. package/dist/services/dispatch/active-dispatch-index.js +118 -0
  123. package/dist/services/dispatch/batch-counter.js +1 -2
  124. package/dist/services/dispatch/dispatch-record-writer.d.ts +29 -16
  125. package/dist/services/dispatch/dispatch-record-writer.js +58 -100
  126. package/dist/services/dispatch/dispatch-sub-agent.js +1 -1
  127. package/dist/services/dispatch/karpathy-block.d.ts +55 -0
  128. package/dist/services/dispatch/karpathy-block.js +101 -0
  129. package/dist/services/dispatch/ledger-reaper.d.ts +80 -0
  130. package/dist/services/dispatch/ledger-reaper.js +131 -0
  131. package/dist/services/dispatch/test-tool-detection.d.ts +17 -1
  132. package/dist/services/dispatch/test-tool-detection.js +12 -1
  133. package/dist/services/evidence/evidence-generator.js +23 -12
  134. package/dist/services/feedback/feedback-promotion-service.d.ts +8 -11
  135. package/dist/services/feedback/feedback-promotion-service.js +30 -35
  136. package/dist/services/feedback/promotion-artifact-json-evidence.d.ts +18 -0
  137. package/dist/services/feedback/promotion-artifact-missing.d.ts +22 -0
  138. package/dist/services/feedback/promotion-artifact-missing.js +63 -0
  139. package/dist/services/final-review/final-review-contract.d.ts +95 -4
  140. package/dist/services/final-review/final-review-contract.js +64 -0
  141. package/dist/services/final-review/final-review-delivery.d.ts +13 -0
  142. package/dist/services/final-review/final-review-delivery.js +26 -12
  143. package/dist/services/final-review/final-review-evidence-collect.js +8 -53
  144. package/dist/services/final-review/final-review-evidence-records.d.ts +21 -0
  145. package/dist/services/final-review/final-review-evidence-records.js +67 -0
  146. package/dist/services/final-review/final-review-evidence-sources.d.ts +22 -0
  147. package/dist/services/final-review/final-review-evidence-sources.js +28 -4
  148. package/dist/services/final-review/final-review-prompt.js +19 -6
  149. package/dist/services/final-review/final-review-runner.js +5 -0
  150. package/dist/services/final-review/final-review-service.d.ts +2 -2
  151. package/dist/services/final-review/index.d.ts +1 -1
  152. package/dist/services/final-review/pre-post-diff.d.ts +2 -75
  153. package/dist/services/final-review/pre-post-diff.js +60 -59
  154. package/dist/services/hooks/pre-tool-code-gate.d.ts +7 -1
  155. package/dist/services/hooks/pre-tool-code-gate.js +21 -2
  156. package/dist/services/hooks/worktree-authorization-gate.js +6 -31
  157. package/dist/services/hooks/worktree-refusal-messages.d.ts +74 -0
  158. package/dist/services/hooks/worktree-refusal-messages.js +102 -0
  159. package/dist/services/lint/eslint-runner-support.d.ts +1 -1
  160. package/dist/services/lint/eslint-runner-support.js +2 -1
  161. package/dist/services/lint/eslint-runner-types.d.ts +8 -0
  162. package/dist/services/lint/eslint-runner.js +17 -4
  163. package/dist/services/llm/anthropic-runner.js +24 -7
  164. package/dist/services/loop/loop-observability.d.ts +39 -0
  165. package/dist/services/loop/loop-observability.js +55 -0
  166. package/dist/services/loop/monotonic-guard.js +6 -9
  167. package/dist/services/loop/monotonic-runner.js +8 -7
  168. package/dist/services/loop/run-driver.js +18 -22
  169. package/dist/services/memory/project-memory-service/index/kind-dispatch.js +14 -1
  170. package/dist/services/memory/project-memory-service/index/project-memory-plan-exec.js +13 -2
  171. package/dist/services/memory/project-memory-service/index.d.ts +2 -2
  172. package/dist/services/memory/project-memory-service/index.js +1 -1
  173. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.d.ts +36 -0
  174. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.js +48 -2
  175. package/dist/services/memory/project-memory-service/parsers/markdown-pure.d.ts +23 -1
  176. package/dist/services/memory/project-memory-service/parsers/markdown-pure.js +37 -0
  177. package/dist/services/memory/project-memory-service/types.d.ts +32 -0
  178. package/dist/services/observability/observability-service.d.ts +7 -0
  179. package/dist/services/observability/observability-service.js +2 -1
  180. package/dist/services/openspec/coverage-evidence-reader.d.ts +9 -9
  181. package/dist/services/openspec/coverage-evidence-reader.js +8 -8
  182. package/dist/services/openspec/openspec-archive-service.d.ts +1 -1
  183. package/dist/services/openspec/openspec-archive-service.js +6 -6
  184. package/dist/services/prd/gate-evidence-derivation.d.ts +4 -3
  185. package/dist/services/prd/gate-evidence-derivation.js +4 -3
  186. package/dist/services/qa/bdd-test-style-verifier.js +22 -8
  187. package/dist/services/race/gate2-evaluator.d.ts +58 -0
  188. package/dist/services/race/gate2-evaluator.js +111 -0
  189. package/dist/services/race/gate2-policy.d.ts +17 -0
  190. package/dist/services/race/gate2-policy.js +31 -0
  191. package/dist/services/race/lane-phase.d.ts +19 -0
  192. package/dist/services/race/lane-phase.js +113 -0
  193. package/dist/services/race/pilot-gate-store.d.ts +67 -0
  194. package/dist/services/race/pilot-gate-store.js +227 -0
  195. package/dist/services/scan/file-size-baseline.d.ts +33 -0
  196. package/dist/services/scan/file-size-baseline.js +173 -0
  197. package/dist/services/scan/file-size-scan.d.ts +35 -3
  198. package/dist/services/scan/file-size-scan.js +63 -42
  199. package/dist/services/scan/type-corroboration.d.ts +32 -0
  200. package/dist/services/scan/type-corroboration.js +51 -0
  201. package/dist/services/scan/type-sanity-service.d.ts +14 -0
  202. package/dist/services/scan/type-sanity-service.js +23 -22
  203. package/dist/services/security/safe-settings-path.d.ts +5 -0
  204. package/dist/services/security/safe-settings-path.js +64 -8
  205. package/dist/services/skill/resume-detector.js +11 -11
  206. package/dist/services/skills/hooks-codegate-superpowers.d.ts +5 -6
  207. package/dist/services/skills/hooks-codegate-superpowers.js +7 -8
  208. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  209. package/dist/services/skills/hooks-settings-service.js +1 -1
  210. package/dist/services/skills/presence-lease-order.d.ts +13 -0
  211. package/dist/services/skills/presence-lease-order.js +24 -0
  212. package/dist/services/skills/skill-conformance-service.js +1 -0
  213. package/dist/services/skills/skill-statusline-service.js +4 -7
  214. package/dist/services/slice/slice-check-service.js +8 -8
  215. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +24 -8
  216. package/dist/services/workflow/pipeline-verify-gate-support.js +34 -39
  217. package/dist/services/workflow/pipeline-verify-qa-phase.d.ts +102 -0
  218. package/dist/services/workflow/pipeline-verify-qa-phase.js +176 -0
  219. package/dist/services/workflow/pipeline-verify-service.js +27 -28
  220. package/dist/services/workflow/request-type-resolution.d.ts +99 -0
  221. package/dist/services/workflow/request-type-resolution.js +130 -0
  222. package/dist/services/workflow/workflow-skip-service.d.ts +1 -20
  223. package/dist/services/workflow/workflow-skip-service.js +22 -25
  224. package/dist/services/workflow/workflow-state-store.d.ts +9 -0
  225. package/dist/services/workflow/workflow-state-store.js +26 -1
  226. package/dist/services/workspace/claude-settings-retirements.d.ts +54 -0
  227. package/dist/services/workspace/claude-settings-retirements.js +112 -0
  228. package/dist/services/workspace/claude-settings-template-merge.d.ts +35 -15
  229. package/dist/services/workspace/claude-settings-template-merge.js +33 -53
  230. package/dist/services/workspace/claude-settings-template.d.ts +62 -12
  231. package/dist/services/workspace/claude-settings-template.js +58 -58
  232. package/dist/services/workspace/migrate-1-4-1-service.js +3 -0
  233. package/dist/services/workspace/reconcile-service.js +0 -1
  234. package/dist/shared/incrementing-number.d.ts +33 -2
  235. package/dist/shared/incrementing-number.js +72 -3
  236. package/package.json +5 -7
  237. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  238. package/skills/bee/peaks-prd/SKILL.md +4 -3
  239. package/skills/bee/peaks-qa/SKILL.md +1 -1
  240. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  241. package/skills/bee/peaks-qa/references/qa-transition-gates.md +1 -1
  242. package/skills/bee/peaks-rd/SKILL.md +2 -2
  243. package/skills/bee/peaks-rd/references/rd-fanout-contracts.md +1 -1
  244. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +8 -4
  245. package/skills/bee/peaks-rd/references/rd-transition-gates.md +3 -3
  246. package/skills/bee/peaks-rd/references/v2-12-fanout-collapse.md +2 -2
  247. package/skills/bee/peaks-rd/references/writing-handoff-frontmatter.md +1 -1
  248. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  249. package/skills/bee/peaks-sc/SKILL.md +1 -1
  250. package/skills/bee/peaks-security-audit/SKILL.md +10 -2
  251. package/skills/bee/peaks-txt/SKILL.md +4 -3
  252. package/skills/bee/peaks-ui/SKILL.md +3 -3
  253. package/skills/peaks-audit/SKILL.md +29 -1
  254. package/skills/peaks-code/SKILL.md +37 -17
  255. package/skills/peaks-code/references/fast-lane-norm.md +42 -0
  256. package/skills/peaks-code/references/fast-mode.md +3 -2
  257. package/skills/peaks-code/references/local-artifact-workspace.md +3 -3
  258. package/skills/peaks-code/references/micro-cycle.md +3 -3
  259. package/skills/peaks-code/references/resume-detection.md +1 -1
  260. package/skills/peaks-code/references/runbook.md +12 -6
  261. package/skills/peaks-code/references/step-11-memory-sediment.md +4 -0
  262. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  263. package/skills/peaks-code/references/swarm-dispatch-contract.md +40 -16
  264. package/skills/peaks-code/references/workflow-gates-and-types.md +6 -6
  265. package/skills/peaks-code/references/worktree-governance.md +4 -4
  266. package/skills/peaks-content/SKILL.md +1 -1
  267. package/skills/peaks-doctor/SKILL.md +1 -1
  268. package/skills/peaks-final-review/SKILL.md +31 -11
  269. package/skills/peaks-ide/SKILL.md +1 -1
  270. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  271. package/skills/peaks-race-code/SKILL.md +185 -0
  272. package/skills/peaks-resume/SKILL.md +1 -1
  273. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  274. package/skills/peaks-solo/SKILL.md +1 -1
  275. package/skills/peaks-sop/SKILL.md +1 -1
  276. package/skills/peaks-status/SKILL.md +1 -1
  277. package/skills/peaks-test/SKILL.md +7 -4
  278. package/dist/cli/commands/vm-command-shared.d.ts +0 -23
  279. package/dist/cli/commands/vm-command-shared.js +0 -23
  280. package/dist/cli/commands/vm-commands.d.ts +0 -3
  281. package/dist/cli/commands/vm-commands.js +0 -45
  282. package/dist/cli/commands/vm-hypervisor-probe.d.ts +0 -27
  283. package/dist/cli/commands/vm-hypervisor-probe.js +0 -78
  284. package/dist/cli/commands/vm-hypervisor-runtime.d.ts +0 -15
  285. package/dist/cli/commands/vm-hypervisor-runtime.js +0 -64
  286. package/dist/cli/commands/vm-release-command.d.ts +0 -5
  287. package/dist/cli/commands/vm-release-command.js +0 -101
  288. package/dist/cli/commands/vm-spawn-command.d.ts +0 -5
  289. package/dist/cli/commands/vm-spawn-command.js +0 -177
  290. package/dist/cli/commands/vm-status-command.js +0 -50
  291. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.d.ts +0 -23
  292. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.js +0 -64
  293. package/dist/services/vm/vm-lease.d.ts +0 -40
  294. package/dist/services/vm/vm-lease.js +0 -160
@@ -0,0 +1,99 @@
1
+ // src/services/artifacts/request-state-order.ts
2
+ //
3
+ // The request state machine's ORDER rule, in one place (S-14, session
4
+ // `2026-10-12-session-74bd69`).
5
+ //
6
+ // `ALLOWED_STATES_PER_ROLE` is a SEQUENCE, but `transitionRequestArtifact`
7
+ // tested only membership. Measured: with `rd → implemented` and
8
+ // `rd → qa-handoff` both refused, `rd → handed-off` still passed — a slice
9
+ // could report itself delivered past every intermediate gate. A FORWARD jump is
10
+ // refused here.
11
+ //
12
+ // Deliberately allowed: any move to or from `blocked` (a side state, not a
13
+ // step); the current state; and any move BACKWARD — the QA return-to-rd repair
14
+ // re-enters `rd: spec-locked` from `qa-handoff` (micro-cycle.md §"How Code
15
+ // routes QA findings back to RD"), so this is a skip test, not a rising-rank
16
+ // test. `--allow-incomplete` bypasses it, like every other transition gate —
17
+ // the flag opens FOUR gates now (order, prerequisites, lint, file size), so the
18
+ // refusal's own remedy line reads narrower than the flag actually is.
19
+ //
20
+ // FAIL-CLOSED. An unreadable current state is REFUSED, not allowed: allowing it
21
+ // would make a deleted `- state:` line an off-switch for this whole gate.
22
+ //
23
+ // Split out of `request-artifact-state-helpers.ts` (254 raw lines at the split)
24
+ // so that file stays under its 300-line cap while this rule has room to be
25
+ // stated in full.
26
+ import { ALLOWED_STATES_PER_ROLE } from './request-artifact-state-helpers.js';
27
+ /** The role's states in declared order, minus `blocked` (which has no rank). */
28
+ function orderedStatesForRole(role) {
29
+ return ALLOWED_STATES_PER_ROLE[role].filter((state) => state !== 'blocked');
30
+ }
31
+ /**
32
+ * `null` when the move is allowed, or the breach when it is not.
33
+ *
34
+ * FAIL-CLOSED on an unreadable current state. A carrier with no `- state:` line
35
+ * reads as the literal `'unknown'` (the `readArtifactState(...) ?? 'unknown'`
36
+ * fallback in the transition service), and this gate runs before every other
37
+ * one. Reading "I could not read it" as "no jump" would therefore hand the gate
38
+ * an off-switch that is one deleted line — re-opening the `rd → handed-off` jump
39
+ * this module exists to stop — so an unreadable state is refused, not allowed.
40
+ */
41
+ export function stateOrderViolation(role, from, to) {
42
+ if (from === 'blocked' || to === 'blocked')
43
+ return null;
44
+ const order = orderedStatesForRole(role);
45
+ const toIndex = order.indexOf(to);
46
+ if (toIndex < 0)
47
+ return null;
48
+ const fromIndex = order.indexOf(from);
49
+ if (fromIndex < 0)
50
+ return { kind: 'unreadable', skipped: [], next: null };
51
+ if (toIndex <= fromIndex + 1)
52
+ return null;
53
+ return {
54
+ kind: 'jump',
55
+ skipped: order.slice(fromIndex + 1, toIndex),
56
+ next: order[fromIndex + 1] ?? null
57
+ };
58
+ }
59
+ /** The breach kinds get their own codes: a refusal that cannot be named is a
60
+ * refusal a consumer cannot act on, and "jumped" is not "could not be read". */
61
+ export const STATE_ORDER_JUMP_CODE = 'STATE_ORDER_JUMP';
62
+ export const STATE_ORDER_UNREADABLE_CODE = 'STATE_ORDER_UNREADABLE';
63
+ export class StateOrderViolationError extends Error {
64
+ code;
65
+ role;
66
+ from;
67
+ to;
68
+ skipped;
69
+ kind;
70
+ constructor(role, from, to, breach) {
71
+ super(`Cannot transition ${role} from '${from}' to '${to}': ` +
72
+ (breach.kind === 'unreadable'
73
+ ? "the artifact's current state could not be read (no '- state:' line, " +
74
+ "or a state this role's machine does not define). Failing closed — a move " +
75
+ 'that cannot be shown to be legal is refused, not allowed. '
76
+ : `that skips ${breach.skipped.map((state) => `'${state}'`).join(', ')}. ` +
77
+ (breach.next === null
78
+ ? ''
79
+ : `Move one state at a time — the next legal state is '${breach.next}'. `)) +
80
+ 'Walk the states in order, or bypass with --allow-incomplete --reason "<justification>".');
81
+ this.name = 'StateOrderViolationError';
82
+ this.code = breach.kind === 'unreadable' ? STATE_ORDER_UNREADABLE_CODE : STATE_ORDER_JUMP_CODE;
83
+ this.role = role;
84
+ this.from = from;
85
+ this.to = to;
86
+ this.kind = breach.kind;
87
+ this.skipped = breach.skipped;
88
+ }
89
+ }
90
+ /** Throws when `to` skips an intermediate state or the current state is
91
+ * unreadable. `bypass` is the caller's `--allow-incomplete` escape hatch. */
92
+ export function assertLegalStateStep(role, from, to, bypass) {
93
+ if (bypass)
94
+ return;
95
+ const breach = stateOrderViolation(role, from, to);
96
+ if (breach !== null) {
97
+ throw new StateOrderViolationError(role, from, to, breach);
98
+ }
99
+ }
@@ -0,0 +1,44 @@
1
+ import { type RequestType } from './artifact-prerequisites.js';
2
+ import { type RequestArtifactState } from './request-artifact-state-helpers.js';
3
+ import type { RequestArtifactRole } from './artifact-templates.js';
4
+ export type DemandRow = {
5
+ role: RequestArtifactRole;
6
+ state: RequestArtifactState;
7
+ /** The table's own `relativePath` values, `<rid>` still unsubstituted. */
8
+ paths: ReadonlyArray<string>;
9
+ };
10
+ /**
11
+ * Every row of `requestType`'s table that demands at least one artifact, in role
12
+ * then state declaration order. This is the answer to "which prerequisite table
13
+ * is being applied" that does not require opening `artifact-prerequisites.ts`.
14
+ */
15
+ export declare function demandRows(requestType: RequestType): DemandRow[];
16
+ export type DemandDelta = {
17
+ /** Demanded by `to` and not by `from`. */
18
+ added: string[];
19
+ /** Demanded by `from` and not by `to`. */
20
+ removed: string[];
21
+ };
22
+ /** The artifacts a type change starts demanding, and stops demanding. */
23
+ export declare function demandDelta(from: RequestType, to: RequestType): DemandDelta;
24
+ /**
25
+ * The artifacts `requestType` demands that are not on disk right now.
26
+ *
27
+ * Deliberately NOT restricted to the paths a retag just added. A request that
28
+ * recorded no type and is retagged to the effective type it already had — the
29
+ * commonest retag there is — changes nothing in the demand set, so a delta-only
30
+ * answer would be empty on exactly the input this check exists for.
31
+ *
32
+ * Answered with `checkPrerequisites` — the same resolver the transition gate
33
+ * runs — rather than a second path probe, so a retag cannot report a file
34
+ * present that the next transition would refuse. The rows also carry a
35
+ * declaration check against the PRD capsule; the result is filtered to the
36
+ * table's own paths, because that failure is not the type's. `emitEvents: false`
37
+ * because nothing transitions here.
38
+ */
39
+ export declare function unsatisfiedDemand(options: {
40
+ projectRoot: string;
41
+ sessionId: string;
42
+ requestId: string;
43
+ requestType: RequestType;
44
+ }): Promise<string[]>;
@@ -0,0 +1,71 @@
1
+ import { checkPrerequisites, getPrerequisitesFor } from './artifact-prerequisites.js';
2
+ import { ALLOWED_STATES_PER_ROLE } from './request-artifact-state-helpers.js';
3
+ const ROLES = Object.keys(ALLOWED_STATES_PER_ROLE);
4
+ /**
5
+ * Every row of `requestType`'s table that demands at least one artifact, in role
6
+ * then state declaration order. This is the answer to "which prerequisite table
7
+ * is being applied" that does not require opening `artifact-prerequisites.ts`.
8
+ */
9
+ export function demandRows(requestType) {
10
+ const rows = [];
11
+ for (const role of ROLES) {
12
+ for (const state of ALLOWED_STATES_PER_ROLE[role]) {
13
+ const paths = getPrerequisitesFor(role, state, requestType).map((entry) => entry.relativePath);
14
+ if (paths.length > 0)
15
+ rows.push({ role, state, paths });
16
+ }
17
+ }
18
+ return rows;
19
+ }
20
+ function demandPaths(requestType) {
21
+ const paths = new Set();
22
+ for (const row of demandRows(requestType)) {
23
+ for (const path of row.paths)
24
+ paths.add(path);
25
+ }
26
+ return paths;
27
+ }
28
+ /** The artifacts a type change starts demanding, and stops demanding. */
29
+ export function demandDelta(from, to) {
30
+ const before = demandPaths(from);
31
+ const after = demandPaths(to);
32
+ return {
33
+ added: [...after].filter((path) => !before.has(path)),
34
+ removed: [...before].filter((path) => !after.has(path))
35
+ };
36
+ }
37
+ /**
38
+ * The artifacts `requestType` demands that are not on disk right now.
39
+ *
40
+ * Deliberately NOT restricted to the paths a retag just added. A request that
41
+ * recorded no type and is retagged to the effective type it already had — the
42
+ * commonest retag there is — changes nothing in the demand set, so a delta-only
43
+ * answer would be empty on exactly the input this check exists for.
44
+ *
45
+ * Answered with `checkPrerequisites` — the same resolver the transition gate
46
+ * runs — rather than a second path probe, so a retag cannot report a file
47
+ * present that the next transition would refuse. The rows also carry a
48
+ * declaration check against the PRD capsule; the result is filtered to the
49
+ * table's own paths, because that failure is not the type's. `emitEvents: false`
50
+ * because nothing transitions here.
51
+ */
52
+ export async function unsatisfiedDemand(options) {
53
+ const wanted = new Set([...demandPaths(options.requestType)].map((path) => path.replace('<rid>', options.requestId)));
54
+ const missing = new Set();
55
+ for (const row of demandRows(options.requestType)) {
56
+ const result = await checkPrerequisites({
57
+ projectRoot: options.projectRoot,
58
+ sessionId: options.sessionId,
59
+ role: row.role,
60
+ newState: row.state,
61
+ requestId: options.requestId,
62
+ requestType: options.requestType,
63
+ emitEvents: false
64
+ });
65
+ for (const entry of result.missing) {
66
+ if (wanted.has(entry.path))
67
+ missing.add(entry.path);
68
+ }
69
+ }
70
+ return [...missing];
71
+ }
@@ -22,9 +22,16 @@ export interface LlmRunner {
22
22
  maxTokens: number;
23
23
  }): Promise<{
24
24
  output: string;
25
+ /**
26
+ * `input` / `output` are the counts an observability reader sums; `source`
27
+ * says whether the provider reported them or the runner had to estimate
28
+ * (optional so a runner that always has provider numbers — or a test fake —
29
+ * need not state it).
30
+ */
25
31
  tokens: {
26
32
  input: number;
27
33
  output: number;
34
+ source?: 'provider' | 'estimated';
28
35
  };
29
36
  }>;
30
37
  }
@@ -54,3 +54,21 @@ export declare function resolveActiveSkillForCaller(projectRoot: string, opts?:
54
54
  legacyPresence?: boolean;
55
55
  callerId?: string | null;
56
56
  }): ActiveSkillResolution;
57
+ /**
58
+ * Whether any in-flight lease in this session carries a `peaks-*` skill.
59
+ *
60
+ * Independent of `resolveActiveSkillForCaller` on purpose: that function is
61
+ * the one under suspicion when the identity cannot be resolved, so asking it
62
+ * whether peaks is present would be circular. Fails open — a bug in peaks
63
+ * must not brick the harness.
64
+ */
65
+ export declare function hasPeaksLeaseInSession(projectRoot: string): boolean;
66
+ /**
67
+ * Whether this caller owns at least one in-flight lease in the session.
68
+ *
69
+ * `resolveActiveSkillForCaller` cannot answer this: it returns
70
+ * `{ skill: null, source: 'none' }` both when a caller has no lease and when
71
+ * the id handed over is not the lease's key. Those two need different
72
+ * decisions, so the call site asks directly.
73
+ */
74
+ export declare function hasLeaseForCaller(projectRoot: string, callerId: string): boolean;
@@ -28,6 +28,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs';
28
28
  import { join } from 'node:path';
29
29
  import { getSessionIdCanonical } from '../../session/session-manager.js';
30
30
  import { getSessionDir } from '../../session/getSessionDir.js';
31
+ import { comparePresenceLeases } from '../../skills/presence-lease-order.js';
31
32
  import { readPresenceLease, listPresenceLeases } from '../../skills/presence-lease-service.js';
32
33
  import { getCurrentSessionId, normalizeSkillPresenceMode } from '../../skills/skill-presence-service.js';
33
34
  const ACTIVE_SKILL_PREFIX = 'active-skill-';
@@ -87,7 +88,13 @@ export function resolveActiveSkillForCaller(projectRoot, opts) {
87
88
  catch {
88
89
  canonicalLeases = [];
89
90
  }
90
- for (const lease of canonicalLeases) {
91
+ // Freshest first, through the same comparator the statusline reader uses.
92
+ // The two readers disagreed: that one sorted by heartbeat, this one took
93
+ // `readdirSync` order, so "who is driving" had two answers. Sorted here rather
94
+ // than in the shared `listPresenceLeases`, whose output order every consumer
95
+ // sees.
96
+ const orderedLeases = [...canonicalLeases].sort(comparePresenceLeases);
97
+ for (const lease of orderedLeases) {
91
98
  if (lease.status !== 'preparing' && lease.status !== 'running')
92
99
  continue;
93
100
  if (typeof lease.skill !== 'string' || lease.skill.length === 0)
@@ -162,3 +169,43 @@ export function resolveActiveSkillForCaller(projectRoot, opts) {
162
169
  void getCurrentSessionId;
163
170
  return { skill: null, callerId: null, sessionId, mode: null, source: 'none' };
164
171
  }
172
+ /**
173
+ * Whether any in-flight lease in this session carries a `peaks-*` skill.
174
+ *
175
+ * Independent of `resolveActiveSkillForCaller` on purpose: that function is
176
+ * the one under suspicion when the identity cannot be resolved, so asking it
177
+ * whether peaks is present would be circular. Fails open — a bug in peaks
178
+ * must not brick the harness.
179
+ */
180
+ export function hasPeaksLeaseInSession(projectRoot) {
181
+ try {
182
+ const sessionId = getSessionIdCanonical(projectRoot);
183
+ if (sessionId === null)
184
+ return false;
185
+ return listPresenceLeases(projectRoot, sessionId).some((lease) => (lease.status === 'preparing' || lease.status === 'running') &&
186
+ typeof lease.skill === 'string' &&
187
+ lease.skill.startsWith('peaks-'));
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ }
193
+ /**
194
+ * Whether this caller owns at least one in-flight lease in the session.
195
+ *
196
+ * `resolveActiveSkillForCaller` cannot answer this: it returns
197
+ * `{ skill: null, source: 'none' }` both when a caller has no lease and when
198
+ * the id handed over is not the lease's key. Those two need different
199
+ * decisions, so the call site asks directly.
200
+ */
201
+ export function hasLeaseForCaller(projectRoot, callerId) {
202
+ try {
203
+ const sessionId = getSessionIdCanonical(projectRoot);
204
+ if (sessionId === null)
205
+ return false;
206
+ return listPresenceLeases(projectRoot, sessionId).some((lease) => (lease.status === 'preparing' || lease.status === 'running') && lease.callerId === callerId);
207
+ }
208
+ catch {
209
+ return false;
210
+ }
211
+ }
@@ -12,12 +12,21 @@
12
12
  * never bricked by a peaks bug.
13
13
  */
14
14
  export interface CodeBanInput {
15
- readonly skill: string;
15
+ /** The resolved driving skill, or `null` when no skill could be resolved. */
16
+ readonly skill: string | null;
16
17
  readonly command: string;
18
+ /** Whether a `peaks-*` lease exists in this peaks session. */
19
+ readonly peaksLeasePresent: boolean;
20
+ /**
21
+ * Whether the caller's identity was resolved. When `true`, `skill === null`
22
+ * means "this caller resolved and has no peaks skill" — which is an allow.
23
+ * When `false`, we could not tell who is driving at all.
24
+ */
25
+ readonly identityResolved: boolean;
17
26
  }
18
27
  export interface CodeBanResult {
19
28
  readonly denied: boolean;
20
29
  readonly reason: string;
21
30
  }
22
- export declare function isCodeCommit(skill: string, command: string): boolean;
31
+ export declare function isCodeCommit(skill: string | null, command: string): boolean;
23
32
  export declare function evaluateCodeBan(input: CodeBanInput): CodeBanResult;
@@ -14,8 +14,22 @@
14
14
  const COMMIT_APPLY_PATTERN = /^\s*git\s+(commit|apply)\b/;
15
15
  const DENY_REASON = 'Code Commit Ban Red Line: peaks-* skills must go through peaks-code / peaks-rd. ' +
16
16
  'Use `peaks request transition` instead of `git commit` / `git apply` directly.';
17
+ /**
18
+ * Narrower than plain fail-closed on purpose: it fires only when a peaks skill
19
+ * is actually present in the session. `resolveActiveSkillForCaller` returns
20
+ * `null` for any unbound session, and failing closed on that would block
21
+ * `git commit` for every ordinary session in any repo with the gate installed.
22
+ *
23
+ * This branch exists because the ban used to be skipped wholesale when the
24
+ * driver did not resolve — the caller guarded it with `if (skill !== null)`, so
25
+ * a resolution failure meant no ban at all.
26
+ */
27
+ const UNRESOLVED_IDENTITY_REASON = 'Code Commit Ban Red Line: a peaks skill is registered in this session, but the ' +
28
+ 'caller could not be identified, so this commit cannot be shown to come from a ' +
29
+ 'non-peaks session. Re-run from the bound session, or use ' +
30
+ '`peaks request transition` instead of `git commit` / `git apply`.';
17
31
  export function isCodeCommit(skill, command) {
18
- if (!skill.startsWith('peaks-'))
32
+ if (skill === null || !skill.startsWith('peaks-'))
19
33
  return false;
20
34
  return COMMIT_APPLY_PATTERN.test(command);
21
35
  }
@@ -23,5 +37,11 @@ export function evaluateCodeBan(input) {
23
37
  if (isCodeCommit(input.skill, input.command)) {
24
38
  return { denied: true, reason: DENY_REASON };
25
39
  }
40
+ if (input.skill === null &&
41
+ !input.identityResolved &&
42
+ input.peaksLeasePresent &&
43
+ COMMIT_APPLY_PATTERN.test(input.command)) {
44
+ return { denied: true, reason: UNRESOLVED_IDENTITY_REASON };
45
+ }
26
46
  return { denied: false, reason: '' };
27
47
  }
@@ -29,6 +29,23 @@ export declare const PEAKS_CODE_RUNTIME_CONTRACT: RedLineCatalogEntry;
29
29
  * can spread this list into RED_LINE_CATALOG and add their own without
30
30
  * touching this file.
31
31
  */
32
+ /**
33
+ * The seven `*-runtime` entries below carry `enforcerRef: null` deliberately.
34
+ *
35
+ * They used to point at one module that built seven enforcers out of a shared
36
+ * `buildContract` helper. Nothing imported any of them, so it enforced nothing,
37
+ * and the audit's liveness probe already classified these entries `prose-only`
38
+ * for exactly that reason — the null states the same fact directly rather than
39
+ * through a probe. The module is gone; `peaks audit red-lines` reports identical
40
+ * counts with it gone and with it present, which is the check that this was
41
+ * cleanup and not a change of verdict.
42
+ *
43
+ * Wiring them is not the cheaper-looking alternative. Run against the SKILL.md
44
+ * files as they stand, six of the seven FIRE — only `peaks-doctor` is clean —
45
+ * and each would have to be satisfied by editing a shipped SKILL.md until it
46
+ * contains the phrase its regex expects. Re-decide the contracts first; do not
47
+ * wire these to "restore" them.
48
+ */
32
49
  export declare const PEAKS_AUDIT_RUNTIME: RedLineCatalogEntry;
33
50
  export declare const PEAKS_CONTENT_RUNTIME: RedLineCatalogEntry;
34
51
  export declare const PEAKS_IDE_RUNTIME: RedLineCatalogEntry;
@@ -145,6 +145,23 @@ export const PEAKS_CODE_RUNTIME_CONTRACT = {
145
145
  * can spread this list into RED_LINE_CATALOG and add their own without
146
146
  * touching this file.
147
147
  */
148
+ /**
149
+ * The seven `*-runtime` entries below carry `enforcerRef: null` deliberately.
150
+ *
151
+ * They used to point at one module that built seven enforcers out of a shared
152
+ * `buildContract` helper. Nothing imported any of them, so it enforced nothing,
153
+ * and the audit's liveness probe already classified these entries `prose-only`
154
+ * for exactly that reason — the null states the same fact directly rather than
155
+ * through a probe. The module is gone; `peaks audit red-lines` reports identical
156
+ * counts with it gone and with it present, which is the check that this was
157
+ * cleanup and not a change of verdict.
158
+ *
159
+ * Wiring them is not the cheaper-looking alternative. Run against the SKILL.md
160
+ * files as they stand, six of the seven FIRE — only `peaks-doctor` is clean —
161
+ * and each would have to be satisfied by editing a shipped SKILL.md until it
162
+ * contains the phrase its regex expects. Re-decide the contracts first; do not
163
+ * wire these to "restore" them.
164
+ */
148
165
  export const PEAKS_AUDIT_RUNTIME = {
149
166
  id: 'rl-peaks-audit-runtime-001',
150
167
  rule: 'peaks-audit SKILL.md must declare the audit-runtime contract (machine-readable audit log, six-dimension audit, author identity)',
@@ -155,14 +172,14 @@ export const PEAKS_AUDIT_RUNTIME = {
155
172
  '6 dimensions',
156
173
  'author identity.*local gitconfig'
157
174
  ],
158
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
175
+ enforcerRef: null
159
176
  };
160
177
  export const PEAKS_CONTENT_RUNTIME = {
161
178
  id: 'rl-peaks-content-runtime-001',
162
179
  rule: 'peaks-content SKILL.md must declare the content-runtime contract (what this skill do, failure mode, each red line is written)',
163
180
  markers: ['MANDATORY', 'BLOCKING'],
164
181
  phrases: ['what this skill do', 'failure mode', 'each red line is written'],
165
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
182
+ enforcerRef: null
166
183
  };
167
184
  export const PEAKS_IDE_RUNTIME = {
168
185
  id: 'rl-peaks-ide-runtime-001',
@@ -173,33 +190,33 @@ export const PEAKS_IDE_RUNTIME = {
173
190
  'what this skill do',
174
191
  'general workflow-gating tool'
175
192
  ],
176
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
193
+ enforcerRef: null
177
194
  };
178
195
  export const PEAKS_DOCTOR_RUNTIME = {
179
196
  id: 'rl-peaks-doctor-runtime-001',
180
197
  rule: 'peaks-doctor SKILL.md must declare the doctor-orchestrator marker',
181
198
  markers: ['MANDATORY'],
182
199
  phrases: ['peaks-loop doctor is a doctor orchestrator'],
183
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
200
+ enforcerRef: null
184
201
  };
185
202
  export const PEAKS_ISSUE_FIX_ORCHESTRATOR_RUNTIME = {
186
203
  id: 'rl-peaks-issue-fix-orchestrator-runtime-001',
187
204
  rule: 'peaks-issue-fix-orchestrator SKILL.md must declare the deviation note + autonomous work proceed markers',
188
205
  markers: ['MANDATORY'],
189
206
  phrases: ['deviation note', 'autonomous work proceed'],
190
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
207
+ enforcerRef: null
191
208
  };
192
209
  export const PEAKS_SOP_RUNTIME = {
193
210
  id: 'rl-peaks-sop-runtime-001',
194
211
  rule: 'peaks-sop SKILL.md must declare the sop-runtime contract (each red line below, sop lint reports findings)',
195
212
  markers: ['MANDATORY'],
196
213
  phrases: ['each red line below is written', 'sop lint reports findings'],
197
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
214
+ enforcerRef: null
198
215
  };
199
216
  export const PEAKS_SLICE_DECOMPOSE_RUNTIME = {
200
217
  id: 'rl-peaks-slice-decompose-runtime-001',
201
218
  rule: 'peaks-slice-decompose SKILL.md must declare the slice-decompose contract (what this skill do, failure mode)',
202
219
  markers: ['MANDATORY'],
203
220
  phrases: ['what this skill do', 'failure mode ('],
204
- enforcerRef: 'src/services/audit/enforcers/lint-peaks-skill-runtime.ts'
221
+ enforcerRef: null
205
222
  };
@@ -0,0 +1,26 @@
1
+ export type AuditRole = 'security' | 'perf';
2
+ export interface HandoffMissingRefusal {
3
+ readonly warnings: readonly string[];
4
+ readonly nextActions: readonly string[];
5
+ }
6
+ /**
7
+ * Build the refusal payload for a `handoff-missing` detect result.
8
+ *
9
+ * `envelopeValidated` is a MEASUREMENT, not an assumption — pass
10
+ * `envelope !== undefined && is<Role>AuditEnvelope(envelope)`. The load-bearing
11
+ * sentence is emitted only when it is true: the read-only `detect` surface
12
+ * carries no envelope at all, so claiming there that the envelope was valid
13
+ * would be a claim stronger than the code.
14
+ *
15
+ * An omitted `requestId` is the un-scoped probe: `resolveHandoffPath` could only
16
+ * have tried `prd/handoff.md`, so the refusal must not name the slice-scoped path
17
+ * as the missing one, and must say that the creating command needs a `--rid`
18
+ * this run does not have.
19
+ */
20
+ export declare function handoffMissingRefusal(opts: {
21
+ readonly role: AuditRole;
22
+ readonly projectRoot: string;
23
+ readonly sessionId: string;
24
+ readonly requestId?: string;
25
+ readonly envelopeValidated: boolean;
26
+ }): HandoffMissingRefusal;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The `handoff-missing` refusal text, in one module so the security and perf
3
+ * arms cannot drift apart.
4
+ *
5
+ * WHY THIS EXISTS. Both audit services read `prd/handoff-<rid>.md` and refuse
6
+ * with detect state `handoff-missing` when it is absent — writing nothing. The
7
+ * refusal used to name only the DIRECTORY and never said the audit itself had
8
+ * succeeded. Measured twice on 2026-10-13, once per slice, by four independent
9
+ * reviewers — the two slice ids are named in the RD request artifact, not here,
10
+ * so this comment carries the fact without carrying provenance that rots:
11
+ * each produced an envelope that PASSED `isSecurityAuditEnvelope` /
12
+ * `isPerfAuditEnvelope` — so the run got past validation to this gate — and then
13
+ * could not land it. The refusal named a file they had never been told they
14
+ * would need, and the real order is handoff → audit.
15
+ *
16
+ * So the refusal now states the order: the envelope was valid, only the write is
17
+ * blocked, here is the missing path, here is the one command that creates it.
18
+ *
19
+ * NOT DONE HERE, deliberately: creating the handoff. An audit must not author
20
+ * its own input — synthesising the capsule would make the audit's premise
21
+ * self-supplied — so this module names the creating command and stops.
22
+ */
23
+ import { join } from 'node:path';
24
+ import { handoffRelativePath } from '../prd/handoff-service.js';
25
+ /** Per-role names, so the two arms differ by data rather than by copy-paste. */
26
+ const ROLE = {
27
+ security: { skill: 'peaks-security-audit', validator: 'isSecurityAuditEnvelope' },
28
+ perf: { skill: 'peaks-perf-audit', validator: 'isPerfAuditEnvelope' }
29
+ };
30
+ /** The replaced range, by name: C0 … DEL … C1. */
31
+ const LAST_C0_CODE_POINT = 0x1f;
32
+ const DEL_CODE_POINT = 0x7f;
33
+ const FIRST_C1_CODE_POINT = 0x80;
34
+ const LAST_C1_CODE_POINT = 0x9f;
35
+ const isControlCodePoint = (code) => code <= LAST_C0_CODE_POINT ||
36
+ code === DEL_CODE_POINT ||
37
+ (code >= FIRST_C1_CODE_POINT && code <= LAST_C1_CODE_POINT);
38
+ /**
39
+ * A value as it may be PRINTED: control code points replaced with `?`, never
40
+ * truncated — the same set `printableWarningText` (`src/cli/cli-helpers.ts`) and
41
+ * `printableToken` (`.husky/pipeline/contract-verdict.mjs`) replace, and the same
42
+ * code-point comparison `printableWarningText` uses to find them.
43
+ *
44
+ * `requestId` is safe without this (`handoffRelativePath` enforces
45
+ * `REQUEST_ID_PATTERN`), but `sessionId` is guarded only by `isUnsafePathInput`,
46
+ * which rejects traversal and drive paths and NOT C0/C1 control characters. A
47
+ * newline in a `--sid` would otherwise split a refusal line and forge one of its
48
+ * own — on the very surface this module exists to make readable.
49
+ */
50
+ function printable(value) {
51
+ let rendered = '';
52
+ for (const char of value) {
53
+ rendered += isControlCodePoint(char.codePointAt(0) ?? 0) ? '?' : char;
54
+ }
55
+ return rendered;
56
+ }
57
+ /**
58
+ * Build the refusal payload for a `handoff-missing` detect result.
59
+ *
60
+ * `envelopeValidated` is a MEASUREMENT, not an assumption — pass
61
+ * `envelope !== undefined && is<Role>AuditEnvelope(envelope)`. The load-bearing
62
+ * sentence is emitted only when it is true: the read-only `detect` surface
63
+ * carries no envelope at all, so claiming there that the envelope was valid
64
+ * would be a claim stronger than the code.
65
+ *
66
+ * An omitted `requestId` is the un-scoped probe: `resolveHandoffPath` could only
67
+ * have tried `prd/handoff.md`, so the refusal must not name the slice-scoped path
68
+ * as the missing one, and must say that the creating command needs a `--rid`
69
+ * this run does not have.
70
+ */
71
+ export function handoffMissingRefusal(opts) {
72
+ const { skill, validator } = ROLE[opts.role];
73
+ // The real paths are built from the RAW ids, so `handoffRelativePath`'s guard
74
+ // runs on exactly the bytes `resolveHandoffPath` would probe. Each value is
75
+ // sanitised at the point it is interpolated, below — not here — so the render
76
+ // is the only thing that changes.
77
+ const prdDir = join(opts.projectRoot, '.peaks', '_runtime', opts.sessionId, 'prd');
78
+ // The path the creating command WRITES. With a rid that is the slice-scoped
79
+ // capsule; `resolveHandoffPath` already ran `handoffRelativePath` for these
80
+ // same ids on the way in, so this join cannot throw where that one did not.
81
+ const missingPath = opts.requestId === undefined
82
+ ? join(prdDir, 'handoff.md')
83
+ : join(opts.projectRoot, handoffRelativePath(opts.sessionId, opts.requestId));
84
+ const createCommand = opts.requestId === undefined
85
+ ? `peaks prd handoff init --rid <request-id> --sid ${opts.sessionId} --body <body> --apply`
86
+ : `peaks prd handoff init --rid ${opts.requestId} --sid ${opts.sessionId} --body <body> --apply`;
87
+ return {
88
+ warnings: [
89
+ `peaks-prd handoff not found under ${printable(prdDir)}`,
90
+ ...(opts.requestId === undefined
91
+ ? [
92
+ "No --rid was supplied, so only the pre-rid-scoping `prd/handoff.md` could be probed. Pass --rid to resolve this slice's `prd/handoff-<rid>.md`."
93
+ ]
94
+ : [])
95
+ ],
96
+ nextActions: [
97
+ ...(opts.envelopeValidated
98
+ ? [
99
+ `The audit envelope passed validation (${validator}); only the artifact write is blocked.`
100
+ ]
101
+ : []),
102
+ opts.requestId === undefined
103
+ ? `The only handoff path probed was: ${printable(missingPath)}`
104
+ : `Missing peaks-prd handoff: ${printable(missingPath)}`,
105
+ `Create it with: ${printable(createCommand)}`,
106
+ `Until the handoff exists, ${skill} cannot start (gate fail).`
107
+ ]
108
+ };
109
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Reading the sha256-locked PRD handoff capsule and the project-level security
3
+ * template. Split out of `security-audit-service.ts` so the audit service and
4
+ * the declaration's producer can both depend on the readers without depending
5
+ * on each other.
6
+ */
7
+ /**
8
+ * Handoff frontmatter — minimal projection of the peaks-prd v2.11.0 handoff
9
+ * frontmatter. We only need sha256 for verification; the rest of the handoff
10
+ * body is consumed by the parent LLM, not by this service.
11
+ */
12
+ export interface HandoffFrontmatter {
13
+ readonly sha256: string;
14
+ readonly schemaVersion: number;
15
+ }
16
+ /**
17
+ * Read the peaks-prd handoff frontmatter + body, verify sha256 matches
18
+ * the body. Returns null on missing file or sha256 mismatch; otherwise
19
+ * returns the parsed frontmatter + body string.
20
+ *
21
+ * Defensive: we read frontmatter via a 1-line regex match, not via
22
+ * a YAML parser. The handoff service (`src/services/prd/handoff-service.ts`)
23
+ * is the canonical writer; we only consume its output here.
24
+ */
25
+ export declare function readAndVerifyHandoff(handoffPath: string, projectRoot: string): {
26
+ frontmatter: HandoffFrontmatter;
27
+ body: string;
28
+ } | null;
29
+ /**
30
+ * Read the project-level security-template.md. Returns the body
31
+ * string (with frontmatter stripped) or null if the file is absent.
32
+ * Does NOT validate the template content; the parent LLM validates
33
+ * by reading.
34
+ */
35
+ export declare function readSecurityTemplate(projectRoot: string): string | null;
36
+ /** The verified handoff's sha256, or `unknown` when there is no capsule. */
37
+ export declare function resolveHandoffHash(projectRoot: string, sessionId: string, rid: string): string;