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
@@ -8,25 +8,38 @@ export declare function writeInitialDispatchRecord(input: WriteInitialDispatchIn
8
8
  record: DispatchRecord;
9
9
  };
10
10
  /**
11
- * Active-dispatches index. Per-session JSON file at
12
- * `.peaks/_sub_agents/<sid>/active-dispatches.json`. Map<recordPath,
13
- * ActiveDispatchEntry>. Updated on dispatch + completion.
11
+ * Bound the dispatch ledger before a new record registers: index rows left
12
+ * `queued` past the bound, whose record is still `queued`, are finalized by the
13
+ * tooling rather than by a remembered `peaks sub-agent finalize` call (measured:
14
+ * 39/39, 2/2, 9/9, 23/23 rows across four sessions had never been finalized).
15
+ *
16
+ * The RECORD decides, not the index row. Nothing writes a mid-flight status into
17
+ * a row — `registerActiveDispatch` hardcodes `queued` and the only unregister
18
+ * caller deletes the row — so a row reads `queued` for a sub-agent that is
19
+ * heartbeating right now, and a row-keyed guard would reap a live dispatch.
20
+ * `no-execution` is terminal for the heartbeat pollers, so that would stop a
21
+ * watcher waiting on work that is still running.
22
+ *
23
+ * The clock passed in is the SAME one that stamps this dispatch's `createdAt`,
24
+ * so the bound is judged on one clock and a caller that injects a clock (every
25
+ * test, and any replay) sees a consistent frame.
26
+ */
27
+ /**
28
+ * The record's own status, or `null` when the record file is absent. An
29
+ * unparseable file reports `unreadable` — a real terminal status — rather than
30
+ * `null`, so a caller can tell "no record here" from "a record I may not
31
+ * rewrite"; the reaper drops a row only for the first.
32
+ *
33
+ * Exported because the reaper takes it as its reader, so production and its
34
+ * tests judge on the same implementation rather than on two copies of it.
14
35
  */
15
- export interface ActiveDispatchEntry {
16
- readonly recordPath: string;
17
- readonly requestId: string;
18
- readonly role: string;
19
- readonly batchId: string;
20
- readonly createdAt: string;
21
- readonly status: 'queued' | 'running' | 'finalizing' | 'done' | 'failed' | 'cancelled' | 'stale' | 'no-execution' | 'never-started' | 'unreadable';
22
- }
36
+ export declare function readRecordStatus(recordPath: string): string | null;
23
37
  /**
24
- * for a session. Returns the current map<recordPath, entry>. Used
25
- * by the LLM-side runner to discover in-flight records on restart.
26
- * Returns an empty map when the index file is missing or corrupt
27
- * (the on-disk records directory is the next fallback).
38
+ * The active-dispatches index lives in `./active-dispatch-index.ts` (split out
39
+ * to keep this file under its size cap). Re-exported here so every existing
40
+ * importer keeps its path.
28
41
  */
29
- export declare function readActiveDispatchIndex(projectRoot: string, sessionId: string): Record<string, ActiveDispatchEntry>;
42
+ export { readActiveDispatchIndex, type ActiveDispatchEntry } from './active-dispatch-index.js';
30
43
  export declare const DISPATCH_RECORD_TTL_DAYS = 30;
