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
@@ -1,5 +1,5 @@
1
1
  import { type DispatchOptions } from './sub-agent-shared.js';
2
- export declare function buildIsolationBlock(isolationMode: 'worktree' | 'container' | 'vm' | null, leaseId: string | null, worktreePath: string | null, worktreeBranch: string | null): string;
2
+ export declare function buildIsolationBlock(isolationMode: 'worktree' | 'container' | null, leaseId: string | null, worktreePath: string | null, worktreeBranch: string | null): string;
3
3
  export declare function buildMustLsFilesBlock(options: DispatchOptions, projectRoot: string): {
4
4
  mustLsFilesVerification: {
5
5
  path: string;
@@ -1,3 +1,4 @@
1
+ import type { Command } from 'commander';
1
2
  import { type ProgramIO } from '../cli-helpers.js';
2
3
  import { getAdapter } from '../../services/ide/ide-registry.js';
3
4
  import type { ContextGuardDecision } from '../../services/context/context-guard.js';
@@ -10,12 +11,17 @@ export interface ComposeDispatchPromptInput {
10
11
  options: DispatchOptions;
11
12
  /** The prompt the sub-agent receives, as `preflightDispatch` resolved it. */
12
13
  prompt: string;
13
- isolationMode: 'worktree' | 'container' | 'vm' | null;
14
+ isolationMode: 'worktree' | 'container' | null;
14
15
  leaseId: string | null;
15
16
  worktreePath: string | null;
16
17
  worktreeBranch: string | null;
17
18
  decision: ContextGuardDecision;
18
19
  asJson: boolean;
20
+ /**
21
+ * The registered CLI, so the prompt's own quotations of it can be resolved
22
+ * against the commands that exist rather than against a second, hand-kept list.
23
+ */
24
+ rootCommand: Command;
19
25
  }
20
26
  export interface ComposedDispatchPrompt {
21
27
  adapter: ReturnType<typeof getAdapter>;
@@ -1,7 +1,3 @@
1
- // The prompt `peaks sub-agent dispatch` hands a sub-agent: the adapter check, the
2
- // optional preflight blocks (memory / codegraph / UI library / fresh context /
3
- // context probe / session capsule), the isolation and must-ls-files blocks, and the
4
- // warning list the envelope carries.
5
1
  import { fail, getErrorMessage } from 'peaks-loop-shared/result';
6
2
  import { printResult } from '../cli-helpers.js';
7
3
  import { detectInstalledIde } from '../../services/ide/ide-detector.js';
@@ -16,6 +12,9 @@ import { computeUiLibraryDispatchBlock } from '../../services/standards/ui-libra
16
12
  import { readFreshContextBlock } from '../../services/fresh-context/fresh-context-block.js';
17
13
  import { deprecatedReviewerWarnings } from './sub-agent-shared.js';
18
14
  import { buildIsolationBlock, buildMustLsFilesBlock } from './dispatch-prompt-blocks.js';
15
+ import { ensureArtifactContractBlock, readArtifactContractBlock } from '../../services/artifacts/artifact-contract-block.js';
16
+ import { ensureKarpathyBlock } from '../../services/dispatch/karpathy-block.js';
17
+ import { cliInvocationWarnings } from './dispatch-cli-invocation-check.js';
19
18
  // loadPreferences can throw on schema mismatch; we fall back to defaults
20
19
  // to avoid breaking the dispatch on a stale preferences.json file.
21
20
  function loadProjectPreferences(projectRoot) {
@@ -154,7 +153,7 @@ async function composeMemoryAugmentedBody(input, projectPrefs) {
154
153
  });
155
154
  }
156
155
  export async function composeDispatchPrompt(io, input) {
157
- const { projectRoot, role, options, isolationMode, leaseId, worktreePath, worktreeBranch, decision, asJson } = input;
156
+ const { projectRoot, sid, rid, role, options, isolationMode, leaseId, worktreePath, worktreeBranch, decision, asJson, rootCommand, prompt } = input;
158
157
  const projectPrefs = loadProjectPreferences(projectRoot);
159
158
  const ide = detectInstalledIde(projectRoot) ?? 'claude-code';
160
159
  const adapter = getAdapter(ide);
@@ -164,8 +163,31 @@ export async function composeDispatchPrompt(io, input) {
164
163
  const memoryAugmentedBody = await composeMemoryAugmentedBody(input, projectPrefs);
165
164
  const isolationBlock = buildIsolationBlock(isolationMode, leaseId, worktreePath, worktreeBranch);
166
165
  const { mustLsFilesVerification, mustLsFilesBlock } = buildMustLsFilesBlock(options, projectRoot);
167
- const effectivePrompt = `${memoryAugmentedBody}${isolationBlock}${mustLsFilesBlock}`;
166
+ // What the downstream gate will demand of this role, named in advance. `''`
167
+ // when this role has no gated artifacts under this type, so an unaffected
168
+ // role's prompt stays byte-identical. Injection is idempotent — a caller
169
+ // prompt that already carries a block keeps exactly one (see the helper).
170
+ const contractBlock = await readArtifactContractBlock({
171
+ projectRoot,
172
+ sessionId: sid,
173
+ requestId: rid,
174
+ role
175
+ });
176
+ // The presence test runs on the ASSEMBLED prompt, not on the caller's draft:
177
+ // this string is what the sub-agent receives as `toolCall.args.prompt` and
178
+ // what the dispatch record stores as `prompt`. A draft that merely names
179
+ // Karpathy (or carries a copy with a word wrong) does not count as carrying
180
+ // the canonical block, so the block is added rather than trusted.
181
+ const effectivePrompt = ensureKarpathyBlock(ensureArtifactContractBlock(`${memoryAugmentedBody}${isolationBlock}${mustLsFilesBlock}`, contractBlock));
182
+ // Findings travel as WARNINGS, never as a refusal, and they are read off the
183
+ // CALLER's prompt rather than the assembled one — both decisions are measured
184
+ // and recorded on `dispatch-cli-invocation-check.ts`.
185
+ const invocationWarnings = cliInvocationWarnings(prompt, rootCommand);
168
186
  // + rerouted here, never refused — rationale on the helper itself.
169
- const warnings = [...decision.warnings, ...deprecatedReviewerWarnings(role)];
187
+ const warnings = [
188
+ ...decision.warnings,
189
+ ...deprecatedReviewerWarnings(role),
190
+ ...invocationWarnings
191
+ ];
170
192
  return { adapter, effectivePrompt, warnings, mustLsFilesVerification };
171
193
  }
@@ -11,7 +11,7 @@ export interface WriteDispatchRecordInput {
11
11
  effectivePrompt: string;
12
12
  toolCall: SubAgentToolCall;
13
13
  batchId: string;
14
- isolationMode: 'worktree' | 'container' | 'vm' | null;
14
+ isolationMode: 'worktree' | 'container' | null;
15
15
  leaseId: string | null;
16
16
  /** The dispatch's warning list — this function appends to it, as the inline block did. */
17
17
  warnings: string[];
@@ -8,7 +8,7 @@ export interface BuildDispatchToolCallInput {
8
8
  rid: string;
9
9
  sid: string;
10
10
  projectRoot: string;
11
- isolationMode: 'worktree' | 'container' | 'vm' | null;
11
+ isolationMode: 'worktree' | 'container' | null;
12
12
  leaseId: string | null;
13
13
  asJson: boolean;
14
14
  }
@@ -6,6 +6,7 @@
6
6
  *
7
7
  * See `src/services/doc/doc-generator.ts` for the underlying logic.
8
8
  */
9
+ import { mkdirSync, writeFileSync } from 'node:fs';
9
10
  import { resolve as resolvePath } from 'node:path';
10
11
  import { findProjectRoot } from '../../services/config/config-safety.js';
11
12
  import { generateSkillFromCommands, gitLogSince, renderSkillMarkdown, suggestChangelog } from '../../services/doc/doc-generator.js';
@@ -31,7 +32,6 @@ export function registerDocCommands(program, io) {
31
32
  if (opts.output !== undefined) {
32
33
  // Write to file
33
34
  try {
34
- const { writeFileSync, mkdirSync } = require('node:fs');
35
35
  mkdirSync(resolvePath(opts.output, '..'), { recursive: true });
36
36
  writeFileSync(resolvePath(opts.output), md, 'utf8');
37
37
  printResult(io, ok('doc.generate-skill', {
@@ -18,7 +18,7 @@ export const CHECK_UNPROMOTED_DESCRIPTION = 'Scan `.peaks/memory/*.md` and list
18
18
  export const NO_LAYER_NEXT_ACTIONS = [
19
19
  'No --layer passed. Choose one of A / B / C and re-run.',
20
20
  'A: append to sops/*.md (procedural rules)',
21
- 'B: append a matcher to .peaks/.claude-settings-template.json (tool-call interception)',
21
+ 'B: append a matcher to .peaks/.claude-settings-template.json, or to .claude/settings.json for a hook that ships with this repo (tool-call interception)',
22
22
  'C: extend HardFloorCategory in mode-gate.ts (always pauses regardless of mode)',
23
23
  'Or pass --dry-run to preview all three stubs first.'
24
24
  ];
@@ -12,6 +12,7 @@ import { existsSync, statSync } from 'node:fs';
12
12
  import { join, resolve } from 'node:path';
13
13
  import { REQUEST_ID_PATTERN } from '../../services/artifacts/request-artifact-service.js';
14
14
  import { createAnthropicRunner, LlmBindingError, resolveAnthropicConfig } from '../../services/llm/anthropic-runner.js';
15
+ import { emitTokenUsageEvent } from '../../services/observability/observability-service.js';
15
16
  import { prepareFinalReview } from '../../services/final-review/final-review-service.js';
16
17
  import { getErrorMessage } from '../cli-helpers.js';
17
18
  import { DEFAULT_LLM_PROVIDER, isSupportedLlmProvider, SUPPORTED_LLM_PROVIDERS } from './final-review-command-shared.js';
@@ -136,6 +137,25 @@ function resolvePrepareInputs(rid, options) {
136
137
  function isRefusal(value) {
137
138
  return !('projectRoot' in value);
138
139
  }
140
+ /**
141
+ * The `token-usage` emission owner: the one site where a completed review's
142
+ * token counts and the session binding are both in scope. Fire-and-forget —
143
+ * `emitTokenUsageEvent` never throws, and this never blocks or fails the review
144
+ * it reports on.
145
+ *
146
+ * `source` defaults to `'provider'` only for a runner that states neither: the
147
+ * real runner always tags its counts (`anthropic-runner.ts` `tokenCounts`), so
148
+ * the default is reached by a test fake, not by a production call.
149
+ */
150
+ function emitReviewTokenUsage(inputs, tokens) {
151
+ emitTokenUsageEvent({
152
+ projectRoot: inputs.projectRoot,
153
+ sessionId: inputs.sessionId,
154
+ inputTokens: tokens.input,
155
+ outputTokens: tokens.output,
156
+ source: tokens.source ?? 'provider'
157
+ });
158
+ }
139
159
  /**
140
160
  * Real provider path: bind a real `LlmRunner` and run the service.
141
161
  *
@@ -153,7 +173,8 @@ async function runRealReview(io, rid, inputs, options) {
153
173
  projectRoot: inputs.projectRoot,
154
174
  sessionId: inputs.sessionId,
155
175
  llmRunner,
156
- ...(options.base === undefined ? {} : { baseRef: options.base })
176
+ ...(options.base === undefined ? {} : { baseRef: options.base }),
177
+ onLlmTokens: (tokens) => emitReviewTokenUsage(inputs, tokens)
157
178
  });
158
179
  emitReviewEnvelope(io, { rid, goal: inputs, model: config.model, review, json });
159
180
  }
@@ -149,9 +149,9 @@ export function emitAllowSkipped(io, options) {
149
149
  }
150
150
  /**
151
151
  * Hard block: a worktree-mutating tool call without a current-task user grant. emitBlock writes
152
- * the Claude Code permissionDecision:"deny" envelope and exits 2. The reason includes the
153
- * remediation hint so the LLM can run `peaks worktree auth grant` and retry, and the user can
154
- * read the deny text in the next-turn stderr.
152
+ * the Claude Code permissionDecision:"deny" envelope and exits 2. The reason carries the
153
+ * remediation hint from `worktree-refusal-messages.ts`, which names the USER-side path — the
154
+ * grant is not the agent's to issue — and the user can read the deny text in the next-turn stderr.
155
155
  */
156
156
  function emitWorktreeDeny(io, options, wtDecision) {
157
157
  emitBlock(io, `[worktree-gate:${wtDecision.code}] ${wtDecision.reason} — ${wtDecision.remediation}`);
@@ -5,7 +5,7 @@ import { getAdapter } from '../../services/ide/ide-registry.js';
5
5
  import { evaluateCodeBan } from '../../services/audit/enforcers/code-ban.js';
6
6
  import { isRootWrite } from '../../services/audit/enforcers/no-root-pollution.js';
7
7
  import { checkLoginGate } from '../../services/audit/enforcers/login-gate.js';
8
- import { resolveActiveSkillForCaller } from '../../services/audit/enforcers/active-skill-resolver.js';
8
+ import { hasLeaseForCaller, hasPeaksLeaseInSession, resolveActiveSkillForCaller } from '../../services/audit/enforcers/active-skill-resolver.js';
9
9
  import { fail, ok } from 'peaks-loop-shared/result';
10
10
  import { emitDecision, emitHint } from '../../services/hooks/output.js';
11
11
  /**
@@ -98,26 +98,47 @@ export function registerHookHandleCommand(program, io) {
98
98
  // The envelope shape (skill / callerId / sessionId / source) is
99
99
  // unchanged from 4.0.7; the underlying source is now
100
100
  // `canonical` for the lease + index path.
101
- const activeSkill = resolveActiveSkillForCaller(projectRoot);
102
- if (activeSkill.skill !== null) {
103
- const codeDecision = evaluateCodeBan({
104
- skill: activeSkill.skill,
105
- command: fallbackCommand
106
- });
107
- if (codeDecision.denied) {
108
- const formatted = formatDecisionResponse(ide, 'deny', codeDecision.reason);
109
- emitDecision(io, formatted.stdout);
110
- if (options.json === true) {
111
- emitHint(io, JSON.stringify(ok('hook.handle', {
112
- ide,
113
- tool: hook.toolName,
114
- decision: 'deny',
115
- reason: codeDecision.reason,
116
- enforcer: 'code-ban'
117
- })));
118
- }
119
- return;
101
+ //
102
+ // Scoped to THIS caller: without a callerId the resolver returns
103
+ // whichever lease `readdirSync` yields first, so another window's skill
104
+ // would be applied here. The identity comes from the payload, not the
105
+ // environment — whether the hook subprocess inherits the
106
+ // caller-identifying env is unverified, and the payload already has it.
107
+ const callerId = pluckString(parsed, ['caller_id']) ?? pluckString(parsed, ['session_id']);
108
+ const identityAvailable = typeof callerId === 'string' && callerId.length > 0;
109
+ const callerHasLease = identityAvailable && hasLeaseForCaller(projectRoot, callerId);
110
+ // A scoped resolve answers for THIS caller only when this caller owns a
111
+ // lease. An id with no lease is ambiguous: either a caller with no peaks
112
+ // skill, or an id that is not the lease's key — and the harness does
113
+ // hand over a differing session id (skill-statusline-service.ts:100-103).
114
+ // The two are indistinguishable here, so that case keeps the unscoped
115
+ // answer, which denies, rather than turning a peaks commit into an allow.
116
+ const activeSkill = !identityAvailable
117
+ ? { skill: null, callerId: null, sessionId: null, mode: null, source: 'none' }
118
+ : callerHasLease
119
+ ? resolveActiveSkillForCaller(projectRoot, { callerId })
120
+ : resolveActiveSkillForCaller(projectRoot);
121
+ // Evaluated even when nothing resolved: the old `if (skill !== null)`
122
+ // guard meant an unresolved driver skipped the ban entirely.
123
+ const codeDecision = evaluateCodeBan({
124
+ skill: activeSkill.skill,
125
+ command: fallbackCommand,
126
+ peaksLeasePresent: hasPeaksLeaseInSession(projectRoot),
127
+ identityResolved: callerHasLease
128
+ });
129
+ if (codeDecision.denied) {
130
+ const formatted = formatDecisionResponse(ide, 'deny', codeDecision.reason);
131
+ emitDecision(io, formatted.stdout);
132
+ if (options.json === true) {
133
+ emitHint(io, JSON.stringify(ok('hook.handle', {
134
+ ide,
135
+ tool: hook.toolName,
136
+ decision: 'deny',
137
+ reason: codeDecision.reason,
138
+ enforcer: 'code-ban'
139
+ })));
120
140
  }
141
+ return;
121
142
  }
122
143
  // Lazy import to avoid circular: peaks gate enforce logic
123
144
  const { enforceBashCommand } = await import('../../services/sop/gate-enforce-service.js');
@@ -116,7 +116,9 @@ export function registerLintCommands(program, io) {
116
116
  }
117
117
  const envelope = result.state === 'ok' || result.state === 'baseline-missing'
118
118
  ? ok('code.lint', { ...result, ...extras }, [], [])
119
- : fail('code.lint', result.state.toUpperCase().replace(/-/g, '_'), `peaks code lint state: ${result.state}`, { ...result, ...extras }, [`Re-run with --scope <path> or restore the ESLint toolchain.`]);
119
+ : fail('code.lint', result.state.toUpperCase().replace(/-/g, '_'), `peaks code lint state: ${result.state}${result.reason === undefined ? '' : ` — ${result.reason}`}`, { ...result, ...extras }, [
120
+ 'The reason above names which condition fired; a spawn timeout wants a larger --timeout-ms.'
121
+ ]);
120
122
  printResult(io, envelope, options.json);
121
123
  });
122
124
  addJsonOption(lint
@@ -1,7 +1,7 @@
1
1
  // The cycle-file index seam for `--capture-score`. Pure path/IO plus its own path-safety
2
2
  // contract; it owns no command registration, which is why it lives outside the
3
3
  // registrar that calls it.
4
- import { existsSync } from 'node:fs';
4
+ import { existsSync, readdirSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { isUnsafePathInput } from '../../shared/path-safety.js';
7
7
  /** Test seam: pick the next cycle-N.json number for capture-score
@@ -22,11 +22,9 @@ export function nextEvalCaptureIndex(projectRoot, sid, rid) {
22
22
  const dir = join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'cycles');
23
23
  if (!existsSync(dir))
24
24
  return 1;
25
- // eslint-disable-next-line @typescript-eslint/no-var-requires
26
- const fs = require('node:fs');
27
25
  let entries;
28
26
  try {
29
- entries = fs.readdirSync(dir);
27
+ entries = readdirSync(dir);
30
28
  }
31
29
  catch {
32
30
  return 1;
@@ -111,13 +111,13 @@ export function nextActionsForArchiveError(code) {
111
111
  ];
112
112
  case 'OPENSPEC_COVERAGE_EVIDENCE_MISSING':
113
113
  return [
114
- 'Run `pnpm test:coverage` (which invokes scripts/coverage-c8.mjs) to generate coverage-summary.json',
114
+ 'Generate coverage/coverage-summary.json with the project coverage run (`node .husky/coverage-ratchet.mjs` in this repo)',
115
115
  'Or pass --coverage-summary <path> to point at an existing summary',
116
116
  'Or re-run with --force to bypass the gate'
117
117
  ];
118
118
  case 'OPENSPEC_COVERAGE_EVIDENCE_STALE':
119
119
  return [
120
- 'Re-run `pnpm test:coverage` to refresh coverage-summary.json',
120
+ 'Re-generate coverage/coverage-summary.json, then re-run',
121
121
  'Or re-run with --force to bypass the gate after confirming the source delta is acceptable'
122
122
  ];
123
123
  case 'OPENSPEC_COVERAGE_EVIDENCE_MISMATCH':
@@ -19,9 +19,7 @@ function readStdinSync() {
19
19
  // Node 22: read stdin synchronously via fs.readFileSync(0, 'utf8').
20
20
  // We use the file descriptor 0 convention.
21
21
  try {
22
- // Lazy import to avoid pulling readline at module load
23
- const { readFileSync: rfs } = require('node:fs');
24
- const raw = rfs(0, 'utf8');
22
+ const raw = readFileSync(0, 'utf8');
25
23
  if (raw.trim().length === 0) {
26
24
  throw new Error('stdin was empty; expected JSON envelope on stdin or --envelope <path>');
27
25
  }
@@ -63,7 +61,14 @@ export function registerPerfAuditCommands(program, io) {
63
61
  });
64
62
  const envelope = detect.state === 'ready'
65
63
  ? ok('perf-audit.detect', detect, [...detect.warnings], [...detect.nextActions])
66
- : fail('perf-audit.detect', detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${detect.state}`, detect, [...detect.nextActions]);
64
+ : {
65
+ // `fail()` builds `warnings: []`, so the detector's own diagnosis is
66
+ // spread over it. Without this the human-readable refusal drops the
67
+ // sentence saying WHY the run is not ready, while `--json` keeps it
68
+ // at `data.detect.warnings` — the 9.2 shape, one surface over.
69
+ ...fail('perf-audit.detect', detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${detect.state}`, detect, [...detect.nextActions]),
70
+ warnings: [...detect.warnings]
71
+ };
67
72
  printResult(io, envelope, options.json);
68
73
  if (detect.state !== 'ready') {
69
74
  process.exitCode = 1;
@@ -118,7 +123,12 @@ export function registerPerfAuditCommands(program, io) {
118
123
  envelope: envelopeValue
119
124
  });
120
125
  if (result.detect.state !== 'ready' || result.artifactPath === null) {
121
- printResult(io, fail('perf-audit.run', result.detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${result.detect.state}`, result, [...result.detect.nextActions]), options.json);
126
+ printResult(io, {
127
+ // Same spread as the detect arm: the run's refusal is the only place
128
+ // the detector's warning would reach a person, and `fail()` empties it.
129
+ ...fail('perf-audit.run', result.detect.state.toUpperCase().replace(/-/g, '_'), `perf-audit is not ready: ${result.detect.state}`, result, [...result.detect.nextActions]),
130
+ warnings: [...result.detect.warnings]
131
+ }, options.json);
122
132
  process.exitCode = 1;
123
133
  return;
124
134
  }
@@ -17,7 +17,7 @@
17
17
  * `project-memory-index-command.ts`, `project-memories-show-command.ts`,
18
18
  * `project-knowledge-command.ts`.
19
19
  */
20
- import { describeMemoryBlockDrops, describeSessionScanFailures, extractSessionMemories, readProjectMemories, VALID_PROJECT_MEMORY_KINDS } from '../../services/memory/project-memory-service.js';
20
+ import { describeMemoryBlockDrops, describeMemoryWriteSkips, describeSessionScanFailures, extractSessionMemories, readProjectMemories, VALID_PROJECT_MEMORY_KINDS } from '../../services/memory/project-memory-service.js';
21
21
  import { fail, ok } from 'peaks-loop-shared/result';
22
22
  import { addJsonOption, getErrorMessage, printResult } from '../cli-helpers.js';
23
23
  import { registerProjectDashboardCommand } from './project-dashboard-command.js';
@@ -38,15 +38,18 @@ function extractData(result) {
38
38
  };
39
39
  }
40
40
  /**
41
- * Two drop axes, one channel. `droppedBlocks` = a block was found and rejected
42
- * (or a marker-shaped comment was not findable at all); `scanFailures` = the
43
- * whole artifact could not be read, so its blocks were never candidates.
44
- * `data` is unchanged by either — same contract as `memory.extract`.
41
+ * Three axes, one channel. `droppedBlocks` = a block was found and rejected (or
42
+ * a marker-shaped comment was not findable at all); `scanFailures` = the whole
43
+ * artifact could not be read, so its blocks were never candidates;
44
+ * `skippedWrites` = the block parsed and was planned, and the store already held
45
+ * its target name, so nothing was written. `data` is unchanged by any of them —
46
+ * same contract as `memory.extract`.
45
47
  */
46
48
  function extractWarnings(result) {
47
49
  return [
48
50
  ...describeMemoryBlockDrops(result.droppedBlocks),
49
- ...describeSessionScanFailures(result.scanFailures)
51
+ ...describeSessionScanFailures(result.scanFailures),
52
+ ...describeMemoryWriteSkips(result.skippedWrites, result.extractedCount, result.writtenFiles.length)
50
53
  ];
51
54
  }
52
55
  function runProjectMemories(io, options) {
@@ -0,0 +1,15 @@
1
+ import type { Command } from 'commander';
2
+ import { type PilotGateCounts, type PilotGateReason, type PilotGateVerdict } from '../../services/race/gate2-evaluator.js';
3
+ import { type RaceGate2Policy } from '../../services/race/gate2-policy.js';
4
+ import { type ProgramIO } from '../cli-helpers.js';
5
+ export type PilotStatusReport = {
6
+ readonly policyVersion: string;
7
+ readonly evaluatorVersion: string;
8
+ readonly recordedPolicyVersion?: string;
9
+ readonly policy: RaceGate2Policy;
10
+ readonly verdict: PilotGateVerdict;
11
+ readonly counts: PilotGateCounts;
12
+ readonly reasons: readonly PilotGateReason[];
13
+ readonly evidencePath: string;
14
+ };
15
+ export declare function registerRaceCommands(program: Command, io: ProgramIO): void;
@@ -0,0 +1,65 @@
1
+ import { CLI_VERSION } from 'peaks-loop-shared/version';
2
+ import { fail, ok } from 'peaks-loop-shared/result';
3
+ import { evaluatePilotGate } from '../../services/race/gate2-evaluator.js';
4
+ import { RACE_GATE2_POLICY_V1, RACE_GATE2_POLICY_VERSION } from '../../services/race/gate2-policy.js';
5
+ import { readPilotGate } from '../../services/race/pilot-gate-store.js';
6
+ import { addJsonOption, printResult } from '../cli-helpers.js';
7
+ import { registerRacePilotGateRecordCommand } from './race-pilot-gate-record-command.js';
8
+ const RACE_DESCRIPTION = 'peaks-race-code fast lane: gate-2 threshold policy and evidence';
9
+ const PILOT_STATUS_DESCRIPTION = 'Judge .peaks/race/pilot-gate.json against the gate-2 policy. Read-only; prints pass | fail | insufficient-evidence.';
10
+ const PROJECT_HELP = 'project root (default: cwd)';
11
+ export function registerRaceCommands(program, io) {
12
+ const race = program.command('race').description(RACE_DESCRIPTION);
13
+ registerRacePilotStatusCommand(race, io);
14
+ registerRacePilotGateRecordCommand(race, io);
15
+ }
16
+ function registerRacePilotStatusCommand(race, io) {
17
+ addJsonOption(race
18
+ .command('pilot-status')
19
+ .description(PILOT_STATUS_DESCRIPTION)
20
+ .option('--project <path>', PROJECT_HELP, '.')).action((options) => runPilotStatus(options, io));
21
+ }
22
+ function refuseNoVerdict(io, options, refusal, path) {
23
+ printResult(io, fail('race.pilot-status', refusal.code, refusal.message, { evidencePath: path }, [
24
+ refusal.nextAction
25
+ ]), options.json);
26
+ process.exitCode = 1;
27
+ }
28
+ function runPilotStatus(options, io) {
29
+ const read = readPilotGate(options.project);
30
+ if (read.kind === 'missing') {
31
+ refuseNoVerdict(io, options, {
32
+ code: 'PILOT_GATE_EVIDENCE_MISSING',
33
+ message: `No gate-2 evidence at ${read.path}: no verdict was reached`,
34
+ nextAction: 'Record a pilot task with `peaks race pilot-gate record`'
35
+ }, read.path);
36
+ return;
37
+ }
38
+ if (read.kind === 'invalid') {
39
+ refuseNoVerdict(io, options, {
40
+ code: 'PILOT_GATE_EVIDENCE_INVALID',
41
+ message: `Gate-2 evidence at ${read.path} is unreadable, so no verdict was reached: ${read.message}`,
42
+ nextAction: 'Repair or re-record the evidence file before judging it'
43
+ }, read.path);
44
+ return;
45
+ }
46
+ const evaluation = evaluatePilotGate(read.gate.tasks, RACE_GATE2_POLICY_V1);
47
+ const report = {
48
+ policyVersion: RACE_GATE2_POLICY_VERSION,
49
+ evaluatorVersion: CLI_VERSION,
50
+ policy: RACE_GATE2_POLICY_V1,
51
+ verdict: evaluation.verdict,
52
+ counts: evaluation.counts,
53
+ reasons: evaluation.reasons,
54
+ evidencePath: read.path
55
+ };
56
+ const withRecorded = read.gate.policyVersion === undefined
57
+ ? report
58
+ : { ...report, recordedPolicyVersion: read.gate.policyVersion };
59
+ printResult(io, ok('race.pilot-status', withRecorded, [], []), options.json);
60
+ // `fail` is the only non-zero verdict: `insufficient-evidence` is the normal
61
+ // "keep running the pilot" state, not a failure (PRD §5.1).
62
+ if (evaluation.verdict === 'fail') {
63
+ process.exitCode = 1;
64
+ }
65
+ }
@@ -0,0 +1,3 @@
1
+ import type { Command } from 'commander';
2
+ import { type ProgramIO } from '../cli-helpers.js';
3
+ export declare function registerRacePilotGateRecordCommand(race: Command, io: ProgramIO): void;
@@ -0,0 +1,81 @@
1
+ import { fail, getErrorMessage, ok } from 'peaks-loop-shared/result';
2
+ import { buildPilotTaskRow, RISK_SURFACE_MAX, upsertPilotTask, HANDLING_VALUES, LANE_CHOSEN_BY_VALUES, OUTCOME_VALUES } from '../../services/race/pilot-gate-store.js';
3
+ import { addJsonOption, multipleOption, printResult } from '../cli-helpers.js';
4
+ const PILOT_GATE_DESCRIPTION = 'Gate-2 evidence for the peaks-race-code fast lane';
5
+ const RECORD_DESCRIPTION = 'Upsert one gate-2 evidence row into .peaks/race/pilot-gate.json, keyed by --rid. Refreshes lastEvaluation.';
6
+ const PROJECT_HELP = 'project root (default: cwd)';
7
+ /**
8
+ * A boolean is required with an explicit `true|false` rather than a `--no-*`
9
+ * flag: Commander's negated form DEFAULTS the flag, which would let a row be
10
+ * written with a `false` nobody chose. A required value makes "must be given
11
+ * explicitly" mechanical instead of a convention.
12
+ */
13
+ function parseBooleanFlag(value) {
14
+ if (value === 'true')
15
+ return true;
16
+ if (value === 'false')
17
+ return false;
18
+ throw new Error(`expected true or false, got ${JSON.stringify(value)}`);
19
+ }
20
+ export function registerRacePilotGateRecordCommand(race, io) {
21
+ const pilotGate = race.command('pilot-gate').description(PILOT_GATE_DESCRIPTION);
22
+ addJsonOption(pilotGate
23
+ .command('record')
24
+ .description(RECORD_DESCRIPTION)
25
+ .requiredOption('--rid <id>', 'task request id (letters or digits, then letters, digits, ".", "_" or "-")')
26
+ .requiredOption('--session-id <session>', 'session the task ran in')
27
+ .requiredOption('--date <YYYY-MM-DD>', 'task date')
28
+ .requiredOption('--lane-chosen-by <who>', `who chose the lane (${LANE_CHOSEN_BY_VALUES.join(' | ')})`)
29
+ .requiredOption('--outcome <outcome>', `task outcome (${OUTCOME_VALUES.join(' | ')})`)
30
+ .option('--file <path>', 'repo-relative changed file (repeatable)', multipleOption, [])
31
+ .option('--risk-surface <n>', `risk surface hit, 1..${RISK_SURFACE_MAX} (repeatable)`, multipleOption, [])
32
+ .requiredOption('--risk-surface-handling <handling>', `how a hit was handled (${HANDLING_VALUES.join(' | ')})`)
33
+ .requiredOption('--rolled-back <true|false>', 'was the change rolled back?', parseBooleanFlag)
34
+ .requiredOption('--ci-red <true|false>', 'is a CI failure attributed to this task?', parseBooleanFlag)
35
+ .requiredOption('--missed-risk-surface <true|false>', 'is a missed risk surface known? (no procedure exists for setting this yet)', parseBooleanFlag)
36
+ .option('--project <path>', PROJECT_HELP, '.')).action((options) => runRecord(options, io));
37
+ }
38
+ /**
39
+ * Validate, then write. Validation is fail-closed and runs BEFORE the upsert:
40
+ * a refusal leaves the evidence file exactly as it was, and the message names
41
+ * the flag that broke a rule.
42
+ */
43
+ /** Flags in, row input out. Every value is re-validated by the store. */
44
+ function toInput(options) {
45
+ return {
46
+ rid: options.rid,
47
+ sessionId: options.sessionId,
48
+ date: options.date,
49
+ laneChosenBy: options.laneChosenBy,
50
+ outcome: options.outcome,
51
+ filesChanged: options.file ?? [],
52
+ riskSurfacesHit: (options.riskSurface ?? []).map((value) => Number(value)),
53
+ riskSurfaceHandling: options.riskSurfaceHandling,
54
+ rolledBack: options.rolledBack,
55
+ ciRed: options.ciRed,
56
+ missedRiskSurface: options.missedRiskSurface
57
+ };
58
+ }
59
+ function runRecord(options, io) {
60
+ const built = buildPilotTaskRow(toInput(options));
61
+ if (built.kind === 'invalid') {
62
+ printResult(io, fail('race.pilot-gate.record', 'PILOT_TASK_INVALID', built.message, { rid: options.rid }, [
63
+ 'Fix the flag this message names; nothing was written'
64
+ ]), options.json);
65
+ process.exitCode = 1;
66
+ return;
67
+ }
68
+ try {
69
+ const result = upsertPilotTask(options.project, built.row);
70
+ printResult(io, ok('race.pilot-gate.record', {
71
+ rid: built.row.rid,
72
+ evidencePath: result.path,
73
+ verdict: result.evaluation.verdict,
74
+ counts: result.evaluation.counts
75
+ }, [], []), options.json);
76
+ }
77
+ catch (error) {
78
+ printResult(io, fail('race.pilot-gate.record', 'PILOT_GATE_WRITE_FAILED', getErrorMessage(error), { rid: options.rid }, ['The evidence file was left as it was']), options.json);
79
+ process.exitCode = 1;
80
+ }
81
+ }
@@ -35,6 +35,14 @@ export type RequestTransitionOptions = {
35
35
  forceConfirm?: boolean;
36
36
  json?: boolean;
37
37
  };
38
+ export type RequestRetagOptions = {
39
+ role: RequestArtifactRole;
40
+ type: RequestType;
41
+ project: string;
42
+ /** Required on this write verb — see the note in `request-retag-command.ts`. */
43
+ sessionId: string;
44
+ json?: boolean;
45
+ };
38
46
  export type RequestLintOptions = {
39
47
  role: RequestArtifactRole;
40
48
  project: string;
@@ -1,6 +1,7 @@
1
1
  import { registerRequestInitCommand } from './request-init-command.js';
2
2
  import { registerRequestListCommand } from './request-list-command.js';
3
3
  import { registerRequestShowCommand } from './request-show-command.js';
4
+ import { registerRequestRetagCommand } from './request-retag-command.js';
4
5
  import { registerRequestTransitionCommand } from './request-transition-command.js';
5
6
  import { registerRequestLintCommand } from './request-lint-command.js';
6
7
  import { registerRequestRepairStatusCommand } from './request-repair-status-command.js';
@@ -13,6 +14,7 @@ export function registerRequestCommands(program, io) {
13
14
  registerRequestInitCommand(request, io);
14
15
  registerRequestListCommand(request, io);
15
16
  registerRequestShowCommand(request, io);
17
+ registerRequestRetagCommand(request, io);
16
18
  registerRequestTransitionCommand(request, io);
17
19
  registerRequestLintCommand(request, io);
18
20
  registerRequestRepairStatusCommand(request, io);