peaks-loop 4.1.4 → 4.1.5

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 (240) hide show
  1. package/.claude-plugin/marketplace.json +7 -2
  2. package/CHANGELOG.md +112 -0
  3. package/README-en.md +1 -1
  4. package/README.md +1 -1
  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/code-commands.d.ts +6 -4
  9. package/dist/cli/commands/code-commands.js +6 -4
  10. package/dist/cli/commands/code-gate-command.d.ts +5 -5
  11. package/dist/cli/commands/code-gate-command.js +49 -9
  12. package/dist/cli/commands/code-mode-gate-plan-command.d.ts +1 -1
  13. package/dist/cli/commands/code-mode-gate-plan-command.js +2 -2
  14. package/dist/cli/commands/core/memory-extract-command.js +10 -5
  15. package/dist/cli/commands/dispatch-cli-invocation-check.d.ts +108 -0
  16. package/dist/cli/commands/dispatch-cli-invocation-check.js +87 -0
  17. package/dist/cli/commands/dispatch-cli-invocation-scan.d.ts +66 -0
  18. package/dist/cli/commands/dispatch-cli-invocation-scan.js +162 -0
  19. package/dist/cli/commands/dispatch-commands.js +12 -5
  20. package/dist/cli/commands/dispatch-preflight.js +46 -0
  21. package/dist/cli/commands/dispatch-prompt-composition.d.ts +6 -0
  22. package/dist/cli/commands/dispatch-prompt-composition.js +29 -7
  23. package/dist/cli/commands/doc-commands.js +1 -1
  24. package/dist/cli/commands/feedback-commands-helpers.js +1 -1
  25. package/dist/cli/commands/final-review-prepare-command.js +22 -1
  26. package/dist/cli/commands/gate-commands-enforce.js +3 -3
  27. package/dist/cli/commands/hook-handle.js +41 -20
  28. package/dist/cli/commands/lint-commands.js +3 -1
  29. package/dist/cli/commands/loop-eval-capture-index.js +2 -4
  30. package/dist/cli/commands/perf-audit-commands.js +15 -5
  31. package/dist/cli/commands/project-commands.js +9 -6
  32. package/dist/cli/commands/race-commands.d.ts +15 -0
  33. package/dist/cli/commands/race-commands.js +65 -0
  34. package/dist/cli/commands/race-pilot-gate-record-command.d.ts +3 -0
  35. package/dist/cli/commands/race-pilot-gate-record-command.js +81 -0
  36. package/dist/cli/commands/request-command-options.d.ts +8 -0
  37. package/dist/cli/commands/request-commands.js +2 -0
  38. package/dist/cli/commands/request-init-command.js +67 -12
  39. package/dist/cli/commands/request-retag-command.d.ts +3 -0
  40. package/dist/cli/commands/request-retag-command.js +50 -0
  41. package/dist/cli/commands/request-show-command.d.ts +8 -0
  42. package/dist/cli/commands/request-show-command.js +14 -1
  43. package/dist/cli/commands/request-transition-command.js +12 -4
  44. package/dist/cli/commands/request-transition-failures.d.ts +14 -0
  45. package/dist/cli/commands/request-transition-failures.js +45 -3
  46. package/dist/cli/commands/scan-scope-commands.js +2 -2
  47. package/dist/cli/commands/security-audit-commands.js +26 -6
  48. package/dist/cli/commands/worktree-lease-gc-command.js +1 -1
  49. package/dist/services/artifacts/artifact-contract-block.d.ts +53 -0
  50. package/dist/services/artifacts/artifact-contract-block.js +212 -0
  51. package/dist/services/artifacts/artifact-prerequisites.d.ts +27 -19
  52. package/dist/services/artifacts/artifact-prerequisites.js +63 -133
  53. package/dist/services/artifacts/artifact-templates.d.ts +1 -1
  54. package/dist/services/artifacts/artifact-templates.js +17 -10
  55. package/dist/services/artifacts/prerequisite-checks.d.ts +87 -0
  56. package/dist/services/artifacts/prerequisite-checks.js +198 -0
  57. package/dist/services/artifacts/prerequisite-transition-event.d.ts +20 -0
  58. package/dist/services/artifacts/prerequisite-transition-event.js +27 -0
  59. package/dist/services/artifacts/request-artifact-metadata.d.ts +31 -0
  60. package/dist/services/artifacts/request-artifact-metadata.js +44 -0
  61. package/dist/services/artifacts/request-artifact-service.d.ts +5 -0
  62. package/dist/services/artifacts/request-artifact-service.js +23 -51
  63. package/dist/services/artifacts/request-artifact-state-helpers.d.ts +12 -0
  64. package/dist/services/artifacts/request-artifact-state-helpers.js +28 -4
  65. package/dist/services/artifacts/request-retag-service.d.ts +68 -0
  66. package/dist/services/artifacts/request-retag-service.js +125 -0
  67. package/dist/services/artifacts/request-state-order.d.ts +38 -0
  68. package/dist/services/artifacts/request-state-order.js +99 -0
  69. package/dist/services/artifacts/request-type-demand.d.ts +44 -0
  70. package/dist/services/artifacts/request-type-demand.js +71 -0
  71. package/dist/services/audit/audit-goal-service.d.ts +7 -0
  72. package/dist/services/audit/enforcers/active-skill-resolver.d.ts +18 -0
  73. package/dist/services/audit/enforcers/active-skill-resolver.js +48 -1
  74. package/dist/services/audit/enforcers/code-ban.d.ts +11 -2
  75. package/dist/services/audit/enforcers/code-ban.js +21 -1
  76. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.d.ts +17 -0
  77. package/dist/services/audit/red-line-catalog-p2-a-bee-runtime.js +24 -7
  78. package/dist/services/audit-independent/handoff-missing-refusal.d.ts +26 -0
  79. package/dist/services/audit-independent/handoff-missing-refusal.js +109 -0
  80. package/dist/services/audit-independent/handoff-readers.d.ts +37 -0
  81. package/dist/services/audit-independent/handoff-readers.js +81 -0
  82. package/dist/services/audit-independent/index.d.ts +6 -1
  83. package/dist/services/audit-independent/index.js +6 -1
  84. package/dist/services/audit-independent/judged-declaration-build.d.ts +48 -0
  85. package/dist/services/audit-independent/judged-declaration-build.js +73 -0
  86. package/dist/services/audit-independent/judged-declaration-check.d.ts +79 -0
  87. package/dist/services/audit-independent/judged-declaration-check.js +155 -0
  88. package/dist/services/audit-independent/judged-declaration.d.ts +94 -0
  89. package/dist/services/audit-independent/judged-declaration.js +218 -0
  90. package/dist/services/audit-independent/perf-audit-service.js +12 -14
  91. package/dist/services/audit-independent/security-audit-artifact.d.ts +28 -0
  92. package/dist/services/audit-independent/security-audit-artifact.js +90 -0
  93. package/dist/services/audit-independent/security-audit-service.d.ts +6 -53
  94. package/dist/services/audit-independent/security-audit-service.js +34 -178
  95. package/dist/services/capability-guard-runner/contracts/J05.js +60 -14
  96. package/dist/services/codegraph/codegraph-index-integrity.js +2 -0
  97. package/dist/services/context/build-dispatch-system-prompt.d.ts +3 -3
  98. package/dist/services/context/build-dispatch-system-prompt.js +7 -7
  99. package/dist/services/context/collector.js +5 -1
  100. package/dist/services/dispatch/active-dispatch-index.d.ts +36 -0
  101. package/dist/services/dispatch/active-dispatch-index.js +118 -0
  102. package/dist/services/dispatch/batch-counter.js +1 -2
  103. package/dist/services/dispatch/dispatch-record-writer.d.ts +29 -16
  104. package/dist/services/dispatch/dispatch-record-writer.js +58 -100
  105. package/dist/services/dispatch/dispatch-sub-agent.js +1 -1
  106. package/dist/services/dispatch/karpathy-block.d.ts +55 -0
  107. package/dist/services/dispatch/karpathy-block.js +101 -0
  108. package/dist/services/dispatch/ledger-reaper.d.ts +80 -0
  109. package/dist/services/dispatch/ledger-reaper.js +131 -0
  110. package/dist/services/evidence/evidence-generator.js +15 -8
  111. package/dist/services/feedback/feedback-promotion-service.d.ts +8 -11
  112. package/dist/services/feedback/feedback-promotion-service.js +30 -35
  113. package/dist/services/feedback/promotion-artifact-json-evidence.d.ts +18 -0
  114. package/dist/services/feedback/promotion-artifact-missing.d.ts +22 -0
  115. package/dist/services/feedback/promotion-artifact-missing.js +63 -0
  116. package/dist/services/final-review/final-review-contract.d.ts +95 -4
  117. package/dist/services/final-review/final-review-contract.js +64 -0
  118. package/dist/services/final-review/final-review-delivery.d.ts +13 -0
  119. package/dist/services/final-review/final-review-delivery.js +26 -12
  120. package/dist/services/final-review/final-review-evidence-collect.js +8 -53
  121. package/dist/services/final-review/final-review-evidence-records.d.ts +21 -0
  122. package/dist/services/final-review/final-review-evidence-records.js +67 -0
  123. package/dist/services/final-review/final-review-evidence-sources.d.ts +22 -0
  124. package/dist/services/final-review/final-review-evidence-sources.js +28 -4
  125. package/dist/services/final-review/final-review-prompt.js +19 -6
  126. package/dist/services/final-review/final-review-runner.js +5 -0
  127. package/dist/services/final-review/final-review-service.d.ts +2 -2
  128. package/dist/services/final-review/index.d.ts +1 -1
  129. package/dist/services/final-review/pre-post-diff.d.ts +2 -75
  130. package/dist/services/final-review/pre-post-diff.js +60 -59
  131. package/dist/services/hooks/pre-tool-code-gate.d.ts +7 -1
  132. package/dist/services/hooks/pre-tool-code-gate.js +21 -2
  133. package/dist/services/hooks/worktree-authorization-gate.js +6 -31
  134. package/dist/services/hooks/worktree-refusal-messages.d.ts +74 -0
  135. package/dist/services/hooks/worktree-refusal-messages.js +102 -0
  136. package/dist/services/lint/eslint-runner-support.d.ts +1 -1
  137. package/dist/services/lint/eslint-runner-support.js +2 -1
  138. package/dist/services/lint/eslint-runner-types.d.ts +8 -0
  139. package/dist/services/lint/eslint-runner.js +17 -4
  140. package/dist/services/llm/anthropic-runner.js +24 -7
  141. package/dist/services/loop/loop-observability.d.ts +39 -0
  142. package/dist/services/loop/loop-observability.js +55 -0
  143. package/dist/services/loop/monotonic-guard.js +6 -9
  144. package/dist/services/loop/monotonic-runner.js +8 -7
  145. package/dist/services/loop/run-driver.js +18 -22
  146. package/dist/services/memory/project-memory-service/index/kind-dispatch.js +14 -1
  147. package/dist/services/memory/project-memory-service/index/project-memory-plan-exec.js +13 -2
  148. package/dist/services/memory/project-memory-service/index.d.ts +2 -2
  149. package/dist/services/memory/project-memory-service/index.js +1 -1
  150. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.d.ts +36 -0
  151. package/dist/services/memory/project-memory-service/parsers/frontmatter-parse.js +48 -2
  152. package/dist/services/memory/project-memory-service/parsers/markdown-pure.d.ts +23 -1
  153. package/dist/services/memory/project-memory-service/parsers/markdown-pure.js +37 -0
  154. package/dist/services/memory/project-memory-service/types.d.ts +32 -0
  155. package/dist/services/observability/observability-service.d.ts +7 -0
  156. package/dist/services/observability/observability-service.js +2 -1
  157. package/dist/services/prd/gate-evidence-derivation.d.ts +4 -3
  158. package/dist/services/prd/gate-evidence-derivation.js +4 -3
  159. package/dist/services/qa/bdd-test-style-verifier.js +22 -8
  160. package/dist/services/race/gate2-evaluator.d.ts +58 -0
  161. package/dist/services/race/gate2-evaluator.js +111 -0
  162. package/dist/services/race/gate2-policy.d.ts +17 -0
  163. package/dist/services/race/gate2-policy.js +31 -0
  164. package/dist/services/race/lane-phase.d.ts +19 -0
  165. package/dist/services/race/lane-phase.js +113 -0
  166. package/dist/services/race/pilot-gate-store.d.ts +67 -0
  167. package/dist/services/race/pilot-gate-store.js +227 -0
  168. package/dist/services/scan/file-size-baseline.d.ts +26 -0
  169. package/dist/services/scan/file-size-baseline.js +150 -0
  170. package/dist/services/scan/file-size-scan.d.ts +42 -3
  171. package/dist/services/scan/file-size-scan.js +58 -42
  172. package/dist/services/scan/type-sanity-service.js +13 -3
  173. package/dist/services/skill/resume-detector.js +3 -3
  174. package/dist/services/skills/hooks-codegate-superpowers.d.ts +5 -6
  175. package/dist/services/skills/hooks-codegate-superpowers.js +7 -8
  176. package/dist/services/skills/hooks-settings-service.d.ts +1 -1
  177. package/dist/services/skills/hooks-settings-service.js +1 -1
  178. package/dist/services/skills/presence-lease-order.d.ts +13 -0
  179. package/dist/services/skills/presence-lease-order.js +24 -0
  180. package/dist/services/skills/skill-conformance-service.js +1 -0
  181. package/dist/services/skills/skill-statusline-service.js +4 -7
  182. package/dist/services/slice/slice-check-service.js +8 -8
  183. package/dist/services/workflow/pipeline-verify-gate-support.js +2 -1
  184. package/dist/services/workflow/pipeline-verify-service.js +1 -1
  185. package/dist/services/workflow/workflow-skip-service.d.ts +0 -20
  186. package/dist/services/workflow/workflow-skip-service.js +3 -4
  187. package/dist/services/workspace/claude-settings-retirements.d.ts +54 -0
  188. package/dist/services/workspace/claude-settings-retirements.js +112 -0
  189. package/dist/services/workspace/claude-settings-template-merge.d.ts +35 -15
  190. package/dist/services/workspace/claude-settings-template-merge.js +33 -53
  191. package/dist/services/workspace/claude-settings-template.d.ts +62 -12
  192. package/dist/services/workspace/claude-settings-template.js +58 -58
  193. package/dist/services/workspace/migrate-1-4-1-service.js +3 -0
  194. package/dist/services/workspace/reconcile-service.js +0 -1
  195. package/dist/shared/incrementing-number.d.ts +10 -0
  196. package/dist/shared/incrementing-number.js +27 -0
  197. package/package.json +5 -5
  198. package/skills/bee/peaks-perf-audit/SKILL.md +1 -1
  199. package/skills/bee/peaks-prd/SKILL.md +1 -1
  200. package/skills/bee/peaks-qa/SKILL.md +1 -1
  201. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  202. package/skills/bee/peaks-qa/references/qa-transition-gates.md +1 -1
  203. package/skills/bee/peaks-rd/SKILL.md +2 -2
  204. package/skills/bee/peaks-rd/references/rd-fanout-contracts.md +1 -1
  205. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +8 -4
  206. package/skills/bee/peaks-rd/references/rd-transition-gates.md +3 -3
  207. package/skills/bee/peaks-rd/references/v2-12-fanout-collapse.md +2 -2
  208. package/skills/bee/peaks-rd/references/writing-handoff-frontmatter.md +1 -1
  209. package/skills/bee/peaks-reviewer/SKILL.md +1 -1
  210. package/skills/bee/peaks-sc/SKILL.md +1 -1
  211. package/skills/bee/peaks-security-audit/SKILL.md +10 -2
  212. package/skills/bee/peaks-txt/SKILL.md +4 -3
  213. package/skills/bee/peaks-ui/SKILL.md +3 -3
  214. package/skills/peaks-audit/SKILL.md +29 -1
  215. package/skills/peaks-code/SKILL.md +5 -2
  216. package/skills/peaks-code/references/fast-lane-norm.md +42 -0
  217. package/skills/peaks-code/references/fast-mode.md +3 -2
  218. package/skills/peaks-code/references/local-artifact-workspace.md +3 -3
  219. package/skills/peaks-code/references/micro-cycle.md +3 -3
  220. package/skills/peaks-code/references/resume-detection.md +1 -1
  221. package/skills/peaks-code/references/runbook.md +12 -6
  222. package/skills/peaks-code/references/step-11-memory-sediment.md +4 -0
  223. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  224. package/skills/peaks-code/references/swarm-dispatch-contract.md +40 -16
  225. package/skills/peaks-code/references/workflow-gates-and-types.md +6 -6
  226. package/skills/peaks-code/references/worktree-governance.md +4 -4
  227. package/skills/peaks-content/SKILL.md +1 -1
  228. package/skills/peaks-doctor/SKILL.md +1 -1
  229. package/skills/peaks-final-review/SKILL.md +31 -11
  230. package/skills/peaks-ide/SKILL.md +1 -1
  231. package/skills/peaks-issue-fix-orchestrator/SKILL.md +1 -1
  232. package/skills/peaks-race-code/SKILL.md +185 -0
  233. package/skills/peaks-resume/SKILL.md +1 -1
  234. package/skills/peaks-slice-decompose/SKILL.md +1 -1
  235. package/skills/peaks-solo/SKILL.md +1 -1
  236. package/skills/peaks-sop/SKILL.md +1 -1
  237. package/skills/peaks-status/SKILL.md +1 -1
  238. package/skills/peaks-test/SKILL.md +7 -4
  239. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.d.ts +0 -23
  240. package/dist/services/audit/enforcers/lint-peaks-skill-runtime.js +0 -64