31
44
  /**
32
45
  * (older than DISPATCH_RECORD_TTL_DAYS or already GC'd)? Mirrors
@@ -25,6 +25,8 @@ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSyn
25
25
  import { dirname, resolve } from 'node:path';
26
26
  import { assertSafeDispatchRecordPath, dispatchRecordPath } from '../security/safe-settings-path.js';
27
27
  import { withFileLockSync } from 'peaks-loop-shared-channel';
28
+ import { registerActiveDispatch, unregisterActiveDispatch } from './active-dispatch-index.js';
29
+ import { reapStaleQueuedEntries } from './ledger-reaper.js';
28
30
  import { isStageLabel } from './stage-enum.js';
29
31
  import { emitLeaseEvent } from '../observability/observability-service.js';
30
32
  import { upgradeRecord } from './dispatch-record-upgrade.js';
@@ -50,6 +52,8 @@ export function writeInitialDispatchRecord(input) {
50
52
  // source of truth; the index is purely a hint for the LLM-side
51
53
  // runner. A crash between writeAtomic and the index write is
52
54
  // non-fatal — the next restart scans the directory anyway.
55
+ // Bound the ledger BEFORE this dispatch registers (see the helper below).
56
+ reapLedgerBeforeRegister({ projectRoot, sessionId, now });
53
57
  registerActiveDispatch({
54
58
  projectRoot,
55
59
  sessionId,
@@ -61,6 +65,56 @@ export function writeInitialDispatchRecord(input) {
61
65
  });
62
66
  return { path: safePath, record };
63
67
  }
68
+ /**
69
+ * Bound the dispatch ledger before a new record registers: index rows left
70
+ * `queued` past the bound, whose record is still `queued`, are finalized by the
71
+ * tooling rather than by a remembered `peaks sub-agent finalize` call (measured:
72
+ * 39/39, 2/2, 9/9, 23/23 rows across four sessions had never been finalized).
73
+ *
74
+ * The RECORD decides, not the index row. Nothing writes a mid-flight status into
75
+ * a row — `registerActiveDispatch` hardcodes `queued` and the only unregister
76
+ * caller deletes the row — so a row reads `queued` for a sub-agent that is
77
+ * heartbeating right now, and a row-keyed guard would reap a live dispatch.
78
+ * `no-execution` is terminal for the heartbeat pollers, so that would stop a
79
+ * watcher waiting on work that is still running.
80
+ *
81
+ * The clock passed in is the SAME one that stamps this dispatch's `createdAt`,
82
+ * so the bound is judged on one clock and a caller that injects a clock (every
83
+ * test, and any replay) sees a consistent frame.
84
+ */
85
+ /**
86
+ * The record's own status, or `null` when the record file is absent. An
87
+ * unparseable file reports `unreadable` — a real terminal status — rather than
88
+ * `null`, so a caller can tell "no record here" from "a record I may not
89
+ * rewrite"; the reaper drops a row only for the first.
90
+ *
91
+ * Exported because the reaper takes it as its reader, so production and its
92
+ * tests judge on the same implementation rather than on two copies of it.
93
+ */
94
+ export function readRecordStatus(recordPath) {
95
+ if (!existsSync(recordPath))
96
+ return null;
97
+ try {
98
+ return readRecord(recordPath).status;
99
+ }
100
+ catch {
101
+ return 'unreadable';
102
+ }
103
+ }
104
+ function reapLedgerBeforeRegister(input) {
105
+ reapStaleQueuedEntries({
106
+ projectRoot: input.projectRoot,
107
+ sessionId: input.sessionId,
108
+ now: input.now,
109
+ readStatus: readRecordStatus,
110
+ finalize: (recordPath) => markCompleted({
111
+ recordPath,
112
+ outcome: 'no-execution',
113
+ status: 'no-execution',
114
+ projectRoot: input.projectRoot
115
+ })
116
+ });
117
+ }
64
118
  /**
65
119
  * Construct the initial `DispatchRecord` from a `WriteInitialDispatchInput`.
66
120
  * PRD-002b slice 6: extracted from `writeInitialDispatchRecord` so the
@@ -149,108 +203,12 @@ function buildInitialDispatchRecord(input, now) {
149
203
  : null
150
204
  };
151
205
  }
152
- function activeDispatchIndexPath(projectRoot, sessionId) {
153
- return resolve(projectRoot, '.peaks', '_sub_agents', sessionId, 'active-dispatches.json');
154
- }
155
- function registerActiveDispatch(input) {
156
- const indexPath = activeDispatchIndexPath(input.projectRoot, input.sessionId);
157
- const dir = dirname(indexPath);
158
- if (!existsSync(dir)) {
159
- mkdirSync(dir, { recursive: true });
160
- }
161
- let index = {};
162
- try {
163
- if (existsSync(indexPath)) {
164
- const raw = readFileSync(indexPath, 'utf8');
165
- const parsed = JSON.parse(raw);
166
- if (typeof parsed === 'object' && parsed !== null) {
167
- for (const [k, v] of Object.entries(parsed)) {
168
- if (typeof v === 'object' && v !== null && 'recordPath' in v) {
169
- index[k] = v;
170
- }
171
- }
172
- }
173
- }
174
- }
175
- catch {
176
- // Corrupt index — start fresh. The on-disk record is the source of truth.
177
- index = {};
178
- }
179
- index[input.recordPath] = {
180
- recordPath: input.recordPath,
181
- requestId: input.requestId,
182
- role: input.role,
183
- batchId: input.batchId,
184
- createdAt: input.now().toISOString(),
185
- status: 'queued'
186
- };
187
- const tmp = `${indexPath}.tmp-${process.pid}-${Date.now()}`;
188
- writeFileSync(tmp, JSON.stringify(index, null, 2) + '\n', 'utf8');
189
- renameSync(tmp, indexPath);
190
- }
191
- function unregisterActiveDispatch(input) {
192
- const indexPath = activeDispatchIndexPath(input.projectRoot, input.sessionId);
193
- if (!existsSync(indexPath))
194
- return;
195
- let index = {};
196
- try {
197
- const raw = readFileSync(indexPath, 'utf8');
198
- const parsed = JSON.parse(raw);
199
- if (typeof parsed === 'object' && parsed !== null) {
200
- for (const [k, v] of Object.entries(parsed)) {
201
- if (typeof v === 'object' && v !== null && 'recordPath' in v) {
202
- index[k] = v;
203
- }
204
- }
205
- }
206
- }
207
- catch {
208
- return;
209
- }
210
- if (input.recordPath in index) {
211
- index[input.recordPath] = { ...index[input.recordPath], status: input.status };
212
- // and `unreadable` are terminal (the startup-timeout service writes
213
- // them as terminal markers). Unregister on the full terminal set.
214
- if (input.status === 'done' ||
215
- input.status === 'failed' ||
216
- input.status === 'cancelled' ||
217
- input.status === 'no-execution' ||
218
- input.status === 'never-started' ||
219
- input.status === 'unreadable') {
220
- delete index[input.recordPath];
221
- }
222
- const tmp = `${indexPath}.tmp-${process.pid}-${Date.now()}`;
223
- writeFileSync(tmp, JSON.stringify(index, null, 2) + '\n', 'utf8');
224
- renameSync(tmp, indexPath);
225
- }
226
- }
227
206
  /**
228
- * for a session. Returns the current map<recordPath, entry>. Used
229
- * by the LLM-side runner to discover in-flight records on restart.
230
- * Returns an empty map when the index file is missing or corrupt
231
- * (the on-disk records directory is the next fallback).
207
+ * The active-dispatches index lives in `./active-dispatch-index.ts` (split out
208
+ * to keep this file under its size cap). Re-exported here so every existing
209
+ * importer keeps its path.
232
210
  */
