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
@@ -37,6 +37,13 @@ export const ALLOW_LISTED_PATH_PATTERNS = [
37
37
  'CHANGELOG.md',
38
38
  'README.md'
39
39
  ];
40
+ /**
41
+ * The single driver identity that opens the hard-blocked families: the
42
+ * fast-lane skill's name, compared as a whole string. No prefix match and no
43
+ * case folding — a future `peaks-race-<something>` sibling must NOT inherit
44
+ * this write, because the write it opens is source editing.
45
+ */
46
+ const FAST_LANE_DRIVER = 'peaks-race-code';
40
47
  /** Pull the target file path from `input.file_path | input.path | input.notebook_path`. */
41
48
  export function extractFilePath(input) {
42
49
  for (const key of ['file_path', 'path', 'notebook_path']) {
@@ -59,8 +66,14 @@ function matchesAny(path, families) {
59
66
  /**
60
67
  * Pure decision function. Given the tool name + input object, return
61
68
  * the gate verdict. Tolerates malformed payloads (allow).
69
+ *
70
+ * `driver` is the already-resolved identity of whoever is running the
71
+ * tool call, or `null`/absent when no caller identity resolved. Absent and
72
+ * `null` are the same verdict as before this parameter existed: the
73
+ * hard-blocked families deny. Resolution is the caller's job, so this
74
+ * module keeps no session, lease or filesystem state.
62
75
  */
63
- export function decideGateAction(tool, input) {
76
+ export function decideGateAction(tool, input, driver) {
64
77
  // Only gate Edit / Write / MultiEdit.
65
78
  if (tool !== 'Edit' && tool !== 'Write' && tool !== 'MultiEdit') {
66
79
  return { action: 'allow' };
@@ -72,7 +85,7 @@ export function decideGateAction(tool, input) {
72
85
  // handles file paths only.
73
86
  return { action: 'allow' };
74
87
  }
75
- // Allow-list check first — short-circuits any deny.
88
+ // Allow-list check first — short-circuits any deny, for every driver.
76
89
  const allowMatch = matchesAny(filePath, ALLOW_LISTED_PATH_PATTERNS);
77
90
  if (allowMatch !== null) {
78
91
  return { action: 'allow' };
@@ -80,6 +93,12 @@ export function decideGateAction(tool, input) {
80
93
  // Hard-blocked family check.
81
94
  const denyMatch = matchesAny(filePath, HARD_BLOCKED_PATH_FAMILIES);
82
95
  if (denyMatch !== null) {
96
+ // A driver that is not the fast lane falls through to the same deny a
97
+ // two-argument call produces, so an unresolvable identity can never
98
+ // become a silent pass.
99
+ if (driver === FAST_LANE_DRIVER) {
100
+ return { action: 'allow' };
101
+ }
83
102
  const reason = `${denyMatch} (orchestrator's hard-blocked path family)`;
84
103
  const message = `PEAKS_CODE_PROHIBITED_DIRECT_EDIT: ${filePath} matches hard-blocked path family ${reason}; ` +
85
104
  `orchestrator MUST NOT Edit/Write these directly. Use: peaks sub-agent dispatch rd --prompt '<your task>' --request-id <rid> --project . --batch-id <uuid>`;
@@ -37,6 +37,7 @@ import { dirname, join } from 'node:path';
37
37
  import { deserializeLease, isLeaseActive, leaseFilePath } from '../worktree/worktree-lease.js';
38
38
  import { readDispatchProvenance } from '../worktree/dispatch-provenance.js';
39
39
  import { containerLeaseFilePath, deserializeContainerLease, isContainerLeaseActive } from '../container/container-lease.js';
40
+ import { consumedGrantsDenial, expiredGrantsDenial, noAuthorizationDenial, noGrantForOperationDenial, requestMismatchDenial } from './worktree-refusal-messages.js';
40
41
  export const WORKTREE_AUTH_FILE = 'worktree-auth.json';
41
42
  /** Stable identifier of the current "user authorization" — derived from session + tool + key args. */
42
43
  export function currentAuthFingerprint(input) {
@@ -165,13 +166,7 @@ export function classifyToolCall(input) {
165
166
  */
166
167
  export function decideFromAuthorization(input, operation, file) {
167
168
  if (file === null) {
168
- return {
169
- allow: false,
170
- code: 'WORKTREE_USER_AUTH_REQUIRED',
171
- reason: `No current-task user authorization for "${operation}" (session=${input.sessionId}).`,
172
- remediation: `Ask the user to explicitly authorize this worktree-mutating operation, then run \`peaks worktree auth grant --operation ${operation} --reason "<why>"\` ` +
173
- `before the tool call retries. Re-running with --consume=false and a longer --ttl is allowed but should be rare.`
174
- };
169
+ return noAuthorizationDenial(operation, input.sessionId);
175
170
  }
176
171
  const now = Date.now();
177
172
  // First try to find a requestId-matched, non-consumed, unexpired grant. If none is found,
@@ -193,41 +188,21 @@ export function decideFromAuthorization(input, operation, file) {
193
188
  // No live grant matched the current rid (or the caller's rid is null). Diagnose why.
194
189
  const sameOpAnyState = file.grants.filter((g) => g.operation === operation);
195
190
  if (sameOpAnyState.length === 0) {
196
- return {
197
- allow: false,
198
- code: 'WORKTREE_USER_AUTH_REQUIRED',
199
- reason: `No grant for operation "${operation}" in this session.`,
200
- remediation: `Run \`peaks worktree auth grant --operation ${operation} --reason "<why>"\` from the LLM after the user has explicitly asked for the operation.`
201
- };
191
+ return noGrantForOperationDenial(operation);
202
192
  }
203
193
  const ridScoped = sameOpAnyState.find((g) => g.requestId !== null);
204
194
  const ridMatchesScope = ridScoped !== undefined &&
205
195
  (input.requestId === null || ridScoped.requestId === input.requestId);
206
196
  if (ridScoped !== undefined && !ridMatchesScope) {
207
- return {
208
- allow: false,
209
- code: 'WORKTREE_USER_AUTH_REQUEST_MISMATCH',
210
- reason: `Grant for "${operation}" is scoped to requestId=${ridScoped.requestId} but the current tool call carries requestId=${input.requestId ?? 'null'}.`,
211
- remediation: `Either drop the requestId scope from the grant (\`peaks worktree auth grant --operation ${operation} --no-request-id\`) or operate under the scoped request.`
212
- };
197
+ return requestMismatchDenial(operation, ridScoped.requestId, input.requestId);
213
198
  }
214
199
  // Otherwise: every grant for the operation is either consumed or expired.
215
200
  const hasUnexpired = sameOpAnyState.some((g) => Date.parse(g.expiresAt) > now);
216
201
  if (!hasUnexpired) {
217
- return {
218
- allow: false,
219
- code: 'WORKTREE_USER_AUTH_EXPIRED',
220
- reason: `All grants for operation "${operation}" in this session have expired.`,
221
- remediation: `Re-run \`peaks worktree auth grant --operation ${operation} --reason "<why>"\` (default TTL 5 min) before the tool call retries.`
222
- };
202
+ return expiredGrantsDenial(operation);
223
203
  }
224
204
  // Grants exist and at least one is unexpired, but every non-expired one is consumed.
225
- return {
226
- allow: false,
227
- code: 'WORKTREE_USER_AUTH_REQUIRED',
228
- reason: `All unexpired grants for operation "${operation}" in this session are already consumed.`,
229
- remediation: `Re-run \`peaks worktree auth grant --operation ${operation} --reason "<why>"\` to issue a fresh grant (or pass --multi to make it multi-use).`
230
- };
205
+ return consumedGrantsDenial(operation);
231
206
  }
232
207
  /**
233
208
  * Public entry point used by `peaks gate enforce`. Reads the auth file, decides, and (when consume=true
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The denial text the worktree-authorization gate prints when no live user
3
+ * grant covers the operation.
4
+ *
5
+ * WHY ITS OWN MODULE. `worktree-authorization-gate.ts` is 701 lines against a
6
+ * 300-line cap and already carries a baseline row, so it may only shrink. The
7
+ * five refusal texts it used to build inline move here and the gate calls
8
+ * these builders — the extract-don't-append move this repository makes instead
9
+ * of growing an over-cap file.
10
+ *
11
+ * WHY THE TEXT ASKS THE READER TO GO TO THE USER. The gate is a `PreToolUse`
12
+ * hook, so its reader is the agent, and the AGENT IS THE PARTY THE PROJECT'S
13
+ * RULE AIMS AT: the authorization this gate consumes is the user's to give. The
14
+ * gate cannot enforce that distinction — see the next paragraph, which is the
15
+ * part an earlier revision of this file got wrong — so the text asks rather
16
+ * than claims, and the denial that told its own reader to run a command it was
17
+ * told it must not run is the defect this function replaces.
18
+ *
19
+ * WHAT THE GATE ACTUALLY CHECKS — AND WHAT IT DOES NOT. A grant recorded for
20
+ * the operation in this session. Nothing else: the gate has no issuer concept,
21
+ * so it cannot and does not discriminate on who wrote the grant. Measured
22
+ * 2026-10-13, end to end, in a scratch project: `git stash drop stash@{0}` is
23
+ * refused (exit 2); the agent then runs
24
+ * `peaks worktree auth grant --operation git-stash-mutating --reason "the agent
25
+ * wrote this itself; no user was involved"` and gets `ok: true`; the SAME call
26
+ * then exits 0 and is allowed. The grant stays operation-scoped (`git worktree
27
+ * add` against the same project is still refused), so the gate does gate — it
28
+ * just cannot tell consent from self-authorization.
29
+ *
30
+ * WHY THIS MATTERS FOR THE TEXT. An earlier revision of this function said "an
31
+ * agent-issued grant is not the consent this gate checks for, so the reader
32
+ * cannot satisfy this refusal itself". That is exactly the defect the function
33
+ * exists to avoid: a message asserting a guarantee the code does not implement,
34
+ * which this module's own header above already falsifies. The text below says
35
+ * what the measurement shows — the gate needs a recorded grant, and nothing
36
+ * distinguishes who issued it — and keeps the ask, because the authorization is
37
+ * the user's to give even though the gate cannot enforce that.
38
+ *
39
+ * `operation` is a plain `string`, not the gate's `OperationType`: the text
40
+ * only interpolates the value, and importing that type back would make the two
41
+ * modules mutually importing. `as const` on `code` and `allow` keeps each
42
+ * returned literal narrow enough to be the gate's deny variant without the
43
+ * import.
44
+ */
45
+ export declare function noAuthorizationDenial(operation: string, sessionId: string): {
46
+ allow: false;
47
+ code: "WORKTREE_USER_AUTH_REQUIRED";
48
+ reason: string;
49
+ remediation: string;
50
+ };
51
+ export declare function noGrantForOperationDenial(operation: string): {
52
+ allow: false;
53
+ code: "WORKTREE_USER_AUTH_REQUIRED";
54
+ reason: string;
55
+ remediation: string;
56
+ };
57
+ export declare function requestMismatchDenial(operation: string, grantRequestId: string | null, currentRequestId: string | null): {
58
+ allow: false;
59
+ code: "WORKTREE_USER_AUTH_REQUEST_MISMATCH";
60
+ reason: string;
61
+ remediation: string;
62
+ };
63
+ export declare function expiredGrantsDenial(operation: string): {
64
+ allow: false;
65
+ code: "WORKTREE_USER_AUTH_EXPIRED";
66
+ reason: string;
67
+ remediation: string;
68
+ };
69
+ export declare function consumedGrantsDenial(operation: string): {
70
+ allow: false;
71
+ code: "WORKTREE_USER_AUTH_REQUIRED";
72
+ reason: string;
73
+ remediation: string;
74
+ };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * The denial text the worktree-authorization gate prints when no live user
3
+ * grant covers the operation.
4
+ *
5
+ * WHY ITS OWN MODULE. `worktree-authorization-gate.ts` is 701 lines against a
6
+ * 300-line cap and already carries a baseline row, so it may only shrink. The
7
+ * five refusal texts it used to build inline move here and the gate calls
8
+ * these builders — the extract-don't-append move this repository makes instead
9
+ * of growing an over-cap file.
10
+ *
11
+ * WHY THE TEXT ASKS THE READER TO GO TO THE USER. The gate is a `PreToolUse`
12
+ * hook, so its reader is the agent, and the AGENT IS THE PARTY THE PROJECT'S
13
+ * RULE AIMS AT: the authorization this gate consumes is the user's to give. The
14
+ * gate cannot enforce that distinction — see the next paragraph, which is the
15
+ * part an earlier revision of this file got wrong — so the text asks rather
16
+ * than claims, and the denial that told its own reader to run a command it was
17
+ * told it must not run is the defect this function replaces.
18
+ *
19
+ * WHAT THE GATE ACTUALLY CHECKS — AND WHAT IT DOES NOT. A grant recorded for
20
+ * the operation in this session. Nothing else: the gate has no issuer concept,
21
+ * so it cannot and does not discriminate on who wrote the grant. Measured
22
+ * 2026-10-13, end to end, in a scratch project: `git stash drop stash@{0}` is
23
+ * refused (exit 2); the agent then runs
24
+ * `peaks worktree auth grant --operation git-stash-mutating --reason "the agent
25
+ * wrote this itself; no user was involved"` and gets `ok: true`; the SAME call
26
+ * then exits 0 and is allowed. The grant stays operation-scoped (`git worktree
27
+ * add` against the same project is still refused), so the gate does gate — it
28
+ * just cannot tell consent from self-authorization.
29
+ *
30
+ * WHY THIS MATTERS FOR THE TEXT. An earlier revision of this function said "an
31
+ * agent-issued grant is not the consent this gate checks for, so the reader
32
+ * cannot satisfy this refusal itself". That is exactly the defect the function
33
+ * exists to avoid: a message asserting a guarantee the code does not implement,
34
+ * which this module's own header above already falsifies. The text below says
35
+ * what the measurement shows — the gate needs a recorded grant, and nothing
36
+ * distinguishes who issued it — and keeps the ask, because the authorization is
37
+ * the user's to give even though the gate cannot enforce that.
38
+ *
39
+ * `operation` is a plain `string`, not the gate's `OperationType`: the text
40
+ * only interpolates the value, and importing that type back would make the two
41
+ * modules mutually importing. `as const` on `code` and `allow` keeps each
42
+ * returned literal narrow enough to be the gate's deny variant without the
43
+ * import.
44
+ */
45
+ /**
46
+ * The remedy paragraph every denial ends with, with the operation baked in.
47
+ *
48
+ * Four facts, in the order a reader needs them: what the gate requires, what it
49
+ * does not check, whose authorization the rule is, and how to record it.
50
+ */
51
+ function userSideGrant(operation) {
52
+ return [
53
+ `The gate requires one thing: a grant recorded for the "${operation}" operation in this session's \`.peaks/_runtime/<sessionId>/worktree-auth.json\`.`,
54
+ 'Nothing in the gate records or checks WHO issued a grant, so a grant the reader writes itself is accepted — the requirement is a recorded grant, not a verified issuer.',
55
+ "The authorization is the USER's to give: ask them first, then record it with",
56
+ ` peaks worktree auth grant --operation ${operation} --reason "<the words they used>"`,
57
+ '(`--ttl <ms>` and `--multi` are accepted.) A grant with no user behind it satisfies this gate; it does not satisfy the rule the gate exists for, which is why the ask comes first.'
58
+ ].join('\n');
59
+ }
60
+ export function noAuthorizationDenial(operation, sessionId) {
61
+ return {
62
+ allow: false,
63
+ code: 'WORKTREE_USER_AUTH_REQUIRED',
64
+ reason: `No current-task user authorization for "${operation}" (session=${sessionId}).`,
65
+ remediation: userSideGrant(operation)
66
+ };
67
+ }
68
+ export function noGrantForOperationDenial(operation) {
69
+ return {
70
+ allow: false,
71
+ code: 'WORKTREE_USER_AUTH_REQUIRED',
72
+ reason: `No grant for operation "${operation}" in this session.`,
73
+ remediation: userSideGrant(operation)
74
+ };
75
+ }
76
+ export function requestMismatchDenial(operation, grantRequestId, currentRequestId) {
77
+ return {
78
+ allow: false,
79
+ code: 'WORKTREE_USER_AUTH_REQUEST_MISMATCH',
80
+ reason: `Grant for "${operation}" is scoped to requestId=${grantRequestId} but the current tool ` +
81
+ `call carries requestId=${currentRequestId}.`,
82
+ remediation: `Operate under the request the grant is scoped to (requestId=${grantRequestId}), or have ` +
83
+ `the user re-issue the grant unscoped. ${userSideGrant(operation)}`
84
+ };
85
+ }
86
+ export function expiredGrantsDenial(operation) {
87
+ return {
88
+ allow: false,
89
+ code: 'WORKTREE_USER_AUTH_EXPIRED',
90
+ reason: `All grants for operation "${operation}" in this session have expired.`,
91
+ remediation: `${userSideGrant(operation)} (The previous grant expired; the default TTL is 5 minutes.)`
92
+ };
93
+ }
94
+ export function consumedGrantsDenial(operation) {
95
+ return {
96
+ allow: false,
97
+ code: 'WORKTREE_USER_AUTH_REQUIRED',
98
+ reason: `All unexpired grants for operation "${operation}" in this session are already consumed.`,
99
+ remediation: `${userSideGrant(operation)} (The previous grant was single-use and already consumed; a ` +
100
+ `multi-use grant is possible but should be rare.)`
101
+ };
102
+ }
@@ -17,6 +17,6 @@ export declare function matchBaseline(finding: EslintFinding, baseline: readonly
17
17
  export declare function aggregateRedLine(baseline: readonly BaselineViolation[]): readonly RedLineEntry[];
18
18
  export declare const EMPTY_DIFF_RANGE: readonly DiffRange[];
19
19
  export declare const EMPTY_REDLINE: readonly RedLineEntry[];
20
- export declare function emptyResult(state: EslintState, start: number, rawOutput: string): EslintRunResult;
20
+ export declare function emptyResult(state: EslintState, start: number, rawOutput: string, reason?: string): EslintRunResult;
21
21
  export declare function buildEslintArgs(options: EslintRunOptions): string[];
22
22
  export type { DiffRange };
@@ -150,13 +150,14 @@ export function aggregateRedLine(baseline) {
150
150
  }
151
151
  export const EMPTY_DIFF_RANGE = [];
152
152
  export const EMPTY_REDLINE = [];
153
- export function emptyResult(state, start, rawOutput) {
153
+ export function emptyResult(state, start, rawOutput, reason) {
154
154
  return {
155
155
  state,
156
156
  findings: [],
157
157
  summary: { error: 0, warn: 0, info: 0 },
158
158
  durationMs: Date.now() - start,
159
159
  rawOutput,
160
+ ...(reason === undefined ? {} : { reason }),
160
161
  baselineWaived: [],
161
162
  redLine: EMPTY_REDLINE
162
163
  };
@@ -45,6 +45,14 @@ export type EslintRunResult = {
45
45
  readonly summary: EslintSummary;
46
46
  readonly durationMs: number;
47
47
  readonly rawOutput: string;
48
+ /**
49
+ * Why a non-`ok` state was reached. Four different conditions — an
50
+ * unbuildable argument list, a spawn failure, a signal kill (which is how a
51
+ * spawn timeout lands) and unparseable linter output — all reported
52
+ * `execution-failed` and nothing else, so an operator could not tell a
53
+ * timed-out linter from one that emitted rubbish. Absent when `state` is ok.
54
+ */
55
+ readonly reason?: string;
48
56
  readonly baselineWaived: readonly EslintFinding[];
49
57
  readonly redLine: readonly RedLineEntry[];
50
58
  };
@@ -87,7 +87,7 @@ export function runEslint(options) {
87
87
  args = buildEslintArgs(options);
88
88
  }
89
89
  catch (error) {
90
- return emptyResult('execution-failed', start, error instanceof Error ? error.message : String(error));
90
+ return emptyResult('execution-failed', start, error instanceof Error ? error.message : String(error), 'the eslint argument list could not be built');
91
91
  }
92
92
  const projectRoot = resolveProjectRoot(options.cwd);
93
93
  // Invoke eslint via `node <node_modules/eslint/bin/eslint.js>` to bypass
@@ -132,10 +132,23 @@ export function runEslint(options) {
132
132
  if (result.error !== undefined && result.error !== null) {
133
133
  const message = result.error.message;
134
134
  const state = /ENOENT/.test(message) ? 'npx-failed' : 'execution-failed';
135
- return emptyResult(state, start, typeof result.stdout === 'string' ? result.stdout : '');
135
+ // A spawn timeout arrives HERE, as `error.code === 'ETIMEDOUT'` — measured on
136
+ // this host with `--timeout-ms 20000`: the spawn-error branch below wins over
137
+ // the signal branch, because this check comes first and spawnSync sets both.
138
+ // So a timeout must not be reported as "could not be spawned": it was spawned
139
+ // and did not finish, and that difference is the whole diagnosis.
140
+ const timedOut = result.error.code === 'ETIMEDOUT';
141
+ const budgetMs = options.timeoutMs ?? ESLINT_DEFAULT_TIMEOUT_MS;
142
+ return emptyResult(state, start, typeof result.stdout === 'string' ? result.stdout : '', timedOut
143
+ ? `eslint did not finish within the ${budgetMs}ms spawn timeout`
144
+ : `eslint could not be spawned: ${message}`);
136
145
  }
137
146
  if (result.signal !== null && result.signal !== undefined) {
138
- return emptyResult('execution-failed', start, typeof result.stdout === 'string' ? result.stdout : '');
147
+ // A kill that arrived WITHOUT a spawn error — a signal from outside, not the
148
+ // spawn timeout (that one is caught above as ETIMEDOUT). Named so it is not
149
+ // read as linter output that would not parse.
150
+ const budgetMs = options.timeoutMs ?? ESLINT_DEFAULT_TIMEOUT_MS;
151
+ return emptyResult('execution-failed', start, typeof result.stdout === 'string' ? result.stdout : '', `eslint was killed by ${result.signal} after ${Date.now() - start}ms (spawn timeout ${budgetMs}ms)`);
139
152
  }
140
153
  const stdout = typeof result.stdout === 'string' ? result.stdout : '';
141
154
  let findings = [];
@@ -166,7 +179,7 @@ export function runEslint(options) {
166
179
  }
167
180
  }
168
181
  catch {
169
- return emptyResult('execution-failed', start, stdout);
182
+ return emptyResult('execution-failed', start, stdout, `eslint stdout was not valid JSON (${stdout.length} bytes)`);
170
183
  }
171
184
  }
172
185
  if (result.status !== 0 && findings.length === 0) {
@@ -13,6 +13,7 @@
13
13
  * a fake transport instead of reaching the network.
14
14
  */
15
15
  import { getErrorMessage } from 'peaks-loop-shared/result';
16
+ import { estimateTokens } from '../memory/llm-reranker-core.js';
16
17
  /** Public Anthropic endpoint. `ANTHROPIC_BASE_URL` overrides it (gateways, local proxies). */
17
18
  const DEFAULT_BASE_URL = 'https://api.anthropic.com';
18
19
  /** One call is bounded: an unbounded gate is a hung gate. */
@@ -102,6 +103,28 @@ function isTextBlock(block) {
102
103
  function isAbort(error) {
103
104
  return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');
104
105
  }
106
+ /**
107
+ * The two token counts this call reports, and where they came from.
108
+ *
109
+ * `?? 0` used to stand in for an omitted `usage`, which made "the provider
110
+ * reported zero" and "nobody measured" the same number on the wire. When the
111
+ * reply does not carry BOTH counts, the runner falls back to the estimator the
112
+ * repo already has (`llm-reranker-core.ts` `estimateTokens`, 1 token ≈ 4 bytes)
113
+ * over the request body and the returned text, and says so with
114
+ * `source: 'estimated'` rather than leaving the two states indistinguishable.
115
+ */
116
+ function tokenCounts(usage, requestBody, text) {
117
+ const input = usage?.input_tokens;
118
+ const output = usage?.output_tokens;
119
+ if (typeof input !== 'number' || typeof output !== 'number') {
120
+ return {
121
+ input: estimateTokens(requestBody),
122
+ output: estimateTokens(text),
123
+ source: 'estimated'
124
+ };
125
+ }
126
+ return { input, output, source: 'provider' };
127
+ }
105
128
  export function createAnthropicRunner(config, options = {}) {
106
129
  const fetchImpl = options.fetchImpl ?? defaultFetch;
107
130
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -153,13 +176,7 @@ export function createAnthropicRunner(config, options = {}) {
153
176
  if (!output) {
154
177
  throw new LlmRequestError(`LLM reply from ${url} carried no text block`);
155
178
  }
156
- return {
157
- output,
158
- tokens: {
159
- input: payload.usage?.input_tokens ?? 0,
160
- output: payload.usage?.output_tokens ?? 0
161
- }
162
- };
179
+ return { output, tokens: tokenCounts(payload.usage, body, output) };
163
180
  }
164
181
  };
165
182
  }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The loop runtime's two observability emissions: the monotonic guard's verdict
3
+ * for a cycle, and that cycle's own outcome.
4
+ *
5
+ * WHY BOTH MAPPINGS LIVE HERE. The two producers cannot emit for themselves:
6
+ * `checkMonotonicImprovement` is pure (no project root, no session id —
7
+ * `monotonic-guard.ts:83`), and the cycle bookkeeping in `runLoopLocked` has no
8
+ * emitter. So the emit happens in the callers, and the callers are two files.
9
+ * The mapping from loop state to event vocabulary is decided ONCE, here, rather
10
+ * than re-derived at each call site.
11
+ *
12
+ * Fire-and-forget by contract: whatever `emitObservabilityEvent` returns
13
+ * (`written: false` on every error path) is dropped, and neither helper throws.
14
+ */
15
+ import type { MonotonicReport } from './monotonic-guard.js';
16
+ /**
17
+ * `monotonic-trigger` — once per computed report, from each caller of
18
+ * `checkMonotonicImprovement`, which is pure and cannot emit for itself.
19
+ *
20
+ * `pass` → `report: 'pass'`; `block` → `report: 'block'`; `action` is the
21
+ * report's own `code`, a vocabulary the guard already produces
22
+ * (`MONOTONIC_OK` / `MONOTONIC_VIOLATION` / `MONOTONIC_NO_PREVIOUS` /
23
+ * `MONOTONIC_INCOMPARABLE_EVALUATORS`). **`skip` emits NOTHING**: nothing was
24
+ * guarded, so counting it would make the counter track "how often the guard ran"
25
+ * instead of "how often a monotonic condition fired". `'warn'` stays unused —
26
+ * the guard cannot return it, and it is not repurposed here.
27
+ */
28
+ export declare function emitMonotonicReport(projectRoot: string, sid: string, report: MonotonicReport): void;
29
+ /**
30
+ * `cycle` — exactly ONE event per cycle, at the end of the iteration.
31
+ *
32
+ * One, not two: `aggregateDashboardMetrics` counts events, not distinct cycle
33
+ * ids (`aggregation.ts:212`), so emitting `'started'` alongside this one would
34
+ * double `cycleCount`. `'started'` therefore stays unused. `status` is
35
+ * `'failed'` for the cycle whose report carries the violation — the same
36
+ * condition `runLoopLocked` aborts on — and `'completed'` otherwise, so
37
+ * `cycleCount` equals the number of cycles the driver actually ran.
38
+ */
39
+ export declare function emitCycleOutcome(projectRoot: string, sid: string, cycle: number, report: MonotonicReport): void;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The loop runtime's two observability emissions: the monotonic guard's verdict
3
+ * for a cycle, and that cycle's own outcome.
4
+ *
5
+ * WHY BOTH MAPPINGS LIVE HERE. The two producers cannot emit for themselves:
6
+ * `checkMonotonicImprovement` is pure (no project root, no session id —
7
+ * `monotonic-guard.ts:83`), and the cycle bookkeeping in `runLoopLocked` has no
8
+ * emitter. So the emit happens in the callers, and the callers are two files.
9
+ * The mapping from loop state to event vocabulary is decided ONCE, here, rather
10
+ * than re-derived at each call site.
11
+ *
12
+ * Fire-and-forget by contract: whatever `emitObservabilityEvent` returns
13
+ * (`written: false` on every error path) is dropped, and neither helper throws.
14
+ */
15
+ import { emitCycleEvent, emitMonotonicTriggerEvent } from '../observability/observability-service.js';
16
+ /**
17
+ * `monotonic-trigger` — once per computed report, from each caller of
18
+ * `checkMonotonicImprovement`, which is pure and cannot emit for itself.
19
+ *
20
+ * `pass` → `report: 'pass'`; `block` → `report: 'block'`; `action` is the
21
+ * report's own `code`, a vocabulary the guard already produces
22
+ * (`MONOTONIC_OK` / `MONOTONIC_VIOLATION` / `MONOTONIC_NO_PREVIOUS` /
23
+ * `MONOTONIC_INCOMPARABLE_EVALUATORS`). **`skip` emits NOTHING**: nothing was
24
+ * guarded, so counting it would make the counter track "how often the guard ran"
25
+ * instead of "how often a monotonic condition fired". `'warn'` stays unused —
26
+ * the guard cannot return it, and it is not repurposed here.
27
+ */
28
+ export function emitMonotonicReport(projectRoot, sid, report) {
29
+ if (report.status === 'skip')
30
+ return;
31
+ emitMonotonicTriggerEvent({
32
+ projectRoot,
33
+ sessionId: sid,
34
+ report: report.status,
35
+ action: report.code
36
+ });
37
+ }
38
+ /**
39
+ * `cycle` — exactly ONE event per cycle, at the end of the iteration.
40
+ *
41
+ * One, not two: `aggregateDashboardMetrics` counts events, not distinct cycle
42
+ * ids (`aggregation.ts:212`), so emitting `'started'` alongside this one would
43
+ * double `cycleCount`. `'started'` therefore stays unused. `status` is
44
+ * `'failed'` for the cycle whose report carries the violation — the same
45
+ * condition `runLoopLocked` aborts on — and `'completed'` otherwise, so
46
+ * `cycleCount` equals the number of cycles the driver actually ran.
47
+ */
48
+ export function emitCycleOutcome(projectRoot, sid, cycle, report) {
49
+ emitCycleEvent({
50
+ projectRoot,
51
+ sessionId: sid,
52
+ cycle,
53
+ status: report.monotonicityViolation ? 'failed' : 'completed'
54
+ });
55
+ }
@@ -13,6 +13,8 @@
13
13
  *
14
14
  * File budget: ≤ 800 lines (Karpathy §2).
15
15
  */
16
+ import { readFileSync, readdirSync } from 'node:fs';
17
+ import { join } from 'node:path';
16
18
  /** Score normalisation — gateAction maps to a 0..1 score:
17
19
  * pass → 1.0
18
20
  * warn → 0.5
@@ -148,15 +150,10 @@ function classifyFsError(err) {
148
150
  * .peaks/_sub_agents/<sid>/shared/ 跨批 signal → 不 crash").
149
151
  * Pure helper; only present for the cross-session case. */
150
152
  export function loadCrossSessionSignal(projectRoot, sid) {
151
- // Lazily import so unit tests in non-windows environments don't pull
152
- // node:fs through a static `import` (test envs stay small).
153
- // eslint-disable-next-line @typescript-eslint/no-var-requires
154
- const fs = require('node:fs');
155
- const path = require('node:path');
156
- const sharedDir = path.join(projectRoot, '.peaks', '_sub_agents', sid, 'shared');
153
+ const sharedDir = join(projectRoot, '.peaks', '_sub_agents', sid, 'shared');
157
154
  const readdir = (() => {
158
155
  try {
159
- return { ok: true, value: fs.readdirSync(sharedDir) };
156
+ return { ok: true, value: readdirSync(sharedDir) };
160
157
  }
161
158
  catch (err) {
162
159
  return { ok: false, reason: classifyFsError(err) };
@@ -177,10 +174,10 @@ export function loadCrossSessionSignal(projectRoot, sid) {
177
174
  }
178
175
  if (best === null)
179
176
  return null;
180
- const target = path.join(sharedDir, `cycle-${best}.json`);
177
+ const target = join(sharedDir, `cycle-${best}.json`);
181
178
  const readFile = (() => {
182
179
  try {
183
- return { ok: true, value: fs.readFileSync(target, 'utf8') };
180
+ return { ok: true, value: readFileSync(target, 'utf8') };
184
181
  }
185
182
  catch (err) {
186
183
  return { ok: false, reason: classifyFsError(err) };
@@ -21,10 +21,12 @@
21
21
  *
22
22
  * File budget: ≤ 800 lines (Karpathy §2).
23
23
  */
24
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
24
25
  import { join } from 'node:path';
25
26
  import { dispatchEvaluator } from './evaluator-dispatcher.js';
26
27
  import { checkMonotonicImprovement, toScoreRow, DEFAULT_MONOTONIC_THRESHOLD } from './monotonic-guard.js';
27
28
  import { appendMetricLine, readMetricLines } from '../observability/jsonl-store.js';
29
+ import { emitMonotonicReport } from './loop-observability.js';
28
30
  import { findProjectRoot } from '../config/config-safety.js';
29
31
  import { classifyFsError, MONOTONIC_CYCLE_KIND, WALKED_EVALUATORS } from './monotonic-runner-types.js';
30
32
  /** Resolve the slice dir — kept for API/BC (run-driver.ts uses it to
@@ -112,15 +114,11 @@ function loadMostRecentCycleFromSubAgents(projectRoot, sid, rid) {
112
114
  return loadMostRecentCycleFromDir(dir, rid);
113
115
  }
114
116
  function loadMostRecentCycleFromDir(dir, rid) {
115
- // Lazily import so unit tests in non-windows environments don't pull
116
- // node:fs through a static `import`.
117
- // eslint-disable-next-line @typescript-eslint/no-var-requires
118
- const fs = require('node:fs');
119
- if (!fs.existsSync(dir))
117
+ if (!existsSync(dir))
120
118
  return null;
121
119
  const readdir = (() => {
122
120
  try {
123
- return { ok: true, value: fs.readdirSync(dir) };
121
+ return { ok: true, value: readdirSync(dir) };
124
122
  }
125
123
  catch (err) {
126
124
  return { ok: false, reason: classifyFsError(err) };
@@ -143,7 +141,7 @@ function loadMostRecentCycleFromDir(dir, rid) {
143
141
  const target = join(dir, `cycle-${bestCycle}.json`);
144
142
  const readFile = (() => {
145
143
  try {
146
- return { ok: true, value: fs.readFileSync(target, 'utf8') };
144
+ return { ok: true, value: readFileSync(target, 'utf8') };
147
145
  }
148
146
  catch (err) {
149
147
  return { ok: false, reason: classifyFsError(err) };
@@ -222,6 +220,9 @@ export function runMonotonicCheck(options) {
222
220
  const currentCycle = { cycle, scores: rows };
223
221
  const previousCycle = loadPreviousCycle(options.projectRoot, options.sid, options.rid);
224
222
  const report = checkMonotonicImprovement(previousCycle, currentCycle, { threshold });
223
+ // The guard is pure and holds no session binding, so its caller emits, one
224
+ // line after the verdict exists.
225
+ emitMonotonicReport(options.projectRoot, options.sid, report);
225
226
  let persistedAt = null;
226
227
  const envelopeWarns = [];
227
228
  if (persist) {