@@ -30,11 +30,13 @@
30
30
  * - Output: `.peaks/_runtime/<sid>/audit/security-<rid>.md`
31
31
  * - Schema: `.peaks/project-scan/audit-output-schema.md` (schemaVersion: 1)
32
32
  */
33
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
34
- import { join, resolve, isAbsolute } from 'node:path';
35
- import { createHash } from 'node:crypto';
36
- import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
33
+ import { existsSync } from 'node:fs';
34
+ import { join } from 'node:path';
37
35
  import { resolveHandoffPath } from '../prd/handoff-service.js';
36
+ import { handoffMissingRefusal } from './handoff-missing-refusal.js';
37
+ import { renderSecurityAuditArtifact, writeSecurityAuditArtifact } from './security-audit-artifact.js';
38
+ import { declarationMissingDetect, renderJudgedDeclaration } from './judged-declaration.js';
39
+ import { buildJudgedDeclarationFor } from './judged-declaration-build.js';
38
40
  /**
39
41
  * Validate a raw value as a SecurityAuditEnvelope. Mirrors the
40
42
  * `isEccEnvelope` strict-shape pattern.
@@ -75,70 +77,6 @@ export function isSecurityAuditEnvelope(value) {
75
77
  }
76
78
  return true;
77
79
  }
78
- /**
79
- * Read the peaks-prd handoff frontmatter + body, verify sha256 matches
80
- * the body. Returns null on missing file or sha256 mismatch; otherwise
81
- * returns the parsed frontmatter + body string.
82
- *
83
- * Defensive: we read frontmatter via a 1-line regex match, not via
84
- * a YAML parser. The handoff service (`src/services/prd/handoff-service.ts`)
85
- * is the canonical writer; we only consume its output here.
86
- */
87
- export function readAndVerifyHandoff(handoffPath, projectRoot) {
88
- if (!handoffPath || !isAbsolute(handoffPath)) {
89
- const absolutePath = resolve(projectRoot, handoffPath);
90
- if (!existsSync(absolutePath))
91
- return null;
92
- return readAndVerifyHandoff(absolutePath, projectRoot);
93
- }
94
- if (!existsSync(handoffPath))
95
- return null;
96
- let raw;
97
- try {
98
- raw = readFileSync(handoffPath, 'utf8');
99
- }
100
- catch {
101
- // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
102
- return null;
103
- }
104
- // Frontmatter pattern: `---` line, then key: value pairs, then `---` line.
105
- const match = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
106
- if (match === null)
107
- return null;
108
- const frontmatterRaw = match[1];
109
- const body = match[2];
110
- const sha256Match = frontmatterRaw.match(/^sha256:\s*([a-f0-9]{64})\s*$/m);
111
- const schemaVersionMatch = frontmatterRaw.match(/^schemaVersion:\s*(\d+)\s*$/m);
112
- if (sha256Match === null || schemaVersionMatch === null)
113
- return null;
114
- const sha256Expected = sha256Match[1];
115
- const schemaVersion = parseInt(schemaVersionMatch[1], 10);
116
- const sha256Actual = createHash('sha256').update(body, 'utf8').digest('hex');
117
- if (sha256Expected !== sha256Actual)
118
- return null;
119
- return {
120
- frontmatter: { sha256: sha256Expected, schemaVersion },
121
- body
122
- };
123
- }
124
- /**
125
- * Read the project-level security-template.md. Returns the body
126
- * string (with frontmatter stripped) or null if the file is absent.
127
- * Does NOT validate the template content; the parent LLM validates
128
- * by reading.
129
- */
130
- export function readSecurityTemplate(projectRoot) {
131
- const templatePath = join(projectRoot, '.peaks', 'project-scan', 'security-template.md');
132
- if (!existsSync(templatePath))
133
- return null;
134
- try {
135
- return readFileSync(templatePath, 'utf8');
136
- }
137
- catch {
138
- // TODO(g2): legacy silent catch — grace: 1 minor release (v2.14.0)
139
- return null;
140
- }
141
- }
142
80
  /**
143
81
  * 5-state detector. The parent skill inspects the state and either
144
82
  * proceeds (when `ready`) or records a degradation note and falls
@@ -159,22 +97,20 @@ export function detectSecurityAudit(input) {
159
97
  const templatePath = join(input.projectRoot, '.peaks', 'project-scan', 'security-template.md');
160
98
  const templatePresent = existsSync(templatePath);
161
99
  if (!handoffPresent) {
100
+ const refusal = handoffMissingRefusal({
101
+ role: 'security',
102
+ projectRoot: input.projectRoot,
103
+ sessionId: input.sessionId,
104
+ ...(input.requestId !== undefined ? { requestId: input.requestId } : {}),
105
+ // Measured, not assumed: `detect` supplies no envelope at all.
106
+ envelopeValidated: input.envelope !== undefined && isSecurityAuditEnvelope(input.envelope)
107
+ });
162
108
  return {
163
109
  state: 'handoff-missing',
164
110
  handoffPresent: false,
165
111
  templatePresent,
166
- warnings: [
167
- `peaks-prd handoff not found under ${join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'prd')}`,
168
- ...(input.requestId === undefined
169
- ? [
170
- "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`."
171
- ]
172
- : [])
173
- ],
174
- nextActions: [
175
- 'Run peaks-prd handoff init to produce a sha256-locked handoff before running peaks security-audit.',
176
- 'Until the handoff exists, peaks-security-audit cannot start (gate fail).'
177
- ]
112
+ warnings: refusal.warnings,
113
+ nextActions: refusal.nextActions
178
114
  };
179
115
  }
180
116
  if (!templatePresent) {
@@ -225,90 +161,6 @@ export function detectSecurityAudit(input) {
225
161
  nextActions
226
162
  };
227
163
  }
228
- /**
229
- * Render a SecurityAuditEnvelope to the canonical audit artifact body
230
- * (markdown). Mirrors `adaptEccEnvelopeToRdCodeReview` in ecc-bridge.ts:
231
- * produce a markdown body with all required sections, ready to write
232
- * to `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
233
- */
234
- export function renderSecurityAuditArtifact(env, opts) {
235
- const counts = {};
236
- for (const v of env.violations) {
237
- counts[v.severity] = (counts[v.severity] ?? 0) + 1;
238
- }
239
- const criticalCount = counts['CRITICAL'] ?? 0;
240
- const findingsBullets = env.violations.length === 0
241
- ? '- (none)'
242
- : env.violations
243
- .map((v) => `- [${v.severity}] ${v.dimension} @ ${v.file}:${v.line} — ${v.hint}`)
244
- .join('\n');
245
- const requiredFixes = buildRequiredFixes(env);
246
- const body = [
247
- '## Summary',
248
- '',
249
- env.summary,
250
- '',
251
- '## Threat model coverage',
252
- '',
253
- `audited at: ${opts.generatedAt}`,
254
- `verdict: ${env.verdict}`,
255
- `handoffHash: ${opts.handoffHash}`,
256
- '',
257
- '## Findings',
258
- '',
259
- findingsBullets,
260
- '',
261
- requiredFixes,
262
- '## Verdict',
263
- '',
264
- `verdict: ${env.verdict}`,
265
- `CRITICAL: ${criticalCount}`,
266
- ''
267
- ]
268
- .filter((s) => s.length > 0)
269
- .join('\n');
270
- return {
271
- body,
272
- violationsCount: env.violations.length,
273
- verdict: env.verdict
274
- };
275
- }
276
- function buildRequiredFixes(env) {
277
- const requiredFixes = env.violations.length === 0
278
- ? ''
279
- : [
280
- '## Required fixes',
281
- '',
282
- ...env.violations.map((v) => `- [${v.severity}] ${v.file}:${v.line} — ${v.hint}`),
283
- ''
284
- ].join('\n');
285
- return requiredFixes;
286
- }
287
- /**
288
- * Write the rendered audit artifact to
289
- * `.peaks/_runtime/<sid>/audit/security-<rid>.md`.
290
- *
291
- * Atomic write (tmp + rename) to avoid partial writes on crash.
292
- * Returns the absolute path on success.
293
- */
294
- export function writeSecurityAuditArtifact(projectRoot, sessionId, rid, body) {
295
- // The rid is a filename below, and the write is tmp+rename, so an
296
- // unvalidated rid can OVERWRITE an arbitrary `.md` rather than merely create
297
- // one. Guarded here (not only at the CLI boundary) so no caller can skip it.
298
- if (!REQUEST_ID_PATTERN.test(rid)) {
299
- throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
300
- }
301
- const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
302
- mkdirSync(targetDir, { recursive: true });
303
- const targetPath = join(targetDir, `security-${rid}.md`);
304
- // tmp + rename for atomicity
305
- const tmpPath = `${targetPath}.tmp`;
306
- writeFileSync(tmpPath, body, 'utf8');
307
- // Sync rename: on Windows, fs.renameSync overwrites if target exists (Node 22+)
308
- const { renameSync } = require('node:fs');
309
- renameSync(tmpPath, targetPath);
310
- return targetPath;
311
- }
312
164
  /**
313
165
  * Convenience: run `detectSecurityAudit` + `renderSecurityAuditArtifact`
314
166
  * + `writeSecurityAuditArtifact` in one call.
@@ -324,24 +176,28 @@ export function runSecurityAudit(input) {
324
176
  ...(input.dispatchError !== undefined ? { dispatchError: input.dispatchError } : {}),
325
177
  ...(input.envelope !== undefined ? { envelope: input.envelope } : {})
326
178
  });
327
- if (detect.state !== 'ready' || input.envelope === undefined) {
328
- return { detect, artifactPath: null, violationsCount: 0, verdict: null };
179
+ // The stamp is built inside the producer, before anything is written, so a
180
+ // caller that reaches the service alone still cannot leave an unstamped
181
+ // artifact behind. Folding its failure into the probe's own verdict keeps the
182
+ // refusal on this function's single early-return rather than a second one.
183
+ const built = buildJudgedDeclarationFor(input);
184
+ // A probe that is already refusing keeps its own diagnosis: the declaration
185
+ // is what this run would write, not what stopped it earlier.
186
+ const probe = built.ok || detect.state !== 'ready' ? detect : declarationMissingDetect(detect, built);
187
+ if (probe.state !== 'ready' || input.envelope === undefined || !built.ok) {
188
+ return { detect: probe, artifactPath: null, violationsCount: 0, verdict: null };
329
189
  }
330
- // detect.state === 'ready' implies input.envelope passed isSecurityAuditEnvelope.
190
+ // probe.state === 'ready' implies input.envelope passed isSecurityAuditEnvelope.
331
191
  const env = input.envelope;
332
- const handoffPath = resolveHandoffPath({
333
- projectRoot: input.projectRoot,
334
- sessionId: input.sessionId,
335
- requestId: input.rid
336
- });
337
- const verified = handoffPath === null ? null : readAndVerifyHandoff(handoffPath, input.projectRoot);
338
- const handoffHash = verified?.frontmatter.sha256 ?? 'unknown';
339
- const rendered = renderSecurityAuditArtifact(env, {
192
+ const renderOpts = {
340
193
  rid: input.rid,
341
- handoffHash,
194
+ handoffHash: built.handoffHash,
342
195
  generatedAt: input.generatedAt
343
- });
344
- const artifactPath = writeSecurityAuditArtifact(input.projectRoot, input.sessionId, input.rid, rendered.body);
196
+ };
197
+ const rendered = renderSecurityAuditArtifact(env, renderOpts);
198
+ const declared = built.declaration;
199
+ const body = `${rendered.body}\n${renderJudgedDeclaration(declared)}`;
200
+ const artifactPath = writeSecurityAuditArtifact(input.projectRoot, input.sessionId, input.rid, body);
345
201
  return {
346
202
  detect,
347
203
  artifactPath,
@@ -12,27 +12,49 @@ const FOUR_DIMENSIONS = [
12
12
  ];
13
13
  const FIFTH_DIMENSION = 'capability-consistency';
14
14
  /**
15
- * One oversized, omitted source that backs `dimension`. `omitted` + over-cap +
16
- * zero delivered bytes is the structural case: nothing can ever deliver it.
15
+ * An oversized source that backs `dimension`, in whichever of the two states
16
+ * the allocator can leave it.
17
+ *
18
+ * F3 (review 2026-10-13) — this used to build the omitted shape behind an
19
+ * `as unknown as CollectedEvidence` cast that omitted `excerpt`, so a `found`
20
+ * over-cap source built here would have been reported as "no deliverable
21
+ * source" while a cap-sized head of it had been inlined. The cast is gone and
22
+ * `excerpt` is declared, so the state the report distinguishes cannot be
23
+ * expressed wrongly from this helper.
17
24
  */