233
- export function readActiveDispatchIndex(projectRoot, sessionId) {
234
- const indexPath = activeDispatchIndexPath(projectRoot, sessionId);
235
- if (!existsSync(indexPath))
236
- return {};
237
- try {
238
- const raw = readFileSync(indexPath, 'utf8');
239
- const parsed = JSON.parse(raw);
240
- if (typeof parsed !== 'object' || parsed === null)
241
- return {};
242
- const out = {};
243
- for (const [k, v] of Object.entries(parsed)) {
244
- if (typeof v === 'object' && v !== null && 'recordPath' in v && 'role' in v) {
245
- out[k] = v;
246
- }
247
- }
248
- return out;
249
- }
250
- catch {
251
- return {};
252
- }
253
- }
211
+ export { readActiveDispatchIndex } from './active-dispatch-index.js';
254
212
  export const DISPATCH_RECORD_TTL_DAYS = 30;
255
213
  /**
256
214
  * (older than DISPATCH_RECORD_TTL_DAYS or already GC'd)? Mirrors
@@ -19,9 +19,9 @@
19
19
  * The export is intentional — the helper has zero side effects and
20
20
  * keeps the dispatch action handler small.
21
21
  */
22
+ import { execFileSync } from 'node:child_process';
22
23
  export function runGitLsFiles(projectRoot, glob) {
23
24
  try {
24
- const { execFileSync } = require('node:child_process');
25
25
  const stdout = execFileSync('git', ['ls-files', '--', glob], {
26
26
  cwd: projectRoot,
27
27
  encoding: 'utf8',
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The Karpathy-guidelines context block, machine-injected into every sub-agent
3
+ * prompt by the dispatch prompt composer
4
+ * (`src/cli/commands/dispatch-prompt-composition.ts`), the same way the Test
5
+ * Tool Detection block is injected by `./test-tool-detection.ts`.
6
+ *
7
+ * Why this module exists: the obligation to deliver this block lived only as
8
+ * prose in `skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md`, addressed
9
+ * to the orchestrator. Measured 2026-10-12: four RD dispatch prompts in one
10
+ * session carried zero occurrences of `Karpathy`, and the one block that WAS
11
+ * appended had a word wrong — which the verbatim requirement makes a defect.
12
+ * An obligation a busy caller can forget is not an executor; this is.
13
+ *
14
+ * SOURCE OF TRUTH: the fenced block in the reference file's
15
+ * §"Karpathy-guidelines context" section is the canonical human-facing text;
16
+ * `KARPATHY_GUIDELINES_BLOCK` below is its machine copy, and
17
+ * `tests/unit/services/dispatch/karpathy-block.test.ts` asserts the two are
18
+ * byte-equal, so the copy cannot drift silently. A second copy that CAN drift
19
+ * is the same defect class as the dropped block; a pinned one is not.
20
+ *
21
+ * Why a static constant rather than a per-call read of the reference file
22
+ * (same reasoning as `./test-tool-detection.ts`): dispatch is a hot path, and
23
+ * the skill tree is not guaranteed to be present in an installed bundle.
24
+ */
25
+ /**
26
+ * The canonical block, verbatim. Byte-for-byte the fenced block under
27
+ * §"Karpathy-guidelines context" in the RD dispatch reference, including its
28
+ * trailing newline.
29
+ */
30
+ export declare const KARPATHY_GUIDELINES_BLOCK = "Karpathy-guidelines context (REQUIRED \u2014 read before any code action)\n\nThe 4 Karpathy guidelines are mandatory for every planning, implementation, refactor, and review action you take. If 200 lines could be 50, rewrite. Touch only what the request requires. Surface assumptions, do not hide them. Define verifiable success criteria.\n\n1. Think Before Coding\n\nDon't assume. Don't hide confusion. Surface tradeoffs. Before implementing: state assumptions explicitly; if multiple interpretations exist, present them; if a simpler approach exists, say so; if unclear, stop and ask.\n\n2. Simplicity First\n\nMinimum code that solves the problem. Nothing speculative. No features beyond what was asked. No abstractions for single-use code. No \"flexibility\" or \"configurability\" that wasn't requested. No error handling for impossible scenarios. If you write 200 lines and it could be 50, rewrite it. Ask yourself: \"Would a senior engineer say this is overcomplicated?\" If yes, simplify.\n\n3. Surgical Changes\n\nTouch only what you must. Clean up only your own mess. When editing existing code: don't \"improve\" adjacent code, comments, or formatting; don't refactor things that aren't broken; match existing style. When your changes create orphans: remove imports/variables/functions that YOUR changes made unused. The test: every changed line should trace directly to the user's request.\n\n4. Goal-Driven Execution\n\nDefine success criteria. Loop until verified. \"Add validation\" \u2192 write tests for invalid inputs, then make them pass. \"Fix the bug\" \u2192 write a test that reproduces it, then make it pass. For multi-step tasks, state a brief plan with verify checkpoints. Strong success criteria let you loop independently. Weak criteria require constant clarification.\n";
31
+ /** True when `text` already carries the canonical block (see the boundary note above). */
32
+ export declare function hasKarpathyBlock(text: string): boolean;
33
+ /**
34
+ * Ensure `text` carries the canonical block. Pure and idempotent.
35
+ *
36
+ * - `text` already carries the block (per {@link hasKarpathyBlock}) → returned
37
+ * unchanged, byte for byte. This is the compliant caller's guarantee: no
38
+ * double-append and no reflow of a prompt that already has the block.
39
+ * - otherwise → `text` with the block appended, and `text` itself untouched.
40
+ *
41
+ * Near-miss policy, stated rather than left implicit: when the caller carries a
42
+ * copy whose body differs, the canonical block is injected anyway and the
43
+ * caller's copy is left in place. Deleting text a caller wrote is not this
44
+ * function's job; delivering the canonical text is. The cost is two
45
+ * "Karpathy-guidelines context" headings in that prompt — visible, and the one
46
+ * the child must obey is the canonical one.
47
+ *
48
+ * The caller applies this to the assembled prompt, not to the caller's draft —
49
+ * see `composeDispatchPrompt`, which runs it on `effectivePrompt` (the exact
50
+ * string handed to the sub-agent as `toolCall.args.prompt` and recorded as the
51
+ * dispatch record's `prompt`). The caller's draft is inside that string
52
+ * verbatim, so a draft-side copy is matched too, and the check also catches a
53
+ * block some other contributor put in the assembled text.
54
+ */
55
+ export declare function ensureKarpathyBlock(text: string): string;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The Karpathy-guidelines context block, machine-injected into every sub-agent
3
+ * prompt by the dispatch prompt composer
4
+ * (`src/cli/commands/dispatch-prompt-composition.ts`), the same way the Test
5
+ * Tool Detection block is injected by `./test-tool-detection.ts`.
6
+ *
7
+ * Why this module exists: the obligation to deliver this block lived only as
8
+ * prose in `skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md`, addressed
9
+ * to the orchestrator. Measured 2026-10-12: four RD dispatch prompts in one
10
+ * session carried zero occurrences of `Karpathy`, and the one block that WAS
11
+ * appended had a word wrong — which the verbatim requirement makes a defect.
12
+ * An obligation a busy caller can forget is not an executor; this is.
13
+ *
14
+ * SOURCE OF TRUTH: the fenced block in the reference file's
15
+ * §"Karpathy-guidelines context" section is the canonical human-facing text;
16
+ * `KARPATHY_GUIDELINES_BLOCK` below is its machine copy, and
17
+ * `tests/unit/services/dispatch/karpathy-block.test.ts` asserts the two are
18
+ * byte-equal, so the copy cannot drift silently. A second copy that CAN drift
19
+ * is the same defect class as the dropped block; a pinned one is not.
20
+ *
21
+ * Why a static constant rather than a per-call read of the reference file
22
+ * (same reasoning as `./test-tool-detection.ts`): dispatch is a hot path, and
23
+ * the skill tree is not guaranteed to be present in an installed bundle.
24
+ */
25
+ /**
26
+ * The canonical block, verbatim. Byte-for-byte the fenced block under
27
+ * §"Karpathy-guidelines context" in the RD dispatch reference, including its
28
+ * trailing newline.
29
+ */
30
+ export const KARPATHY_GUIDELINES_BLOCK = `Karpathy-guidelines context (REQUIRED — read before any code action)
31
+
32
+ The 4 Karpathy guidelines are mandatory for every planning, implementation, refactor, and review action you take. If 200 lines could be 50, rewrite. Touch only what the request requires. Surface assumptions, do not hide them. Define verifiable success criteria.
33
+
34
+ 1. Think Before Coding
35
+
36
+ Don't assume. Don't hide confusion. Surface tradeoffs. Before implementing: state assumptions explicitly; if multiple interpretations exist, present them; if a simpler approach exists, say so; if unclear, stop and ask.
37
+
38
+ 2. Simplicity First
39
+
40
+ Minimum code that solves the problem. Nothing speculative. No features beyond what was asked. No abstractions for single-use code. No "flexibility" or "configurability" that wasn't requested. No error handling for impossible scenarios. If you write 200 lines and it could be 50, rewrite it. Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
41
+
42
+ 3. Surgical Changes
43
+
44
+ Touch only what you must. Clean up only your own mess. When editing existing code: don't "improve" adjacent code, comments, or formatting; don't refactor things that aren't broken; match existing style. When your changes create orphans: remove imports/variables/functions that YOUR changes made unused. The test: every changed line should trace directly to the user's request.
45
+
46
+ 4. Goal-Driven Execution
47
+
48
+ Define success criteria. Loop until verified. "Add validation" → write tests for invalid inputs, then make them pass. "Fix the bug" → write a test that reproduces it, then make it pass. For multi-step tasks, state a brief plan with verify checkpoints. Strong success criteria let you loop independently. Weak criteria require constant clarification.
49
+ `;
50
+ /**
51
+ * The block as the presence test compares it: line endings normalized to `\n`
52
+ * and trailing whitespace trimmed.
53
+ *
54
+ * The trailing boundary is NOT part of the block's identity, and treating it as
55
+ * part of it is a measured defect, not a hypothetical one. A caller that passes
56
+ * its prompt through a shell round-trip (`--prompt "$(cat prompt.txt)"`) or
57
+ * through any tool that trims the last newline hands the CLI the block MINUS
58
+ * its final `\n`; a byte-exact `includes()` then read that as "no block" and
59
+ * appended a second, identical copy — the double-append the contract forbids,
60
+ * reproduced end to end on 2026-10-13. The same normalization answers a Windows
61
+ * checkout, where the reference file the caller copies from may carry CRLF
62
+ * while the constant does not.
63
+ *
64
+ * What is deliberately NOT normalized: the block's BODY. A copy with one word
65
+ * wrong is still treated as absent and the canonical text is added, because the
66
+ * requirement is verbatim delivery and the measured 2026-10-12 failure was
67
+ * exactly a block appended with a word wrong. A header line alone is likewise
68
+ * not evidence: matching the header would accept the wrong body.
69
+ */
70
+ const KARPATHY_GUIDELINES_BLOCK_FOR_PRESENCE = KARPATHY_GUIDELINES_BLOCK.replace(/\r\n/g, '\n').trimEnd();
71
+ /** True when `text` already carries the canonical block (see the boundary note above). */
72
+ export function hasKarpathyBlock(text) {
73
+ return text.replace(/\r\n/g, '\n').includes(KARPATHY_GUIDELINES_BLOCK_FOR_PRESENCE);
74
+ }
75
+ /**
76
+ * Ensure `text` carries the canonical block. Pure and idempotent.
77
+ *
78
+ * - `text` already carries the block (per {@link hasKarpathyBlock}) → returned
79
+ * unchanged, byte for byte. This is the compliant caller's guarantee: no
80
+ * double-append and no reflow of a prompt that already has the block.
81
+ * - otherwise → `text` with the block appended, and `text` itself untouched.
82
+ *
83
+ * Near-miss policy, stated rather than left implicit: when the caller carries a
84
+ * copy whose body differs, the canonical block is injected anyway and the
85
+ * caller's copy is left in place. Deleting text a caller wrote is not this
86
+ * function's job; delivering the canonical text is. The cost is two
87
+ * "Karpathy-guidelines context" headings in that prompt — visible, and the one
88
+ * the child must obey is the canonical one.
89
+ *
90
+ * The caller applies this to the assembled prompt, not to the caller's draft —
91
+ * see `composeDispatchPrompt`, which runs it on `effectivePrompt` (the exact
92
+ * string handed to the sub-agent as `toolCall.args.prompt` and recorded as the
93
+ * dispatch record's `prompt`). The caller's draft is inside that string
94
+ * verbatim, so a draft-side copy is matched too, and the check also catches a
95
+ * block some other contributor put in the assembled text.
96
+ */
97
+ export function ensureKarpathyBlock(text) {
98
+ if (hasKarpathyBlock(text))
99
+ return text;
100
+ return `${text}\n\n${KARPATHY_GUIDELINES_BLOCK}`;
101
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * How long a row may sit in the index still `queued` before the next dispatch
3
+ * write reaps it.
4
+ *
5
+ * Six hours, from the ledger's own data rather than a round number: the ACTIVE
6
+ * session's index spans 8.6 hours and holds 18 entries, all `queued`; the
7
+ * largest gap between two dispatches in it is 4h19m. The bound must clear the
8
+ * longest dispatch a session can legitimately still be running, and 6h is above
9
+ * every dispatch interval this ledger records while staying two orders of
10
+ * magnitude tighter than the 30-day `DISPATCH_RECORD_TTL_DAYS` file GC.
11
+ *
12
+ * Only a row whose RECORD is still `queued` is reaped. The residual risk is
13
+ * recorded rather than hidden: a sub-agent still running when the session
14
+ * dispatches again after a longer-than-six-hour gap has its bookkeeping cleared
15
+ * early. Its work is unaffected; its later finalize call finds nothing `queued`
16
+ * and reports that.
17
+ *
18
+ * One thing the reap inherits rather than causes, recorded because it is
19
+ * invisible otherwise: `markCompleted` also attempts a graph `envelope-received`
20
+ * transition, and the reaped records are graph-bound. That transition is inert —
21
+ * measured 2026-10-13, 54/54 nodes in `.peaks/_runtime/<sessionId>/graphs/` are
22
+ * still `prepared` — so the reap changes no graph state. Documented, not fixed.
23
+ */
24
+ export declare const LEDGER_REAP_BOUND_MS: number;
25
+ export interface ReapStaleQueuedEntriesInput {
26
+ projectRoot: string;
27
+ sessionId: string;
28
+ /**
29
+ * The RECORD's own status — the source of truth — or `null` when the record
30
+ * file is absent. Injected rather than read here so this module does not
31
+ * import the writer that imports it.
32
+ *
33
+ * Why the record and not the index row: no production path ever writes a
34
+ * mid-flight status into a row. `registerActiveDispatch` hardcodes `queued`,
35
+ * and the only unregister caller is `markCompleted`, whose terminal statuses
36
+ * DELETE the row. So every row reads `queued` — measured 20/20 rows of the
37
+ * active session — and a guard that read the row would reap a sub-agent that
38
+ * is heartbeating right now. `no-execution` is terminal for the heartbeat
39
+ * pollers, so that would stop a watcher waiting on live work.
40
+ */
41
+ readStatus: (recordPath: string) => string | null;
42
+ /**
43
+ * Terminal transition for the on-disk record (`markCompleted` in
44
+ * `./dispatch-record-writer.ts`, injected to keep this module free of a
45
+ * cycle back into the writer). It is expected to unregister the row as a
46
+ * side effect, which is what removes it from the index.
47
+ */
48
+ finalize: (recordPath: string) => void;
49
+ /** Test seam; defaults to the real clock. */
50
+ now?: () => Date;
51
+ /** Override {@link LEDGER_REAP_BOUND_MS}; the CLI never does. */
52
+ boundMs?: number;
53
+ }
54
+ /** What the reaper did, so the caller (and a test) can see it rather than infer it. */
55
+ export interface ReapStaleQueuedEntriesResult {
56
+ /**
57
+ * Rows removed from the index. A row is removed when its record was
58
+ * finalized, and also when the row named no usable record — a path outside
59
+ * `.peaks/_sub_agents/`, or one whose file is absent. Both leave the index
60
+ * smaller; only the first changes a record.
61
+ */
62
+ readonly reaped: readonly string[];
63
+ }
64
+ /**
65
+ * Finalize every index row whose RECORD is still `queued` past the bound, and
66
+ * drop it from the index. Called at the start of `writeInitialDispatchRecord`,
67
+ * i.e. at the next dispatch write — the exact moment the index would grow.
68
+ *
69
+ * A row is dropped without finalizing when it names no usable record: a path
70
+ * outside `.peaks/_sub_agents/`, or a file that is absent. A row pointing at no
71
+ * record is stale by definition.
72
+ *
73
+ * The row is only a hint. The RECORD decides: `running` / `finalizing` is a live
74
+ * dispatch and is left alone however old it is, and a record the writer already
75
+ * terminated is left to that writer. Only a record still `queued` — never
76
+ * started AND never finalized — is reaped. (This is the distinction that
77
+ * matters: `no-execution` is terminal for the heartbeat pollers, so reaping a
78
+ * live record would stop a watcher waiting on it.)
79
+ */
80
+ export declare function reapStaleQueuedEntries(input: ReapStaleQueuedEntriesInput): ReapStaleQueuedEntriesResult;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The active-dispatches ledger reaper: the bound that stops the index growing
3
+ * with the session, and the decision about which rows it may act on.
4
+ *
5
+ * Split out of `./active-dispatch-index.ts` (that module owns the index FORMAT —
6
+ * register, unregister, read; this one owns the POLICY). Why a reaper exists at
7
+ * all: nothing ever finalized a dispatch. Measured 2026-10-12 across four
8
+ * sessions, `queued`/total was 39/39, 2/2, 9/9, 23/23 — not one record in any
9
+ * session had been finalized, and a recovery verb built for the purpose
10
+ * (`peaks sub-agent finalize --all-stale`) did not help, because building a verb
11
+ * does not make anyone call it. So the bound is applied by the tooling, at the
12
+ * one moment the index can grow: the next dispatch write.
13
+ */
14
+ import { assertSafeDispatchRecordPath } from '../security/safe-settings-path.js';
15
+ import { readActiveDispatchIndex, unregisterActiveDispatch } from './active-dispatch-index.js';
16
+ const MINUTES_PER_HOUR = 60;
17
+ const MS_PER_MINUTE = 60_000;
18
+ /** The bound, in hours. Named so the constant below states a policy, not a `6`. */
19
+ const LEDGER_REAP_BOUND_HOURS = 6;
20
+ /**
21
+ * How long a row may sit in the index still `queued` before the next dispatch
22
+ * write reaps it.
23
+ *
24
+ * Six hours, from the ledger's own data rather than a round number: the ACTIVE
25
+ * session's index spans 8.6 hours and holds 18 entries, all `queued`; the
26
+ * largest gap between two dispatches in it is 4h19m. The bound must clear the
27
+ * longest dispatch a session can legitimately still be running, and 6h is above
28
+ * every dispatch interval this ledger records while staying two orders of
29
+ * magnitude tighter than the 30-day `DISPATCH_RECORD_TTL_DAYS` file GC.
30
+ *
31
+ * Only a row whose RECORD is still `queued` is reaped. The residual risk is
32
+ * recorded rather than hidden: a sub-agent still running when the session
33
+ * dispatches again after a longer-than-six-hour gap has its bookkeeping cleared
34
+ * early. Its work is unaffected; its later finalize call finds nothing `queued`
35
+ * and reports that.
36
+ *
37
+ * One thing the reap inherits rather than causes, recorded because it is
38
+ * invisible otherwise: `markCompleted` also attempts a graph `envelope-received`
39
+ * transition, and the reaped records are graph-bound. That transition is inert —
40
+ * measured 2026-10-13, 54/54 nodes in `.peaks/_runtime/<sessionId>/graphs/` are
41
+ * still `prepared` — so the reap changes no graph state. Documented, not fixed.
42
+ */
43
+ export const LEDGER_REAP_BOUND_MS = LEDGER_REAP_BOUND_HOURS * MINUTES_PER_HOUR * MS_PER_MINUTE;
44
+ /**
45
+ * Sentinel for a row that names nothing this module may act on: a path outside
46
+ * the ledger (the guard refuses it) or a record file that is absent. Distinct
47
+ * from `unreadable`, which is a real status meaning "a record I may not
48
+ * rewrite" — the two must not be collapsed, because the first is a row to drop
49
+ * and the second is a row to keep.
50
+ */
51
+ const UNUSABLE_ROW = 'unusable-row';
52
+ /**
53
+ * The record's status. The path guard runs HERE, before the record is read,
54
+ * because the row names a path this function goes on to write to; a refused
55
+ * path returns {@link UNUSABLE_ROW} rather than a status, so a refused row is
56
+ * never read and never mistaken for a readable one.
57
+ */
58
+ function readStatusGuarded(input, recordPath) {
59
+ try {
60
+ assertSafeDispatchRecordPath(recordPath, input.projectRoot);
61
+ }
62
+ catch {
63
+ return UNUSABLE_ROW;
64
+ }
65
+ return input.readStatus(recordPath) ?? UNUSABLE_ROW;
66
+ }
67
+ /** Decide one row, from the row and the record it names. */
68
+ function decideRow(input, recordPath, entry, cutoffMs) {
69
+ if (entry.status !== 'queued')
70
+ return 'keep';
71
+ const createdAtMs = Date.parse(entry.createdAt);
72
+ if (!Number.isFinite(createdAtMs) || createdAtMs >= cutoffMs)
73
+ return 'keep';
74
+ const recordStatus = readStatusGuarded(input, recordPath);
75
+ if (recordStatus === 'queued')
76
+ return 'reap';
77
+ if (recordStatus === UNUSABLE_ROW)
78
+ return 'drop';
79
+ return 'keep';
80
+ }
81
+ /** Remove a row from the index without touching the record it named. */
82
+ function dropRow(input, recordPath) {
83
+ unregisterActiveDispatch({
84
+ projectRoot: input.projectRoot,
85
+ sessionId: input.sessionId,
86
+ recordPath,
87
+ status: 'no-execution'
88
+ });
89
+ }
90
+ /**
91
+ * Finalize every index row whose RECORD is still `queued` past the bound, and
92
+ * drop it from the index. Called at the start of `writeInitialDispatchRecord`,
93
+ * i.e. at the next dispatch write — the exact moment the index would grow.
94
+ *
95
+ * A row is dropped without finalizing when it names no usable record: a path
96
+ * outside `.peaks/_sub_agents/`, or a file that is absent. A row pointing at no
97
+ * record is stale by definition.
98
+ *
99
+ * The row is only a hint. The RECORD decides: `running` / `finalizing` is a live
100
+ * dispatch and is left alone however old it is, and a record the writer already
101
+ * terminated is left to that writer. Only a record still `queued` — never
102
+ * started AND never finalized — is reaped. (This is the distinction that
103
+ * matters: `no-execution` is terminal for the heartbeat pollers, so reaping a
104
+ * live record would stop a watcher waiting on it.)
105
+ */
106
+ export function reapStaleQueuedEntries(input) {
107
+ const now = input.now ?? (() => new Date());
108
+ const boundMs = input.boundMs ?? LEDGER_REAP_BOUND_MS;
109
+ const cutoffMs = now().getTime() - boundMs;
110
+ const index = readActiveDispatchIndex(input.projectRoot, input.sessionId);
111
+ const reaped = [];
112
+ for (const [recordPath, entry] of Object.entries(index)) {
113
+ const decision = decideRow(input, recordPath, entry, cutoffMs);
114
+ if (decision === 'keep')
115
+ continue;
116
+ reaped.push(recordPath);
117
+ if (decision === 'drop') {
118
+ dropRow(input, recordPath);
119
+ continue;
120
+ }
121
+ try {
122
+ input.finalize(recordPath);
123
+ }
124
+ catch {
125
+ // The reader said `queued` and the writer could not turn it terminal;
126
+ // drop the row so it cannot accumulate.
127
+ dropRow(input, recordPath);
128
+ }
129
+ }
130
+ return { reaped };
131
+ }