peaks-loop 4.1.26 → 4.2.1

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 (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +160 -0
  3. package/contracts/readonly-argv-whitelist.json +116 -0
  4. package/dist/cli/commands/code-auto-compact-command.js +15 -3
  5. package/dist/cli/commands/core/session-info-command.js +3 -4
  6. package/dist/cli/commands/core/skill-presence-housekeeping-commands.js +7 -1
  7. package/dist/cli/commands/dashboard-long-run.js +2 -1
  8. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  9. package/dist/cli/commands/job-state-root.js +4 -2
  10. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  11. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  12. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  13. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  14. package/dist/cli/commands/mut-commands-helpers.js +53 -80
  15. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  16. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  17. package/dist/cli/commands/outer-cache-commands.js +3 -2
  18. package/dist/cli/commands/playwright-session-store.js +5 -2
  19. package/dist/cli/commands/project-context-command.js +7 -2
  20. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  21. package/dist/cli/commands/request-transition-preflight.js +2 -2
  22. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  23. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  24. package/dist/cli/commands/workspace/init-actions.js +5 -0
  25. package/dist/cli/commands/workspace/init-context.js +1 -0
  26. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  27. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  28. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  29. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  30. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  31. package/dist/cli/commands/worktree-lease-git.js +21 -44
  32. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  33. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  34. package/dist/cli/commands/worktree-lease-load.js +37 -9
  35. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  36. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  37. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  38. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  39. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  40. package/dist/cli/commands/worktree-lease-session.js +9 -6
  41. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  42. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  43. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  44. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  45. package/dist/cli/commands/worktree-lease-store.js +3 -2
  46. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  47. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  48. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  49. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  50. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  51. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  52. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  53. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  54. package/dist/services/capability-audit-service/runner.js +4 -1
  55. package/dist/services/capability-baseline/store.js +2 -1
  56. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  57. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  58. package/dist/services/code/auto-compact-artifacts.js +42 -10
  59. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  60. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  61. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  62. package/dist/services/code/auto-compact-envelopes.js +18 -4
  63. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  64. package/dist/services/code/emit-handoff.js +8 -1
  65. package/dist/services/code/job-shape-decision.js +13 -2
  66. package/dist/services/code/job-shape-provisional.js +9 -1
  67. package/dist/services/code/post-compact-detector.js +9 -1
  68. package/dist/services/code/step-08-session-readers.js +14 -5
  69. package/dist/services/compact/request-transition-hook.js +6 -1
  70. package/dist/services/compact/suggest-service.js +8 -1
  71. package/dist/services/context/post-compact-reinjection.js +15 -14
  72. package/dist/services/context/spillover-store.js +2 -1
  73. package/dist/services/dispatch/contract-store.d.ts +11 -4
  74. package/dist/services/dispatch/contract-store.js +21 -8
  75. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  76. package/dist/services/doctor/doctor-service/index.js +2 -1
  77. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  78. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  79. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  80. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  81. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  82. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  83. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  84. package/dist/services/loop/monotonic-runner.js +2 -1
  85. package/dist/services/loop/spec-service.js +10 -9
  86. package/dist/services/mcp/context-tool.d.ts +3 -0
  87. package/dist/services/mcp/context-tool.js +135 -0
  88. package/dist/services/mcp/surface.js +7 -1
  89. package/dist/services/mcp/tools.js +3 -1
  90. package/dist/services/memory/project-context-service.d.ts +10 -1
  91. package/dist/services/memory/project-context-service.js +13 -6
  92. package/dist/services/observability/jsonl-store.js +4 -1
  93. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  94. package/dist/services/prd/prd-blocks-checker.js +12 -6
  95. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  96. package/dist/services/prd/project-scan-body-tables.js +185 -0
  97. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  98. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  99. package/dist/services/prd/project-scan-content.d.ts +24 -0
  100. package/dist/services/prd/project-scan-content.js +207 -0
  101. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  102. package/dist/services/prd/project-scan-existing-state.js +61 -0
  103. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  104. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  105. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  106. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  107. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  108. package/dist/services/prd/project-scan-library-versions.js +135 -0
  109. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  110. package/dist/services/prd/project-scan-techstack.js +167 -0
  111. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  112. package/dist/services/sc/sc-service.js +8 -8
  113. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  114. package/dist/services/scan/api-diff-recorded.js +5 -5
  115. package/dist/services/session/binding-status-service.js +2 -1
  116. package/dist/services/session/binding-store.js +6 -7
  117. package/dist/services/session/caller-binding-service.js +5 -2
  118. package/dist/services/session/getSessionDir.d.ts +4 -0
  119. package/dist/services/session/getSessionDir.js +38 -13
  120. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  121. package/dist/services/session/session-binding-bridge.js +13 -13
  122. package/dist/services/session/session-checkpoint-service.js +22 -3
  123. package/dist/services/session/session-manager.js +16 -20
  124. package/dist/services/skills/presence-lease-resolver.js +3 -2
  125. package/dist/services/skills/presence-lease-service.js +7 -15
  126. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  127. package/dist/services/skills/presence-lease-store.js +60 -5
  128. package/dist/services/skills/skill-presence-service.js +13 -20
  129. package/dist/services/skills/skill-statusline-model.js +7 -2
  130. package/dist/services/slice/slice-archive-service.js +4 -1
  131. package/dist/services/standards/missing-standards-detector.js +2 -1
  132. package/dist/services/test-cache/test-cache-service.js +2 -1
  133. package/dist/services/workflow/artifact-paths.js +6 -2
  134. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  135. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  136. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  137. package/dist/services/workflow/workflow-state-store.js +11 -4
  138. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  139. package/dist/services/workspace/reconcile-migrate.js +2 -2
  140. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  141. package/dist/services/workspace/reconcile-service.js +11 -11
  142. package/dist/services/workspace/workspace-service.js +5 -5
  143. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  144. package/dist/services/worktree/dispatch-provenance.js +9 -2
  145. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  146. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  147. package/dist/shared/runtime-root.js +6 -1
  148. package/package.json +6 -5
  149. package/skills/peaks-code/SKILL.md +1 -1
  150. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
  151. package/skills/peaks-mut/SKILL.md +6 -2
  152. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  153. package/dist/services/worktree/git-worktree-parser.js +0 -55
  154. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  155. package/dist/services/worktree/worktree-lease-types.js +0 -9
  156. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  157. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -2,12 +2,13 @@
2
2
  * `peaks mut` — command builders and helper functions.
3
3
  *
4
4
  * Originally extracted from `mut-commands.ts` (file-size cap campaign).
5
- * It holds the stub-report factories, the summary emitter, the named-error
6
- * mapping, and — after the `max-lines-per-function` rule was measured at
7
- * 209 code lines for `createMutCommands` — the three subcommand builders
8
- * that drive the mutation pipeline (`run`, `mutants`, `asserts`).
5
+ * It holds the stub-report factories, the summary emitter and — after the
6
+ * `max-lines-per-function` rule was measured at 209 code lines for
7
+ * `createMutCommands` — the three subcommand builders that drive the
8
+ * mutation pipeline (`run`, `mutants`, `asserts`).
9
9
  * The `report` subcommand — a pure reader of an already-written file —
10
- * lives with the CLI surface in `mut-commands.ts`.
10
+ * lives with the CLI surface in `mut-commands.ts`; the named-error mapping
11
+ * and the failure diagnostic live in `mut-failure-diagnostic.ts`.
11
12
  *
12
13
  * The named-error part exists for R7: a missing or unloadable mutation
13
14
  * toolchain must surface a MACHINE-READABLE error code (for example
@@ -18,15 +19,7 @@
18
19
  */
19
20
  import { Command } from 'commander';
20
21
  import { assertTestFilesUsable, buildMutReport, runMutation, scanAssertions } from 'peaks-loop-mut';
21
- import { printErrorEnvelope } from '../cli-helpers.js';
22
- /**
23
- * Fallback code for a mutation failure that carries no named code of its
24
- * own. The production invoker raises the specific codes; anything that
25
- * escapes it without one still gets a stable, greppable name.
26
- */
27
- export const MUT_CLI_ERROR_CODE = 'MUT_FAILED';
28
- /** Named mutation codes are always `MUT_` + upper snake case. */
29
- const NAMED_CODE_PATTERN = /^MUT_[A-Z0-9_]+$/;
22
+ import { emitMutError, mutationFailureLogPath } from './mut-failure-diagnostic.js';
30
23
  /**
31
24
  * The IO the mut family writes to when the caller injects none. Same
32
25
  * shape as `src/cli/program.ts`'s default sinks: one trailing newline
@@ -78,36 +71,6 @@ export function emitSummary(io, json, payload) {
78
71
  }
79
72
  io.stdout(`mut-report.json: ${payload.path}\nsha256: ${payload.sha256}\npassed: ${payload.passed}`);
80
73
  }
81
- /**
82
- * Read the machine-readable code off a failure. The production invoker
83
- * raises named codes (`MUT_TOOLCHAIN_UNAVAILABLE`, `MUT_NO_MUTANTS`,
84
- * `MUT_MUTATE_PATTERN_REQUIRED`, …) and `runMutation` preserves them
85
- * while wrapping. Anything without a recognised code falls back to
86
- * `MUT_FAILED` so the envelope is never anonymous.
87
- */
88
- export function mutErrorCode(err) {
89
- if (err && typeof err === 'object' && 'code' in err) {
90
- const code = err.code;
91
- if (typeof code === 'string' && NAMED_CODE_PATTERN.test(code)) {
92
- return code;
93
- }
94
- }
95
- return MUT_CLI_ERROR_CODE;
96
- }
97
- /** The human-readable half of the envelope. */
98
- export function mutErrorMessage(err) {
99
- return err instanceof Error ? err.message : String(err);
100
- }
101
- /**
102
- * Emit the failure envelope on stderr and set a non-zero exit code. Its
103
- * `data` field carries the machine-readable detail — where an ABSOLUTE path
104
- * belongs; stdout stays reserved for the `--json` payload (R6).
105
- */
106
- export function emitMutError(io, err) {
107
- const details = err?.details;
108
- const data = details && typeof details === 'object' ? details : {};
109
- printErrorEnvelope(io, 'mut', mutErrorCode(err), mutErrorMessage(err), data, []);
110
- }
111
74
  /**
112
75
  * Validate `--test-files` BEFORE any Stryker run, scan or report write: a
113
76
  * missing path must fail with the named code, never reach the mutation
@@ -125,48 +88,55 @@ function assertMutTestFiles(a) {
125
88
  .requiredOption('--project <path>', 'project root')
126
89
  .requiredOption('--test-files <files...>', 'test files to mutate against')
127
90
  .option('--mutate <patterns...>', 'source patterns to mutate, relative to --project')
91
+ .option('--ignore <patterns...>', 'paths or globs NOT to copy into the Stryker sandbox')
128
92
  .requiredOption('--input-sig <hex>', 'TACT.sig (sha256) for chain')
129
93
  .requiredOption('--session-id <sid>', 'session id; CLI writes artifacts only under .peaks/_runtime/<sid>/mut/ (one-axis layout)')
130
94
  .requiredOption('--out <path>', 'output path for mut-report.json')
131
95
  .option('--json', 'machine-readable output', false)
132
96
  .action(async (a) => {
133
- try {
134
- assertMutTestFiles(a);
135
- const { mutation } = await runMutation({
136
- project: a.project,
137
- testFiles: a.testFiles,
138
- mutate: a.mutate ?? [],
139
- invokeStryker
140
- });
141
- const assertions = await scanAssertions({
142
- project: a.project,
143
- testFiles: a.testFiles
144
- });
145
- const report = await buildMutReport({
146
- inputSig: a.inputSig,
147
- out: a.out,
148
- mutation,
149
- assertions
150
- });
151
- emitSummary(io, a.json, {
152
- ok: true,
153
- sha256: report.sha256,
154
- passed: report.thresholds.passed,
155
- path: a.out
156
- });
157
- if (!report.thresholds.passed) {
158
- // H6: CLI裁决 — threshold breach is a non-zero exit so callers
159
- // (peaks-rd, peaks-qa, CI) can block on it without parsing stdout.
160
- process.exitCode = 1;
161
- }
162
- }
163
- catch (err) {
164
- // R7: a named code + actionable message + non-zero exit, never an
165
- // UNHANDLED_ERROR envelope with a bare "Cannot find package".
166
- emitMutError(io, err);
167
- }
97
+ await runMutRunAction(a, invokeStryker, io);
168
98
  });
169
99
  }
100
+ /** The `run` action body, split out so the builder stays inside its line budget. */
101
+ async function runMutRunAction(a, invokeStryker, io) {
102
+ try {
103
+ assertMutTestFiles(a);
104
+ const { mutation } = await runMutation({
105
+ project: a.project,
106
+ testFiles: a.testFiles,
107
+ mutate: a.mutate ?? [],
108
+ ignorePatterns: a.ignore ?? [],
109
+ sessionId: a.sessionId,
110
+ invokeStryker
111
+ });
112
+ const assertions = await scanAssertions({
113
+ project: a.project,
114
+ testFiles: a.testFiles
115
+ });
116
+ const report = await buildMutReport({
117
+ inputSig: a.inputSig,
118
+ out: a.out,
119
+ mutation,
120
+ assertions
121
+ });
122
+ emitSummary(io, a.json, {
123
+ ok: true,
124
+ sha256: report.sha256,
125
+ passed: report.thresholds.passed,
126
+ path: a.out
127
+ });
128
+ if (!report.thresholds.passed) {
129
+ // H6: CLI裁决 — threshold breach is a non-zero exit so callers
130
+ // (peaks-rd, peaks-qa, CI) can block on it without parsing stdout.
131
+ process.exitCode = 1;
132
+ }
133
+ }
134
+ catch (err) {
135
+ // R7: a named code + actionable message + non-zero exit, never an
136
+ // UNHANDLED_ERROR envelope with a bare "Cannot find package".
137
+ emitMutError(io, err, mutationFailureLogPath(a.out));
138
+ }
139
+ }
170
140
  /**
171
141
  * `peaks mut mutants` — Stryker only; writes a stub-assertions
172
142
  * mut-report.json. One-axis: --session-id required.
@@ -177,6 +147,7 @@ export function buildMutMutantsCommand(invokeStryker, io) {
177
147
  .requiredOption('--project <path>', 'project root')
178
148
  .requiredOption('--test-files <files...>', 'test files to mutate against')
179
149
  .option('--mutate <patterns...>', 'source patterns to mutate, relative to --project')
150
+ .option('--ignore <patterns...>', 'paths or globs NOT to copy into the Stryker sandbox')
180
151
  .requiredOption('--input-sig <hex>', 'TACT.sig')
181
152
  .requiredOption('--session-id <sid>', 'session id')
182
153
  .requiredOption('--out <path>', 'output path for mut-report.json')
@@ -188,6 +159,8 @@ export function buildMutMutantsCommand(invokeStryker, io) {
188
159
  project: a.project,
189
160
  testFiles: a.testFiles,
190
161
  mutate: a.mutate ?? [],
162
+ ignorePatterns: a.ignore ?? [],
163
+ sessionId: a.sessionId,
191
164
  invokeStryker
192
165
  });
193
166
  const report = await buildMutReport({
@@ -207,7 +180,7 @@ export function buildMutMutantsCommand(invokeStryker, io) {
207
180
  }
208
181
  }
209
182
  catch (err) {
210
- emitMutError(io, err);
183
+ emitMutError(io, err, mutationFailureLogPath(a.out));
211
184
  }
212
185
  });
213
186
  }
@@ -0,0 +1,48 @@
1
+ import { type ProgramIO } from '../cli-helpers.js';
2
+ /**
3
+ * Fallback code for a mutation failure that carries no named code of its
4
+ * own. The production invoker raises the specific codes; anything that
5
+ * escapes it without one still gets a stable, greppable name.
6
+ */
7
+ export declare const MUT_CLI_ERROR_CODE = "MUT_FAILED";
8
+ /**
9
+ * Read the machine-readable code off a failure. The production invoker
10
+ * raises named codes (`MUT_TOOLCHAIN_UNAVAILABLE`, `MUT_NO_MUTANTS`,
11
+ * `MUT_MUTATE_PATTERN_REQUIRED`, …) and `runMutation` preserves them
12
+ * while wrapping. Anything without a recognised code falls back to
13
+ * `MUT_FAILED` so the envelope is never anonymous.
14
+ */
15
+ export declare function mutErrorCode(err: unknown): string;
16
+ /** The human-readable half of the envelope. */
17
+ export declare function mutErrorMessage(err: unknown): string;
18
+ /**
19
+ * Emit the failure envelope on stderr and set a non-zero exit code. Its
20
+ * `data` field carries the machine-readable detail — where an ABSOLUTE path
21
+ * belongs; stdout stays reserved for the `--json` payload (R6).
22
+ *
23
+ * `diagnosticPath` is set by the Stryker-backed subcommands. When it is
24
+ * given the failure is ALSO written to that file, together with Stryker's
25
+ * own file log when the invoker captured one. The path is then named in the
26
+ * envelope's `data` and `nextActions` so the next caller does not have to
27
+ * guess it.
28
+ */
29
+ export declare function emitMutError(io: ProgramIO, err: unknown, diagnosticPath?: string): void;
30
+ /**
31
+ * Where a failed Stryker run writes its diagnostic — NEXT TO the report the
32
+ * run was going to produce, so both artifacts of one run live together.
33
+ */
34
+ export declare function mutationFailureLogPath(outPath: string): string;
35
+ /**
36
+ * What became of the diagnostic write. A discriminated result rather than
37
+ * `string | undefined`, so a caller cannot mistake a failed write for "no
38
+ * diagnostic requested" — and a diagnostic must never mask the original error.
39
+ */
40
+ export type MutDiagnosticResult = {
41
+ readonly ok: true;
42
+ readonly path: string;
43
+ } | {
44
+ readonly ok: false;
45
+ readonly reason: string;
46
+ };
47
+ /** Persist the failure; the reason a write failed is kept, not swallowed. */
48
+ export declare function writeMutFailureDiagnostic(path: string, err: unknown, details: Record<string, unknown>): MutDiagnosticResult;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * The failure surface of `peaks mut` — the named-error mapping and the
3
+ * diagnostic file a failed Stryker run leaves behind.
4
+ *
5
+ * WHY IT IS ITS OWN MODULE
6
+ * -------------------------
7
+ * R7 needs a MACHINE-READABLE error code (for example
8
+ * `MUT_TOOLCHAIN_UNAVAILABLE`) plus an actionable message and a non-zero
9
+ * exit code — never `UNHANDLED_ERROR` with a bare "Cannot find package".
10
+ * The Stryker-backed subcommands ALSO need the failure written down:
11
+ * Stryker reports several distinct failures as the bare
12
+ * "Something went wrong in the initial test run", and because the runner
13
+ * keeps its console log off (`logLevel: 'off'`, stdout belongs to the
14
+ * `--json` envelope) its own file log is the only place the real reason
15
+ * appears. The production invoker captures that log into the error's
16
+ * `details.strykerLog`; this module turns the error into the file and the
17
+ * envelope that points at it.
18
+ *
19
+ * Split out of `mut-commands-helpers.ts` for the `src/` raw-line cap (300).
20
+ */
21
+ import { mkdirSync, writeFileSync } from 'node:fs';
22
+ import { dirname, join, resolve } from 'node:path';
23
+ import { printErrorEnvelope } from '../cli-helpers.js';
24
+ /**
25
+ * Fallback code for a mutation failure that carries no named code of its
26
+ * own. The production invoker raises the specific codes; anything that
27
+ * escapes it without one still gets a stable, greppable name.
28
+ */
29
+ export const MUT_CLI_ERROR_CODE = 'MUT_FAILED';
30
+ /** Named mutation codes are always `MUT_` + upper snake case. */
31
+ const NAMED_CODE_PATTERN = /^MUT_[A-Z0-9_]+$/;
32
+ /** How many `cause` links the diagnostic walks before it stops. */
33
+ const MAX_CAUSE_DEPTH = 4;
34
+ /**
35
+ * Read the machine-readable code off a failure. The production invoker
36
+ * raises named codes (`MUT_TOOLCHAIN_UNAVAILABLE`, `MUT_NO_MUTANTS`,
37
+ * `MUT_MUTATE_PATTERN_REQUIRED`, …) and `runMutation` preserves them
38
+ * while wrapping. Anything without a recognised code falls back to
39
+ * `MUT_FAILED` so the envelope is never anonymous.
40
+ */
41
+ export function mutErrorCode(err) {
42
+ if (err && typeof err === 'object' && 'code' in err) {
43
+ const code = err.code;
44
+ if (typeof code === 'string' && NAMED_CODE_PATTERN.test(code)) {
45
+ return code;
46
+ }
47
+ }
48
+ return MUT_CLI_ERROR_CODE;
49
+ }
50
+ /** The human-readable half of the envelope. */
51
+ export function mutErrorMessage(err) {
52
+ return err instanceof Error ? err.message : String(err);
53
+ }
54
+ /**
55
+ * Emit the failure envelope on stderr and set a non-zero exit code. Its
56
+ * `data` field carries the machine-readable detail — where an ABSOLUTE path
57
+ * belongs; stdout stays reserved for the `--json` payload (R6).
58
+ *
59
+ * `diagnosticPath` is set by the Stryker-backed subcommands. When it is
60
+ * given the failure is ALSO written to that file, together with Stryker's
61
+ * own file log when the invoker captured one. The path is then named in the
62
+ * envelope's `data` and `nextActions` so the next caller does not have to
63
+ * guess it.
64
+ */
65
+ export function emitMutError(io, err, diagnosticPath) {
66
+ const details = mutErrorDetails(err);
67
+ const written = diagnosticPath
68
+ ? writeMutFailureDiagnostic(diagnosticPath, err, details)
69
+ : undefined;
70
+ // Stryker's log can be large; it belongs in the file, not in stderr.
71
+ const data = { ...details };
72
+ delete data.strykerLog;
73
+ if (written?.ok) {
74
+ data.diagnosticPath = written.path;
75
+ }
76
+ else if (written) {
77
+ // The original failure stays primary; this only says the file is absent.
78
+ data.diagnosticWriteFailure = written.reason;
79
+ }
80
+ printErrorEnvelope(io, 'mut', mutErrorCode(err), mutErrorMessage(err), data, written?.ok ? [`Read the Stryker diagnostic log at ${written.path}`] : []);
81
+ }
82
+ /** The machine-readable `details` an invoker attached to its error, if any. */
83
+ function mutErrorDetails(err) {
84
+ const details = err?.details;
85
+ return details && typeof details === 'object' ? { ...details } : {};
86
+ }
87
+ /**
88
+ * Where a failed Stryker run writes its diagnostic — NEXT TO the report the
89
+ * run was going to produce, so both artifacts of one run live together.
90
+ */
91
+ export function mutationFailureLogPath(outPath) {
92
+ return join(dirname(resolve(outPath)), 'stryker-failure.log');
93
+ }
94
+ /** Persist the failure; the reason a write failed is kept, not swallowed. */
95
+ export function writeMutFailureDiagnostic(path, err, details) {
96
+ try {
97
+ mkdirSync(dirname(path), { recursive: true });
98
+ writeFileSync(path, renderMutFailureLog(err, details), 'utf8');
99
+ return { ok: true, path };
100
+ }
101
+ catch (writeError) {
102
+ const reason = writeError instanceof Error ? writeError.message : String(writeError);
103
+ return { ok: false, reason };
104
+ }
105
+ }
106
+ /** The diagnostic file's body: what failed, and whatever Stryker logged. */
107
+ function renderMutFailureLog(err, details) {
108
+ const lines = [
109
+ '# peaks mut failure diagnostic',
110
+ `time: ${new Date().toISOString()}`,
111
+ `code: ${mutErrorCode(err)}`,
112
+ `message: ${mutErrorMessage(err)}`,
113
+ '',
114
+ '## Error',
115
+ err instanceof Error ? (err.stack ?? err.message) : String(err)
116
+ ];
117
+ const causes = describeCauses(err);
118
+ if (causes.length > 0) {
119
+ lines.push('', '## Cause chain', ...causes);
120
+ }
121
+ const strykerLog = details.strykerLog;
122
+ if (typeof strykerLog === 'string' && strykerLog.trim().length > 0) {
123
+ lines.push('', '## Stryker log', strykerLog.trimEnd());
124
+ }
125
+ return `${lines.join('\n')}\n`;
126
+ }
127
+ /** The `cause` chain of an error, nearest first. Bounded so it cannot loop. */
128
+ function describeCauses(err, depth = 0) {
129
+ if (depth >= MAX_CAUSE_DEPTH || !err || typeof err !== 'object') {
130
+ return [];
131
+ }
132
+ const cause = err.cause;
133
+ if (!cause) {
134
+ return [];
135
+ }
136
+ return [describeCause(cause), ...describeCauses(cause, depth + 1)];
137
+ }
138
+ /** `Error`s keep their stack; anything else is serialised, never stringified blind. */
139
+ function describeCause(cause) {
140
+ if (cause instanceof Error) {
141
+ return cause.stack ?? cause.message;
142
+ }
143
+ if (typeof cause === 'string') {
144
+ return cause;
145
+ }
146
+ return JSON.stringify(cause) ?? 'unserialisable cause';
147
+ }
@@ -27,12 +27,13 @@
27
27
  import { existsSync, readFileSync } from 'node:fs';
28
28
  import { join } from 'node:path';
29
29
  import { fail, ok } from 'peaks-loop-shared/result';
30
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
30
31
  import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
31
32
  import { addJsonOption, printResult } from '../cli-helpers.js';
32
33
  import { findProjectRoot } from '../../services/config/config-safety.js';
33
- const OUTER_SESSION_CACHE_REL = join('.peaks', '_runtime', '.outer-session-cache.json');
34
+ const OUTER_SESSION_CACHE_FILE = '.outer-session-cache.json';
34
35
  function resolveCachePath(projectRoot) {
35
- return join(projectRoot, OUTER_SESSION_CACHE_REL);
36
+ return join(defaultStateRoot(projectRoot), OUTER_SESSION_CACHE_FILE);
36
37
  }
37
38
  function readEnvOuter() {
38
39
  const peaks = process.env.PEAKS_OUTER_SESSION_ID;
@@ -9,6 +9,7 @@ import { spawn } from 'node:child_process';
9
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, unlinkSync } from 'node:fs';
10
10
  import net from 'node:net';
11
11
  import { join, dirname, resolve } from 'node:path';
12
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
12
13
  import { isUnsafePathInput } from '../../shared/path-safety.js';
13
14
  export const DEFAULT_PORT = 8931;
14
15
  export const MAX_PORT = 8949;
@@ -22,8 +23,10 @@ const TERMINAL_HASH_CHARS = 16;
22
23
  const TERMINAL_ID_MAX_CHARS = 64;
23
24
  export const BROWSERS = ['chromium', 'firefox', 'webkit'];
24
25
  export const PLAYWRIGHT_SESSIONS_DIR = 'playwright-sessions';
26
+ /** The runtime root's non-session child holding per-terminal browser profiles. */
27
+ const PLAYWRIGHT_USERDATA_DIR = 'playwright-userdata';
25
28
  export function playwrightSessionsDir(projectRoot) {
26
- return join(projectRoot, '.peaks', '_runtime', PLAYWRIGHT_SESSIONS_DIR);
29
+ return join(defaultStateRoot(projectRoot), PLAYWRIGHT_SESSIONS_DIR);
27
30
  }
28
31
  export function sessionFilePath(projectRoot, terminalId) {
29
32
  // Terminal-id axis. The derived id is already sanitised (`deriveTerminalId`),
@@ -50,7 +53,7 @@ export function defaultUserDataDir(projectRoot, terminalId) {
50
53
  if (isUnsafePathInput(terminalId)) {
51
54
  throw new Error(`Invalid terminal id: ${terminalId} (must be a single path segment)`);
52
55
  }
53
- return join(projectRoot, '.peaks', '_runtime', 'playwright-userdata', terminalId);
56
+ return join(defaultStateRoot(projectRoot), PLAYWRIGHT_USERDATA_DIR, terminalId);
54
57
  }
55
58
  /**
56
59
  * Derive a stable terminal id from the process environment. Prefers
@@ -19,7 +19,11 @@ async function runProjectContext(io, options) {
19
19
  printResult(io, ok('project.context', readContextData(options.project)), options.json);
20
20
  return;
21
21
  }
22
- const result = await generateProjectContext(options.project);
22
+ const result = await generateProjectContext(options.project, {
23
+ // `--no-project-scan-refresh` is the only way to turn the refresh off;
24
+ // absence leaves this `undefined`, which the service reads as "refresh".
25
+ refreshProjectScan: options.projectScanRefresh !== false
26
+ });
23
27
  printResult(io, ok('project.context', {
24
28
  path: result.path,
25
29
  sessionCount: result.sessionCount,
@@ -40,5 +44,6 @@ export function registerProjectContextCommand(project, io) {
40
44
  .command('context')
41
45
  .description('Generate or read persistent project context for cross-session Peaks understanding. Generates BOTH `.peaks/PROJECT.md` (session history) AND `.peaks/project-scan/project-scan.md` (tech stack + archetypes) — see `peaks workspace init` for the full 5-template boot (G4b/AC9).')
42
46
  .requiredOption('--project <path>', 'target project root')
43
- .option('--read', 'read existing PROJECT.md without regenerating')).action((options) => runProjectContext(io, options));
47
+ .option('--read', 'read existing PROJECT.md without regenerating')
48
+ .option('--no-project-scan-refresh', 'skip refreshing the machine fields (capturedAt / techStack / libraryVersions) of an existing project-scan.md')).action((options) => runProjectContext(io, options));
44
49
  }
@@ -13,6 +13,7 @@ import { fail, ok } from 'peaks-loop-shared/result';
13
13
  import { archiveScreenshots } from '../../services/qa/screenshot-archive-service.js';
14
14
  import { getSessionId } from '../../services/session/session-manager.js';
15
15
  import { isUnsafePathInput } from '../../shared/path-safety.js';
16
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
16
17
  import { addJsonOption, printResult } from '../cli-helpers.js';
17
18
  export function registerQaArchiveScreenshotsCommand(qa, io) {
18
19
  addJsonOption(qa
@@ -32,7 +33,7 @@ export function registerQaArchiveScreenshotsCommand(qa, io) {
32
33
  if (isUnsafePathInput(sid)) {
33
34
  throw new Error(`Invalid session id: ${sid} (must be a single path segment)`);
34
35
  }
35
- const targetDir = join(projectRoot, '.peaks', '_runtime', sid, 'qa', 'screenshots');
36
+ const targetDir = join(getSessionDir(projectRoot, sid), 'qa', 'screenshots');
36
37
  const envelope = archiveScreenshots({ sourceDir: options.source, targetDir });
37
38
  printResult(io, ok('qa.archive-screenshots', envelope, [], archiveNextActions(envelope)), options.json);
38
39
  }
@@ -2,9 +2,9 @@
2
2
  // pre-transition refusals `peaks request transition` runs before it touches an
3
3
  // artifact — session-id resolution, the `--allow-incomplete` reason rule, and
4
4
  // the assisted/strict-mode bypass gate.
5
- import { join } from 'node:path';
6
5
  import { fail } from 'peaks-loop-shared/result';
7
6
  import { isUnsafePathInput } from '../../shared/path-safety.js';
7
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
8
8
  import { printResult } from '../cli-helpers.js';
9
9
  import { isBypassLimitReached, recordBypass, MAX_BYPASSES_PER_SESSION } from '../../services/mode/bypass-tracker.js';
10
10
  import { showRequestArtifact } from '../../services/artifacts/request-artifact-service.js';
@@ -71,7 +71,7 @@ async function applyRestrictedBypassGate(io, ctx) {
71
71
  refuseAllowIncompleteRestricted(io, ctx, presence.mode);
72
72
  return false;
73
73
  }
74
- const sessionRoot = join(options.project, '.peaks', '_runtime', resolvedSessionId ?? 'default');
74
+ const sessionRoot = getSessionDir(options.project, resolvedSessionId ?? 'default');
75
75
  if (isBypassLimitReached(sessionRoot)) {
76
76
  refuseBypassLimitReached(io, ctx);
77
77
  return false;
@@ -4,13 +4,21 @@
4
4
  // 300-line file cap.
5
5
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
7
8
  import { slugifyDescription } from '../../shared/incrementing-number.js';
9
+ /**
10
+ * The runtime root's non-session `benchmarks/` child. Named as a module
11
+ * constant because the drift guard's reverse check keeps the registry entry
12
+ * alive through a constant's VALUE — an inline literal is invisible to it once
13
+ * the join no longer spells `'_runtime'`.
14
+ */
15
+ const BENCHMARKS_DIR = 'benchmarks';
8
16
  export function readPrdBody(rid, projectRoot) {
9
17
  // Search all .peaks/**/prd/requests/*-<rid>.md and .peaks/**/prd/requests/<rid>.md
10
18
  const searchRoots = [
11
19
  join(projectRoot, '.peaks', '2026'),
12
20
  join(projectRoot, '.peaks'),
13
- join(projectRoot, '.peaks', '_runtime')
21
+ defaultStateRoot(projectRoot)
14
22
  ];
15
23
  const matchInDir = (dir) => {
16
24
  if (!existsSync(dir))
@@ -70,7 +78,7 @@ export function writeBenchmarkArtifact(rid, benchmark, projectRoot) {
70
78
  // Reuse the current session binding if present; otherwise fall back to
71
79
  // a deterministic local dir under the project root. The CLI may be
72
80
  // invoked from non-CLI contexts (skill layer); we don't require a session.
73
- const dir = join(projectRoot, '.peaks', '_runtime', 'benchmarks');
81
+ const dir = join(defaultStateRoot(projectRoot), BENCHMARKS_DIR);
74
82
  if (!existsSync(dir)) {
75
83
  mkdirSync(dir, { recursive: true });
76
84
  }
@@ -5,6 +5,7 @@ import { parseKarpathyEnvelope, parseMutEnvelope, parseQaEnvelope, parseSecurity
5
5
  import { addJsonOption, printResult } from '../cli-helpers.js';
6
6
  import { fail, ok } from 'peaks-loop-shared/result';
7
7
  import { isUnsafePathInput } from '../../shared/path-safety.js';
8
+ import { getSessionDir } from '../../services/session/getSessionDir.js';
8
9
  import { DEFAULT_REQUEST_TYPE } from '../../services/artifacts/artifact-prerequisites.js';
9
10
  import { REQUEST_ID_PATTERN } from '../../services/artifacts/request-artifact-service.js';
10
11
  import { contractEvidencePaths } from '../../services/workflow/pipeline-verify-gate-support.js';
@@ -154,14 +155,14 @@ export function registerVerdictAggregateCommands(program, io) {
154
155
  }
155
156
  function readAudit(projectRoot, sid, rid, rels, parse) {
156
157
  for (const rel of rels) {
157
- const path = join(projectRoot, '.peaks', '_runtime', sid, rel.replace('<rid>', rid));
158
+ const path = join(getSessionDir(projectRoot, sid), rel.replace('<rid>', rid));
158
159
  if (existsSync(path))
159
160
  return parse(readFileSync(path, 'utf8'));
160
161
  }
161
162
  return null;
162
163
  }
163
164
  async function readMut(projectRoot, sid) {
164
- const path = join(projectRoot, '.peaks', '_runtime', sid, MUT_REL);
165
+ const path = join(getSessionDir(projectRoot, sid), MUT_REL);
165
166
  if (!existsSync(path))
166
167
  return null;
167
168
  const raw = readFileSync(path, 'utf8');
@@ -176,7 +177,7 @@ async function readMut(projectRoot, sid) {
176
177
  return parseMutJson(json);
177
178
  }
178
179
  function readQa(projectRoot, sid, rid) {
179
- const dir = join(projectRoot, '.peaks', '_runtime', sid, QA_REL);
180
+ const dir = join(getSessionDir(projectRoot, sid), QA_REL);
180
181
  const candidates = [`${rid}.md`, `001-${slugifyDescription(rid)}.md`];
181
182
  for (const name of candidates) {
182
183
  const path = join(dir, name);
@@ -157,6 +157,11 @@ function pushProjectScanActions(nextActions, warnings, ctx) {
157
157
  if (projectScanError !== null) {
158
158
  warnings.push(`project-scan bootstrap failed: ${projectScanError}`);
159
159
  }
160
+ else if (projectScanEnvelope !== null && projectScanEnvelope.refreshWarning !== undefined) {
161
+ // An unparseable or unreadable scan is REPORTED, not silently skipped: the
162
+ // machine fields stay stale and nothing else in this envelope would say so.
163
+ warnings.push(projectScanEnvelope.refreshWarning);
164
+ }
160
165
  else if (projectScanEnvelope !== null && projectScanEnvelope.created) {
161
166
  nextActions.push(`Bootstrapped .peaks/project-scan/ (project-scan.md + 4 audit/business templates) — ` +
162
167
  `${projectScanEnvelope.templatesBooted} file(s) written, ${projectScanEnvelope.templatesSkipped} preserved. ` +
@@ -97,6 +97,7 @@ export async function bootstrapProjectScanForInit(options, projectRoot) {
97
97
  envelope: {
98
98
  created: false,
99
99
  skipped: true,
100
+ refreshed: false,
100
101
  templatesBooted: 0,
101
102
  templatesSkipped: 0,
102
103
  projectScanPath: `${projectRoot}/.peaks/project-scan/project-scan.md`,
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The real effects the four write-side `peaks worktree` commands hand to the
3
+ * workspace-runtime package's lifecycle actions.
4
+ *
5
+ * The package takes `fs`, `runGit` and the clock value as parameters, so the
6
+ * host policy stays here: peaks-loop writes every lease through
7
+ * `atomicWriteJson` (same bytes, same rename-over-target), runs git through
8
+ * `runGitCli`, and reads `Date.now()` once per action — exactly what the
9
+ * command bodies did before the extraction.
10
+ */
11
+ import type { LeaseEffects } from 'peaks-loop-workspace-runtime';
12
+ /** One effect bundle per action; `now` is read once here, as before. */
13
+ export declare function leaseEffects(now: number): LeaseEffects;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The real effects the four write-side `peaks worktree` commands hand to the
3
+ * workspace-runtime package's lifecycle actions.
4
+ *
5
+ * The package takes `fs`, `runGit` and the clock value as parameters, so the
6
+ * host policy stays here: peaks-loop writes every lease through
7
+ * `atomicWriteJson` (same bytes, same rename-over-target), runs git through
8
+ * `runGitCli`, and reads `Date.now()` once per action — exactly what the
9
+ * command bodies did before the extraction.
10
+ */
11
+ import { existsSync, readdirSync, readFileSync as readFileSyncNode } from 'node:fs';
12
+ import { atomicWriteJson } from '../../services/ide/shared/atomic-json.js';
13
+ import { runGitCli } from './worktree-lease-git.js';
14
+ const realLeaseFs = {
15
+ readFile: (file) => readFileSyncNode(file, 'utf8'),
16
+ writeFile: (file, contents) => atomicWriteJson(file, JSON.parse(contents)),
17
+ existsSync: (file) => existsSync(file),
18
+ readdir: (dir) => readdirSync(dir)
19
+ };
20
+ /** One effect bundle per action; `now` is read once here, as before. */
21
+ export function leaseEffects(now) {
22
+ return { fs: realLeaseFs, runGit: runGitCli, now };
23
+ }
@@ -1,11 +1,10 @@
1
1
  /**
2
2
  * `peaks worktree gc` — sweep released/expired leases.
3
3
  *
4
- * Extracted verbatim from `worktree-lease-commands.ts` (mechanical move of
5
- * the `.action()` body). The per-lease sweep is now `sweepLease`; the
4
+ * The sweep is `runGc` from `peaks-loop-workspace-runtime`; this file owns the
5
+ * host policy, the effects, the per-lease metric emit and the envelope. The
6
6
  * `--lease-id` / `--dry-run` semantics, the expired-active transition, the
7
- * best-effort git removal + prune, the per-lease metric emit and the
8
- * ok/fail envelopes are unchanged.
7
+ * best-effort git removal + prune and the ok/fail envelopes are unchanged.
9
8
  */
10
9
  import type { Command } from 'commander';
11
10
  import { type ProgramIO } from '../cli-helpers.js';