18
- function undeliverableSource(dimension, totalBytes) {
25
+ function overCapSource(dimension, totalBytes, inlined) {
19
26
  return {
20
27
  source: {
21
28
  key: `k-${dimension}`,
22
29
  label: dimension,
23
30
  segments: [`${dimension}.md`],
31
+ // The fixture deliberately fabricates dimension names (the fifth one is
32
+ // not a `DimensionKind`), so this ONE field is asserted, not inferred —
33
+ // the rest of the record is fully typed.
24
34
  supports: [dimension],
25
35
  delivery: { kind: 'whole' }
26
36
  },
27
37
  relativePath: `${dimension}.md`,
28
38
  absolutePath: `/nonexistent/${dimension}.md`,
29
- status: 'omitted',
39
+ status: inlined ? 'found' : 'omitted',
30
40
  totalBytes,
31
- includedBytes: 0,
32
- content: '',
33
- reason: 'over-cap'
41
+ includedBytes: inlined ? MAX_EVIDENCE_BYTES_PER_FILE : 0,
42
+ excerpt: inlined,
43
+ content: inlined ? 'x'.repeat(MAX_EVIDENCE_BYTES_PER_FILE) : '',
44
+ reason: inlined ? '' : 'over-cap'
34
45
  };
35
46
  }
47
+ /**
48
+ * One oversized, omitted source that backs `dimension`. `omitted` + over-cap +
49
+ * zero delivered bytes is the structural case: nothing can ever deliver it.
50
+ */
51
+ function undeliverableSource(dimension, totalBytes) {
52
+ return overCapSource(dimension, totalBytes, false);
53
+ }
54
+ /** `dimension=excerpt|silent` per entry — what the report says ARRIVED. */
55
+ function excerptState(report) {
56
+ return report.map((r) => `${r.dimension}=${r.excerptDelivered ? 'excerpt' : 'silent'}`).join(',');
57
+ }
36
58
  function reviewJson(dimensions) {
37
59
  return JSON.stringify({
38
60
  rid: 'J05-fixture',
@@ -112,22 +134,46 @@ function probeOutputBudget() {
112
134
  }
113
135
  return { floor, ceiling, badOverrideThrows };
114
136
  }
137
+ /**
138
+ * The over-cap evidence states, as probes.
139
+ *
140
+ * F3 (review 2026-10-13) is the pair that matters: the SAME oversized source,
141
+ * once inlined and once not, has to be reported as two DIFFERENT things. Both
142
+ * are driven here so the report cannot answer "nothing arrived" about a source
143
+ * whose cap-sized head is in the reviewer's prompt.
144
+ *
145
+ * Extracted from `runJ05Contract` so that function stays inside the
146
+ * function-length rule.
147
+ */
148
+ function overCapEvidenceProbes() {
149
+ const reported = undeliverableDimensions(FOUR_DIMENSIONS.map((d) => undeliverableSource(d, MAX_EVIDENCE_BYTES_PER_FILE + 1000)));
150
+ const dimensions = reported.map((r) => r.dimension);
151
+ const fifthOnly = undeliverableDimensions([
152
+ undeliverableSource(FIFTH_DIMENSION, MAX_EVIDENCE_BYTES_PER_FILE + 1000)
153
+ ]);
154
+ const excerptOnly = undeliverableDimensions([
155
+ overCapSource(FOUR_DIMENSIONS[0], MAX_EVIDENCE_BYTES_PER_FILE + 1000, true)
156
+ ]);
157
+ return [
158
+ probe(dimensions.length === FOUR_DIMENSIONS.length &&
159
+ FOUR_DIMENSIONS.every((d) => dimensions.includes(d)), `the canonical dimension set is exactly the four baseline dimensions (reported: ${dimensions.join(',') || 'none'})`),
160
+ probe(fifthOnly.length === 0, `the fifth dimension is not part of the required set (reported: ${fifthOnly.length})`),
161
+ probe(excerptOnly.length === 1 &&
162
+ excerptOnly[0]?.excerptDelivered === true &&
163
+ excerptOnly[0]?.sources[0]?.excerptBytes === MAX_EVIDENCE_BYTES_PER_FILE, `an over-cap source that WAS inlined is reported as an excerpt, not as nothing arrived (reported: ${excerptState(excerptOnly)})`),
164
+ probe(reported.length === FOUR_DIMENSIONS.length && reported.every((r) => !r.excerptDelivered), `an over-cap source that was NOT inlined is reported as nothing arrived (reported: ${excerptState(reported)})`)
165
+ ];
166
+ }
115
167
  export async function runJ05Contract(ctx) {
116
168
  const row = requireBaselineRow(ctx);
117
169
  const missing = missingSourceFiles(ctx, row);
118
170
  const prepared = await probePrepareFinalReview();
119
- const oversized = FOUR_DIMENSIONS.map((d) => undeliverableSource(d, MAX_EVIDENCE_BYTES_PER_FILE + 1000));
120
- const reported = undeliverableDimensions(oversized).map((r) => r.dimension);
121
- const fifthOnly = undeliverableDimensions([
122
- undeliverableSource(FIFTH_DIMENSION, MAX_EVIDENCE_BYTES_PER_FILE + 1000)
123
- ]);
124
171
  const { floor, ceiling, badOverrideThrows } = probeOutputBudget();
125
172
  const result = combineProbes([
126
173
  probe(missing.length === 0, `baseline sourceFiles present (${row.sourceFiles.length})`),
127
174
  probe(prepared.rejected, `a three-dimension review is refused (${prepared.detail})`),
128
175
  probe(prepared.accepted, `a four-dimension review is accepted (${prepared.detail})`),
129
- probe(reported.length === 4 && FOUR_DIMENSIONS.every((d) => reported.includes(d)), `the canonical dimension set is exactly the four baseline dimensions (reported: ${reported.join(',') || 'none'})`),
130
- probe(fifthOnly.length === 0, `the fifth dimension is not part of the required set (reported: ${fifthOnly.length})`),
176
+ ...overCapEvidenceProbes(),
131
177
  probe(MAX_EVIDENCE_BYTES_PER_FILE === 10240, `per-file evidence cap divides the total by four (${String(MAX_EVIDENCE_BYTES_PER_FILE)})`),
132
178
  probe(floor === 15288 && ceiling === 32000, `output budget is clamped on both ends (${String(floor)} / ${String(ceiling)})`),
133
179
  probe(badOverrideThrows, 'a non-integer budget override throws instead of falling back silently')
@@ -249,6 +249,8 @@ let cachedUpstreamGrammars = null;
249
249
  */
250
250
  function loadUpstreamGrammars() {
251
251
  if (cachedUpstreamGrammars === null) {
252
+ // Deliberate, and not a missed ESM conversion: `grammarsPath` is computed
253
+ // at runtime, which no static `import` can express — see the ESM guard.
252
254
  const require = createRequire(import.meta.url);
253
255
  const { moduleDir } = resolveCodegraphUpstreamLayout();
254
256
  const grammarsPath = join(moduleDir, 'extraction', 'grammars.js');
@@ -95,10 +95,10 @@ export interface DispatchPromptInput {
95
95
  * reuse the task body verbatim).
96
96
  * trivially testable.
97
97
  *
98
- * fallback path is `peaks worktree auth grant --rid <id> --reason <text>
99
- * --ttl <5m>` (already shipped). Update the prose once `spawn` lands.
98
+ * fallback path is the command the auth-grant CLI declares:
99
+ * `peaks worktree auth grant --operation <op> --reason <text>`.
100
100
  */
101
- export declare const L1_WORKTREE_GOVERNANCE_BLOCK = "## Superpowers chain refusal (L1 worktree governance \u2014 locked 2026-07-29)\n\nYou MUST NOT follow the superpowers chain for worktree decisions:\n\n- superpowers:brainstorming \u2192 superpowers:writing-plans \u2192\n superpowers:subagent-driven-development \u2192 superpowers:using-git-worktrees\n\nThat chain ends with `git worktree add` (superpowers:using-git-worktrees SKILL.md line 96), which bypasses peaks-loop's L2 hook gate and L3 IDE `permissions.deny`. L3 denial is NOT sufficient \u2014 by then the chain has already taught raw `git worktree add`.\n\nFor worktree operations, use ONLY:\n\n- `peaks worktree spawn --rid <rid> --ttl <duration> --purpose <text>` (after rid-L2-extended ships)\n- until then: `peaks worktree auth grant --rid <id> --reason <text> --ttl <5m>`\n\nSuperpowers skills remain REFERENCE material for brainstorming / planning techniques, but MUST NOT be used as a workflow. peaks-rd's own PRD/RD artifacts (`.peaks/_runtime/<sessionId>/rd/requests/<rid>.md`) are authoritative.\n\nIf the upstream superpowers chain suggests raw `git worktree add`:\n\n1. STOP\n2. Re-author the plan as a peaks-rd artifact\n3. Continue with `peaks worktree spawn` (or the auth-grant fallback)\n";
101
+ export declare const L1_WORKTREE_GOVERNANCE_BLOCK = "## Superpowers chain refusal (L1 worktree governance \u2014 locked 2026-07-29)\n\nYou MUST NOT follow the superpowers chain for worktree decisions:\n\n- superpowers:brainstorming \u2192 superpowers:writing-plans \u2192\n superpowers:subagent-driven-development \u2192 superpowers:using-git-worktrees\n\nThat chain ends with `git worktree add` (superpowers:using-git-worktrees SKILL.md line 96), which bypasses peaks-loop's L2 hook gate and L3 IDE `permissions.deny`. L3 denial is NOT sufficient \u2014 by then the chain has already taught raw `git worktree add`.\n\nFor worktree operations, use ONLY:\n\n- `peaks worktree spawn --rid <rid> --role <role> --purpose <text>` (after rid-L2-extended ships)\n- until then: `peaks worktree auth grant --operation <op> --reason <text>` (`<op>`, e.g. `git-worktree` | `agent-isolation-worktree`)\n\nSuperpowers skills remain REFERENCE material for brainstorming / planning techniques, but MUST NOT be used as a workflow. peaks-rd's own PRD/RD artifacts (`.peaks/_runtime/<sessionId>/rd/requests/<rid>.md`) are authoritative.\n\nIf the upstream superpowers chain suggests raw `git worktree add`:\n\n1. STOP\n2. Re-author the plan as a peaks-rd artifact\n3. Continue with the `spawn` command above (or the auth-grant fallback)\n";
102
102
  /**
103
103
  * system prompt gains three lifecycle rules. The sub-agent must:
104
104
  *
@@ -16,8 +16,8 @@ import { resolveCodegraphBlock } from './codegraph-unavailable-block.js';
16
16
  * reuse the task body verbatim).
17
17
  * trivially testable.
18
18
  *
19
- * fallback path is `peaks worktree auth grant --rid <id> --reason <text>
20
- * --ttl <5m>` (already shipped). Update the prose once `spawn` lands.
19
+ * fallback path is the command the auth-grant CLI declares:
20
+ * `peaks worktree auth grant --operation <op> --reason <text>`.
21
21
  */
22
22
  export const L1_WORKTREE_GOVERNANCE_BLOCK = `## Superpowers chain refusal (L1 worktree governance — locked 2026-07-29)
23
23
 
@@ -30,8 +30,8 @@ That chain ends with \`git worktree add\` (superpowers:using-git-worktrees SKILL
30
30
 
31
31
  For worktree operations, use ONLY:
32
32
 
33
- - \`peaks worktree spawn --rid <rid> --ttl <duration> --purpose <text>\` (after rid-L2-extended ships)
34
- - until then: \`peaks worktree auth grant --rid <id> --reason <text> --ttl <5m>\`
33
+ - \`peaks worktree spawn --rid <rid> --role <role> --purpose <text>\` (after rid-L2-extended ships)
34
+ - until then: \`peaks worktree auth grant --operation <op> --reason <text>\` (\`<op>\`, e.g. \`git-worktree\` | \`agent-isolation-worktree\`)
35
35
 
36
36
  Superpowers skills remain REFERENCE material for brainstorming / planning techniques, but MUST NOT be used as a workflow. peaks-rd's own PRD/RD artifacts (\`.peaks/_runtime/<sessionId>/rd/requests/<rid>.md\`) are authoritative.
37
37
 
@@ -39,7 +39,7 @@ If the upstream superpowers chain suggests raw \`git worktree add\`:
39
39
 
40
40
  1. STOP
41
41
  2. Re-author the plan as a peaks-rd artifact
42
- 3. Continue with \`peaks worktree spawn\` (or the auth-grant fallback)
42
+ 3. Continue with the \`spawn\` command above (or the auth-grant fallback)
43
43
  `;
44
44
  /**
45
45
  * system prompt gains three lifecycle rules. The sub-agent must:
@@ -300,8 +300,8 @@ export const BINDING_RULE_TOKENS = [
300
300
  'MUST NOT follow the superpowers chain',
301
301
  'superpowers:using-git-worktrees',
302
302
  '`git worktree add`',
303
- '`peaks worktree spawn --rid <rid> --ttl <duration> --purpose <text>`',
304
- '`peaks worktree auth grant --rid <id> --reason <text> --ttl <5m>`',
303
+ '`peaks worktree spawn --rid <rid> --role <role> --purpose <text>`',
304
+ '`peaks worktree auth grant --operation <op> --reason <text>`',
305
305
  'MUST NOT be used as a workflow',
306
306
  'STOP',
307
307
  'Re-author the plan as a peaks-rd artifact',
@@ -45,7 +45,11 @@ async function scanFiles(root, exclude) {
45
45
  const s = await stat(full);
46
46
  out.push({
47
47
  path: rel,
48
- kind: classifyKind(relative(root, full)),
48
+ // `rel`, not a second `relative()` call: the raw value is
49
+ // `\`-separated on win32 and `classifyKind` tests for `/__tests__/`,
50
+ // so the nested-test branch could never match on the platform it was
51
+ // written on. The normalised value is the one computed above.
52
+ kind: classifyKind(rel),
49
53
  lines: 0, // computed lazily; full line count is expensive
50
54
  hash: '' // computed lazily via content-hash-cache-pattern
51
55
  });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Active-dispatches index. Per-session JSON file at
3
+ * `.peaks/_sub_agents/<sid>/active-dispatches.json`. Map<recordPath,
4
+ * ActiveDispatchEntry>. Updated on dispatch + completion.
5
+ */
6
+ export interface ActiveDispatchEntry {
7
+ readonly recordPath: string;
8
+ readonly requestId: string;
9
+ readonly role: string;
10
+ readonly batchId: string;
11
+ readonly createdAt: string;
12
+ readonly status: 'queued' | 'running' | 'finalizing' | 'done' | 'failed' | 'cancelled' | 'stale' | 'no-execution' | 'never-started' | 'unreadable';
13
+ }
14
+ export declare function activeDispatchIndexPath(projectRoot: string, sessionId: string): string;
15
+ export declare function registerActiveDispatch(input: {
16
+ projectRoot: string;
17
+ sessionId: string;
18
+ recordPath: string;
19
+ requestId: string;
20
+ role: string;
21
+ batchId: string;
22
+ now: () => Date;
23
+ }): void;
24
+ export declare function unregisterActiveDispatch(input: {
25
+ projectRoot: string;
26
+ sessionId: string;
27
+ recordPath: string;
28
+ status: ActiveDispatchEntry['status'];
29
+ }): void;
30
+ /**
31
+ * for a session. Returns the current map<recordPath, entry>. Used
32
+ * by the LLM-side runner to discover in-flight records on restart.
33
+ * Returns an empty map when the index file is missing or corrupt
34
+ * (the on-disk records directory is the next fallback).
35
+ */
36
+ export declare function readActiveDispatchIndex(projectRoot: string, sessionId: string): Record<string, ActiveDispatchEntry>;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The per-session active-dispatches index
3
+ * (`.peaks/_sub_agents/<sid>/active-dispatches.json`): its path, its
4
+ * `Map<recordPath, ActiveDispatchEntry>` shape, and its register / unregister /
5
+ * read operations. The POLICY that bounds it lives in `./ledger-reaper.ts`.
6
+ *
7
+ * Split out of `./dispatch-record-writer.ts`, which was already over its
8
+ * file-size cap: the writer keeps the on-disk RECORD format, this module owns
9
+ * the INDEX — the hint the LLM-side runner and the status line read
10
+ * (`readActiveLeaf` in `src/services/skills/skill-statusline-model.ts`). The
11
+ * moved functions are byte-identical to their previous bodies apart from the
12
+ * terminal-status chain, which became a lookup set; `dispatch-record-writer.ts`
13
+ * re-exports the two public names so no importer changed.
14
+ */
15
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
16
+ import { dirname, resolve } from 'node:path';
17
+ export function activeDispatchIndexPath(projectRoot, sessionId) {
18
+ return resolve(projectRoot, '.peaks', '_sub_agents', sessionId, 'active-dispatches.json');
19
+ }
20
+ /**
21
+ * Read the index file into a plain map. A missing or corrupt file yields the
22
+ * empty map: the on-disk record is the source of truth and a corrupt index is
23
+ * rebuilt from the records rather than trusted.
24
+ */
25
+ function readIndexMap(indexPath) {
26
+ const index = {};
27
+ if (!existsSync(indexPath))
28
+ return index;
29
+ try {
30
+ const raw = readFileSync(indexPath, 'utf8');
31
+ const parsed = JSON.parse(raw);
32
+ if (typeof parsed === 'object' && parsed !== null) {
33
+ for (const [k, v] of Object.entries(parsed)) {
34
+ if (typeof v === 'object' && v !== null && 'recordPath' in v) {
35
+ index[k] = v;
36
+ }
37
+ }
38
+ }
39
+ }
40
+ catch (error) {
41
+ // Rebuilt from the empty map. `error` is held so the block is not an empty
42
+ // catch; the reason is that a corrupt index is not a fact worth reporting,
43
+ // only a reason to re-read the records.
44
+ void error;
45
+ }
46
+ return index;
47
+ }
48
+ export function registerActiveDispatch(input) {
49
+ const indexPath = activeDispatchIndexPath(input.projectRoot, input.sessionId);
50
+ const dir = dirname(indexPath);
51
+ if (!existsSync(dir)) {
52
+ mkdirSync(dir, { recursive: true });
53
+ }
54
+ const index = readIndexMap(indexPath);
55
+ index[input.recordPath] = {
56
+ recordPath: input.recordPath,
57
+ requestId: input.requestId,
58
+ role: input.role,
59
+ batchId: input.batchId,
60
+ createdAt: input.now().toISOString(),
61
+ status: 'queued'
62
+ };
63
+ const tmp = `${indexPath}.tmp-${process.pid}-${Date.now()}`;
64
+ writeFileSync(tmp, JSON.stringify(index, null, 2) + '\n', 'utf8');
65
+ renameSync(tmp, indexPath);
66
+ }
67
+ /**
68
+ * Statuses that mean the dispatch is over. The startup-timeout service writes
69
+ * the last two as terminal markers, and the finalize CLI writes the rest;
70
+ * unregister must remove the row on all of them.
71
+ *
72
+ * A set rather than a six-way `||` chain: the chain cost the function five
73
+ * branches for a lookup that is data, and pushed its complexity over the
74
+ * eslint ceiling on the way into this module.
75
+ */
76
+ const TERMINAL_INDEX_STATUSES = new Set([
77
+ 'done',
78
+ 'failed',
79
+ 'cancelled',
80
+ 'no-execution',
81
+ 'never-started',
82
+ 'unreadable'
83
+ ]);
84
+ export function unregisterActiveDispatch(input) {
85
+ const indexPath = activeDispatchIndexPath(input.projectRoot, input.sessionId);
86
+ if (!existsSync(indexPath))
87
+ return;
88
+ const index = readIndexMap(indexPath);
89
+ const existing = index[input.recordPath];
90
+ if (existing === undefined)
91
+ return;
92
+ if (TERMINAL_INDEX_STATUSES.has(input.status)) {
93
+ delete index[input.recordPath];
94
+ }
95
+ else {
96
+ index[input.recordPath] = { ...existing, status: input.status };
97
+ }
98
+ const tmp = `${indexPath}.tmp-${process.pid}-${Date.now()}`;
99
+ writeFileSync(tmp, JSON.stringify(index, null, 2) + '\n', 'utf8');
100
+ renameSync(tmp, indexPath);
101
+ }
102
+ /**
103
+ * for a session. Returns the current map<recordPath, entry>. Used
104
+ * by the LLM-side runner to discover in-flight records on restart.
105
+ * Returns an empty map when the index file is missing or corrupt
106
+ * (the on-disk records directory is the next fallback).
107
+ */
108
+ export function readActiveDispatchIndex(projectRoot, sessionId) {
109
+ const indexPath = activeDispatchIndexPath(projectRoot, sessionId);
110
+ const index = readIndexMap(indexPath);
111
+ const out = {};
112
+ for (const [k, v] of Object.entries(index)) {
113
+ if ('role' in v) {
114
+ out[k] = v;
115
+ }
116
+ }
117
+ return out;
118
+ }
@@ -21,7 +21,7 @@
21
21
  * that's your call". A warning is the right surface — let the LLM /
22
22
  * human read the reason and decide.
23
23
  */
24
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
24
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
25
25
  import { dirname, resolve } from 'node:path';
26
26
  import { withFileLockSync } from 'peaks-loop-shared-channel';
27
27
  export const BATCH_LIMIT = 6;
@@ -91,7 +91,6 @@ export function resetBatch(projectRoot, sid, batchId) {
91
91
  const path = batchCounterPath(projectRoot, sid, batchId);
92
92
  if (existsSync(path)) {
93
93
  try {
94
- const { unlinkSync } = require('node:fs');
95
94
  unlinkSync(path);
96
95
  }
97
96
  catch {