peaks-loop 4.1.26 → 4.2.0

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 (119) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +52 -0
  3. package/dist/cli/commands/core/session-info-command.js +3 -4
  4. package/dist/cli/commands/dashboard-long-run.js +2 -1
  5. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  6. package/dist/cli/commands/job-state-root.js +4 -2
  7. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  8. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  9. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  10. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  11. package/dist/cli/commands/mut-commands-helpers.js +13 -46
  12. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  13. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  14. package/dist/cli/commands/outer-cache-commands.js +3 -2
  15. package/dist/cli/commands/playwright-session-store.js +5 -2
  16. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  17. package/dist/cli/commands/request-transition-preflight.js +2 -2
  18. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  19. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  20. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  21. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  22. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  23. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  24. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  25. package/dist/cli/commands/worktree-lease-git.js +21 -44
  26. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  27. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  28. package/dist/cli/commands/worktree-lease-load.js +37 -9
  29. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  30. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  31. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  32. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  33. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  34. package/dist/cli/commands/worktree-lease-session.js +9 -6
  35. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  36. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  37. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  38. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  39. package/dist/cli/commands/worktree-lease-store.js +3 -2
  40. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  41. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  42. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  43. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  44. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  45. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  46. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  47. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  48. package/dist/services/capability-audit-service/runner.js +4 -1
  49. package/dist/services/capability-baseline/store.js +2 -1
  50. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  51. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  52. package/dist/services/code/emit-handoff.js +8 -1
  53. package/dist/services/code/job-shape-decision.js +13 -2
  54. package/dist/services/code/job-shape-provisional.js +9 -1
  55. package/dist/services/code/post-compact-detector.js +9 -1
  56. package/dist/services/code/step-08-session-readers.js +14 -5
  57. package/dist/services/compact/request-transition-hook.js +6 -1
  58. package/dist/services/compact/suggest-service.js +8 -1
  59. package/dist/services/context/post-compact-reinjection.js +15 -14
  60. package/dist/services/context/spillover-store.js +2 -1
  61. package/dist/services/dispatch/contract-store.d.ts +11 -4
  62. package/dist/services/dispatch/contract-store.js +21 -8
  63. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  64. package/dist/services/doctor/doctor-service/index.js +2 -1
  65. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  66. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  67. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  68. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  69. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  70. package/dist/services/loop/monotonic-runner.js +2 -1
  71. package/dist/services/loop/spec-service.js +10 -9
  72. package/dist/services/observability/jsonl-store.js +4 -1
  73. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  74. package/dist/services/prd/prd-blocks-checker.js +12 -6
  75. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  76. package/dist/services/sc/sc-service.js +8 -8
  77. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  78. package/dist/services/scan/api-diff-recorded.js +5 -5
  79. package/dist/services/session/binding-status-service.js +2 -1
  80. package/dist/services/session/binding-store.js +6 -7
  81. package/dist/services/session/caller-binding-service.js +5 -2
  82. package/dist/services/session/getSessionDir.d.ts +4 -0
  83. package/dist/services/session/getSessionDir.js +38 -13
  84. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  85. package/dist/services/session/session-binding-bridge.js +13 -13
  86. package/dist/services/session/session-checkpoint-service.js +22 -3
  87. package/dist/services/session/session-manager.js +16 -20
  88. package/dist/services/skills/presence-lease-resolver.js +3 -2
  89. package/dist/services/skills/presence-lease-service.js +7 -15
  90. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  91. package/dist/services/skills/presence-lease-store.js +60 -5
  92. package/dist/services/skills/skill-presence-service.js +13 -20
  93. package/dist/services/skills/skill-statusline-model.js +7 -2
  94. package/dist/services/slice/slice-archive-service.js +4 -1
  95. package/dist/services/standards/missing-standards-detector.js +2 -1
  96. package/dist/services/test-cache/test-cache-service.js +2 -1
  97. package/dist/services/workflow/artifact-paths.js +6 -2
  98. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  99. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  100. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  101. package/dist/services/workflow/workflow-state-store.js +11 -4
  102. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  103. package/dist/services/workspace/reconcile-migrate.js +2 -2
  104. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  105. package/dist/services/workspace/reconcile-service.js +11 -11
  106. package/dist/services/workspace/workspace-service.js +5 -5
  107. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  108. package/dist/services/worktree/dispatch-provenance.js +9 -2
  109. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  110. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  111. package/dist/shared/runtime-root.js +6 -1
  112. package/package.json +6 -5
  113. package/skills/peaks-mut/SKILL.md +6 -2
  114. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  115. package/dist/services/worktree/git-worktree-parser.js +0 -55
  116. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  117. package/dist/services/worktree/worktree-lease-types.js +0 -9
  118. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  119. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -31,7 +31,7 @@
31
31
  * again — which is exactly the moment the user can say no. Multi-use
32
32
  * is a deliberate opt-in via `--multi`.
33
33
  */
34
- import { type WorktreeLease } from '../worktree/worktree-lease.js';
34
+ import { type WorktreeLease } from 'peaks-loop-workspace-runtime';
35
35
  import { type ContainerLease } from '../container/container-lease.js';
36
36
  export declare const WORKTREE_AUTH_FILE = "worktree-auth.json";
37
37
  /** The narrow surface the gate actually inspects. Keep this list in lock-step with the regex matchers below. */
@@ -34,7 +34,8 @@
34
34
  import { createHash } from 'node:crypto';
35
35
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
36
36
  import { dirname, join } from 'node:path';
37
- import { deserializeLease, isLeaseActive, leaseFilePath } from '../worktree/worktree-lease.js';
37
+ import { deserializeLease, isLeaseActive, leaseFilePath } from 'peaks-loop-workspace-runtime';
38
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
38
39
  import { readDispatchProvenance } from '../worktree/dispatch-provenance.js';
39
40
  import { containerLeaseFilePath, deserializeContainerLease, isContainerLeaseActive } from '../container/container-lease.js';
40
41
  import { consumedGrantsDenial, expiredGrantsDenial, noAuthorizationDenial, noGrantForOperationDenial, requestMismatchDenial } from './worktree-refusal-messages.js';
@@ -48,7 +49,7 @@ export function currentAuthFingerprint(input) {
48
49
  }
49
50
  /** The file the gate reads. Default location: `.peaks/_runtime/<sessionId>/worktree-auth.json`. */
50
51
  export function worktreeAuthFilePath(projectRoot, sessionId) {
51
- return join(projectRoot, '.peaks', '_runtime', sessionId, WORKTREE_AUTH_FILE);
52
+ return join(getSessionDir(projectRoot, sessionId), WORKTREE_AUTH_FILE);
52
53
  }
53
54
  /**
54
55
  * Read + validate the on-disk grant file. Returns `null` for "no file" (not an error — just no auth
@@ -327,12 +328,14 @@ export function evaluateWorktreeAuth(input) {
327
328
  */
328
329
  export function decideFromContainerLease(input) {
329
330
  const containerLeaseId = input.containerLeaseId ?? '';
330
- const file = containerLeaseFilePath(`${input.projectRoot}/.peaks/_runtime/${input.sessionId}`, containerLeaseId);
331
- if (!existsSync(file)) {
331
+ // Total: a bad id is "no lease" — this function's existing fail-closed branch.
332
+ const sessionDir = tryGetSessionDir(input.projectRoot, input.sessionId);
333
+ const file = sessionDir.ok ? containerLeaseFilePath(sessionDir.dir, containerLeaseId) : null;
334
+ if (file === null || !existsSync(file)) {
332
335
  return {
333
336
  allow: false,
334
337
  code: 'CONTAINER_LEASE_FILE_INVALID',
335
- reason: `No container lease at ${file} (leaseId=${containerLeaseId}).`,
338
+ reason: `No container lease at ${file ?? 'an unresolved session directory'} (leaseId=${containerLeaseId}).`,
336
339
  remediation: `Run \`peaks container spawn --rid <rid> --role <role> --purpose "<why>"\` to create the lease, then re-run. The PEAKS_CONTAINER_LEASE_ID env is the source of truth (dispatch injects it).`
337
340
  };
338
341
  }
@@ -375,15 +378,15 @@ export function decideFromContainerLease(input) {
375
378
  export function decideFromLease(input) {
376
379
  const leaseId = input.leaseId ?? '';
377
380
  // `leaseFilePath` expects the per-session runtime dir as its first
378
- // argument, NOT the project root. Compose the same path the spawn
379
- // CLI writes to (`<projectRoot>/.peaks/_runtime/<sid>`).
380
- const runtimeDir = `${input.projectRoot.replace(/[\\/]+$/, '')}/.peaks/_runtime/${input.sessionId}`;
381
- const file = leaseFilePath(runtimeDir, leaseId);
382
- if (!existsSync(file)) {
381
+ // argument, NOT the project root. Total: a bad id resolves to "no lease",
382
+ // the same fail-closed branch as a missing file.
383
+ const sessionDir = tryGetSessionDir(input.projectRoot, input.sessionId);
384
+ const file = sessionDir.ok ? leaseFilePath(sessionDir.dir, leaseId) : null;
385
+ if (file === null || !existsSync(file)) {
383
386
  return {
384
387
  allow: false,
385
388
  code: 'WORKTREE_USER_AUTH_REQUIRED',
386
- reason: `No worktree auth grant AND no lease at ${file} (leaseId=${leaseId}).`,
389
+ reason: `No worktree auth grant AND no lease at ${file ?? 'an unresolved session directory'} (leaseId=${leaseId}).`,
387
390
  remediation: `Either run \`peaks worktree auth grant --operation <op> --reason "<why>"\` or ` +
388
391
  `run \`peaks worktree spawn --rid <rid> --role <role> --purpose "<why>"\` to create the lease.`
389
392
  };
@@ -8,15 +8,14 @@
8
8
  * `verdict-aggregator` envelope union (`karpathy` / `security` / `perf`).
9
9
  *
10
10
  * Karpathy §2 Simplicity First: no new dependencies, no LLM scheduling,
11
- * one binary per evaluator. Each evaluator returns the same envelope
12
- * shape the existing reviewer fan-out produces; verdict-aggregator
13
- * accepts them via `envelopesToAggregatorInput` unchanged (BC).
14
- *
15
- * File budget: ≤ 800 lines.
11
+ * one binary per evaluator. Each returns the same envelope shape the
12
+ * reviewer fan-out produces; verdict-aggregator accepts them via
13
+ * `envelopesToAggregatorInput` unchanged (BC). File budget: ≤ 800 lines.
16
14
  */
17
15
  import { execFileSync } from 'node:child_process';
18
16
  import { existsSync, readFileSync } from 'node:fs';
19
17
  import { join } from 'node:path';
18
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
20
19
  import { runMonotonicCheck } from './monotonic-runner.js';
21
20
  /** Dispatch a single evaluator against the given rid and project. */
22
21
  export function dispatchEvaluator(kind, options) {
@@ -581,8 +580,9 @@ function extractSection(body, heading) {
581
580
  * and project it to an `EvaluatorVerdictEnvelope`. Used by workflow yaml
582
581
  * evaluators that point at on-disk artifacts. */
583
582
  export function loadEnvelopeFromDisk(projectRoot, sid, rel, kind) {
584
- const path = join(projectRoot, '.peaks', '_runtime', sid, rel);
585
- if (!existsSync(path))
583
+ const dir = tryGetSessionDir(projectRoot, sid);
584
+ const path = dir.ok ? join(dir.dir, rel) : '';
585
+ if (!path || !existsSync(path))
586
586
  return null;
587
587
  const md = readFileSync(path, 'utf8');
588
588
  return parseAuditMarkdownEnvelope(md, kind);
@@ -26,6 +26,7 @@ import { join } from 'node:path';
26
26
  import { dispatchEvaluator } from './evaluator-dispatcher.js';
27
27
  import { checkMonotonicImprovement, toScoreRow, DEFAULT_MONOTONIC_THRESHOLD } from './monotonic-guard.js';
28
28
  import { appendMetricLine, readMetricLines } from '../observability/jsonl-store.js';
29
+ import { getSessionDir } from '../session/getSessionDir.js';
29
30
  import { emitMonotonicReport } from './loop-observability.js';
30
31
  import { findProjectRoot } from '../config/config-safety.js';
31
32
  import { classifyFsError, MONOTONIC_CYCLE_KIND, WALKED_EVALUATORS } from './monotonic-runner-types.js';
@@ -33,7 +34,7 @@ import { classifyFsError, MONOTONIC_CYCLE_KIND, WALKED_EVALUATORS } from './mono
33
34
  * derive `cyclesDir`). The monotonic-runner writer no longer writes
34
35
  * here; the jsonl-store is the new persistence layer. */
35
36
  export function sliceDir(projectRoot, sid, rid) {
36
- return join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid);
37
+ return join(getSessionDir(projectRoot, sid), 'loop', rid);
37
38
  }
38
39
  /** Load the most recent prior cycle for `(sid, rid)` from the
39
40
  * per-session jsonl store (tail scan, O(N) where N = total jsonl
@@ -4,8 +4,7 @@
4
4
  * Spec-as-first-class CLI backing service. Reads / writes / lints
5
5
  * `.peaks/_runtime/<sid>/loop/<rid>/spec.yaml` — the project-level
6
6
  * (third-tier) spec origin per Slice A resolver (project → global →
7
- * bundled). Authors may also pass an explicit file path to `peaks loop
8
- * spec lint`.
7
+ * bundled). Authors may also pass an explicit path to `peaks loop spec lint`.
9
8
  *
10
9
  * Spec schema (v1):
11
10
  * - evaluators[].kind (native EvaluatorKind)
@@ -14,18 +13,17 @@
14
13
  * - sla[].evaluator (must match an evaluator.kind above)
15
14
  * - sla[].maxScore (0..1; the floor above which the evaluator is
16
15
  * considered to have held its SLA)
17
- * - termination.strategy ("max-cycles" | "monotonic-violation" |
18
- * "manual")
16
+ * - termination.strategy ("max-cycles" | "monotonic-violation" | "manual")
19
17
  * - termination.maxCycles? (positive integer when strategy = max-cycles)
20
18
  *
21
- * Karpathy §2 Simplicity First: pure data + a single hand-rolled
22
- * YAML parser inline; no new deps.
19
+ * Karpathy §2 Simplicity First: pure data + a single hand-rolled YAML parser.
23
20
  *
24
21
  * File budget: ≤ 800 lines.
25
22
  */
26
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
27
24
  import { dirname, join, isAbsolute } from 'node:path';
28
25
  import { isArray } from '../../shared/array-guards.js';
26
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
29
27
  /** Default termination strategy — wired by `peaks loop run` so a
30
28
  * spec.yaml produced by `loop spec bootstrap` actually drives the
31
29
  * loop driver. Previously the string was declared-and-validated but
@@ -39,7 +37,10 @@ export const DEFAULT_MAX_CYCLES = 5;
39
37
  * `{kind:'missing'}` when no file exists. The CLI layer then chooses
40
38
  * to bootstrap a fresh spec or fail. */
41
39
  export function resolveLoopSpec(projectRoot, sid, rid) {
42
- const path = join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'spec.yaml');
40
+ const resolved = tryGetSessionDir(projectRoot, sid);
41
+ if (!resolved.ok)
42
+ return { origin: { kind: 'missing' }, spec: null };
43
+ const path = join(resolved.dir, 'loop', rid, 'spec.yaml');
43
44
  if (!existsSync(path))
44
45
  return { origin: { kind: 'missing' }, spec: null };
45
46
  const raw = readFileSync(path, 'utf8');
@@ -201,7 +202,7 @@ export function serializeSpec(spec) {
201
202
  /** Persist a LoopSpec to disk at the project-level path; ensures the
202
203
  * parent directory exists. Returns the resolved path. */
203
204
  export function persistSpec(projectRoot, sid, spec) {
204
- const path = join(projectRoot, '.peaks', '_runtime', sid, 'loop', spec.rid, 'spec.yaml');
205
+ const path = join(getSessionDir(projectRoot, sid), 'loop', spec.rid, 'spec.yaml');
205
206
  mkdirSync(dirname(path), { recursive: true });
206
207
  writeFileSync(path, serializeSpec(spec), 'utf8');
207
208
  return path;
@@ -562,7 +563,7 @@ function parseScalarNumber(raw) {
562
563
  return null;
563
564
  }
564
565
  export function specPath(projectRoot, sid, rid) {
565
- return join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'spec.yaml');
566
+ return join(getSessionDir(projectRoot, sid), 'loop', rid, 'spec.yaml');
566
567
  }
567
568
  /** Force a path to be inside the project root — guards against the
568
569
  * `peaks loop spec lint <file>` flag accepting arbitrary paths. The
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
19
20
  import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
20
21
  export const METRICS_DIR = 'metrics';
21
22
  export const METRICS_FILENAME = 'slices.jsonl';
@@ -91,7 +92,9 @@ export function readMetricLines(projectRoot, sessionId) {
91
92
  * caller decides mtime ordering (see `pruneMetricsFiles`).
92
93
  */
93
94
  export function listSessionDirsWithMetrics(projectRoot) {
94
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
95
+ // The bare runtime root, READ-only (existsSync + readdirSync): the seam's
96
+ // state-root entry, whose separators both accept.
97
+ const runtimeRoot = defaultStateRoot(projectRoot);
95
98
  if (!existsSync(runtimeRoot)) {
96
99
  return [];
97
100
  }
@@ -24,12 +24,16 @@
24
24
  */
25
25
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
26
26
  import { dirname, join } from 'node:path';
27
+ import { defaultStateRoot, sessionRuntimeDir } from 'peaks-loop-workspace-runtime';
27
28
  import { isUnsafePathInput } from '../../shared/path-safety.js';
28
29
  /** Compute the child-side path where the artifact should be mirrored.
29
30
  * Mirrors the parent shape exactly: `.peaks/_runtime/<sid>/<role>/`. */
30
31
  function childArtifactPath(childRoot, sid, role, sourcePath) {
31
32
  const filename = sourcePath.split(/[\\/]/).pop() ?? 'artifact.md';
32
- return join(childRoot, '.peaks', '_runtime', sid, role, filename);
33
+ // The child project has the same runtime layout as this one; only the root
34
+ // differs, so the state root is resolved against the CHILD.
35
+ const sessionDir = sessionRuntimeDir({ stateRoot: defaultStateRoot(childRoot), sessionId: sid });
36
+ return join(sessionDir, role, filename);
33
37
  }
34
38
  function ensureDirFor(file) {
35
39
  mkdirSync(dirname(file), { recursive: true });
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
18
18
  import { join, resolve } from 'node:path';
19
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
19
20
  const BLOCK_HEADINGS = [
20
21
  {
21
22
  block: 1,
@@ -43,24 +44,29 @@ const BLOCK_HEADINGS = [
43
44
  }
44
45
  ];
45
46
  const MIN_CONTENT_LENGTH = 50;
47
+ /**
48
+ * The runtime root's non-session `prd/` child. Named once because this module
49
+ * is the reader the runtime-layout registry points at for that entry.
50
+ */
51
+ const PRD_RUNTIME_DIR = 'prd';
46
52
  export function findPrdArtifact(projectRoot, requestId) {
53
+ const stateRoot = defaultStateRoot(projectRoot);
47
54
  // Look under .peaks/_runtime/<session>/prd/requests/<rid>.md
48
55
  // Use the first hit (the most common layout is single-session).
49
56
  const candidates = [
50
- join(projectRoot, '.peaks', '_runtime', 'prd', 'requests', `${requestId}.md`),
51
- join(projectRoot, '.peaks', '_runtime', 'change', requestId, 'prd', 'requests', `${requestId}.md`)
57
+ join(stateRoot, PRD_RUNTIME_DIR, 'requests', `${requestId}.md`),
58
+ join(stateRoot, 'change', requestId, PRD_RUNTIME_DIR, 'requests', `${requestId}.md`)
52
59
  ];
53
60
  for (const c of candidates) {
54
61
  if (existsSync(c))
55
62
  return c;
56
63
  }
57
64
  // Fall back to a glob-like search through .peaks/_runtime/*/prd/requests/.
58
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
59
- if (!existsSync(runtimeRoot))
65
+ if (!existsSync(stateRoot))
60
66
  return null;
61
- for (const sessionOrChange of readdirSync(runtimeRoot)) {
67
+ for (const sessionOrChange of readdirSync(stateRoot)) {
62
68
  for (const sub of ['prd/requests', 'change']) {
63
- const dir = join(runtimeRoot, sessionOrChange, sub, requestId);
69
+ const dir = join(stateRoot, sessionOrChange, sub, requestId);
64
70
  if (existsSync(dir) && statSync(dir).isFile())
65
71
  return dir;
66
72
  }
@@ -10,6 +10,7 @@ import { mkdirSync, writeFileSync } from 'node:fs';
10
10
  import { join } from 'node:path';
11
11
  import { isUnsafePathInput } from '../../shared/path-safety.js';
12
12
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
13
+ import { getSessionDir } from '../session/getSessionDir.js';
13
14
  /** One table cell: newlines and pipes from the model cannot break the table. */
14
15
  function cell(value) {
15
16
  return value.replace(/\r?\n/g, ' ').replace(/\|/g, '\\|');
@@ -55,7 +56,7 @@ export function writeReviewerArtifacts(input) {
55
56
  if (!REQUEST_ID_PATTERN.test(input.rid)) {
56
57
  throw new Error(`Invalid request id: ${input.rid} (expected letters, digits, dots, underscores, or dashes)`);
57
58
  }
58
- const dir = join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'rd');
59
+ const dir = join(getSessionDir(input.projectRoot, input.sessionId), 'rd');
59
60
  mkdirSync(dir, { recursive: true });
60
61
  const paths = {
61
62
  markdown: join(dir, `third-party-review-${input.rid}.md`),
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
2
2
  import { execFileSync } from 'node:child_process';
3
3
  import { join, resolve } from 'node:path';
4
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
4
5
  import { isInsidePath } from '../../shared/path-utils.js';
5
6
  import { getWorkspaceConfigForPath } from '../config/config-service.js';
6
7
  import { getArtifactRemoteRepo, getArtifactWorkspaceStatus, getLocalArtifactPath } from '../artifacts/workspace-service.js';
@@ -158,17 +159,16 @@ function readActiveSkillSessionId(projectRoot) {
158
159
  return hasInFlight ? sessionId : null;
159
160
  }
160
161
  /**
161
- * Read the workspace session binding and return its `sessionId`,
162
- * or null when the file is missing / malformed.
162
+ * Read the workspace session binding and return its `sessionId`, or null when
163
+ * the file is missing / malformed.
163
164
  *
164
- * `<projectRoot>/.peaks/_runtime/session.json`. The legacy
165
- * `<projectRoot>/.peaks/.session.json` is consulted as a
166
- * one-minor-release back-compat fallback: if the new path is
167
- * absent but the legacy path is present and valid, we use the
168
- * legacy value. The new path always wins when both exist.
165
+ * `<projectRoot>/.peaks/_runtime/session.json`; the legacy
166
+ * `<projectRoot>/.peaks/.session.json` is a one-minor-release back-compat
167
+ * fallback: if the new path is absent but the legacy path is present and valid,
168
+ * we use the legacy value. The new path always wins when both exist.
169
169
  */
170
170
  function readSessionJsonBinding(projectRoot) {
171
- const newPath = join(projectRoot, '.peaks', '_runtime', 'session.json');
171
+ const newPath = join(defaultStateRoot(projectRoot), 'session.json');
172
172
  const legacyPath = join(projectRoot, '.peaks', '.session.json');
173
173
  const pathToRead = existsSync(newPath) ? newPath : legacyPath;
174
174
  if (!existsSync(pathToRead))
@@ -6,9 +6,8 @@
6
6
  * 3. the `## API Migration` endpoint list in `.peaks/_runtime/<sid>/txt/*.md`
7
7
  *
8
8
  * All three are OPTIONAL: absence is reported in the report's `notes`, never
9
- * silently. `typescript` is a devDependency and is NOT available at runtime, so
10
- * recorded interfaces are read by the line-based extractor below — its limits
11
- * are documented on the function and exercised by tests.
9
+ * silently. `typescript` is not available at runtime, so recorded interfaces are
10
+ * read by the line-based extractor below, whose limits its doc and tests name.
12
11
  */
13
12
  import { type CandidateMention, type DocOperation, type InterfaceRole, type RecordedEndpoint, type RecordedInterface } from './api-diff-types.js';
14
13
  export declare const MAX_CANDIDATE_NAMES = 100;
@@ -6,12 +6,12 @@
6
6
  * 3. the `## API Migration` endpoint list in `.peaks/_runtime/<sid>/txt/*.md`
7
7
  *
8
8
  * All three are OPTIONAL: absence is reported in the report's `notes`, never
9
- * silently. `typescript` is a devDependency and is NOT available at runtime, so
10
- * recorded interfaces are read by the line-based extractor below — its limits
11
- * are documented on the function and exercised by tests.
9
+ * silently. `typescript` is not available at runtime, so recorded interfaces are
10
+ * read by the line-based extractor below, whose limits its doc and tests name.
12
11
  */
13
12
  import { readFileSync, readdirSync, statSync } from 'node:fs';
14
13
  import { join, resolve } from 'node:path';
14
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
15
15
  import { toDisplayPath } from './api-diff-types.js';
16
16
  export const MAX_CANDIDATE_NAMES = 100;
17
17
  const MAX_HITS_PER_NAME = 5;
@@ -393,7 +393,7 @@ function newest(files) {
393
393
  }
394
394
  /** Source 1: the most recent `.peaks/_runtime/<sid>/rd/mock-plan.md`. */
395
395
  export function findMockPlan(projectRoot) {
396
- const runtime = join(projectRoot, '.peaks', '_runtime');
396
+ const runtime = defaultStateRoot(projectRoot);
397
397
  const candidates = listDirs(runtime)
398
398
  .map((sid) => join(runtime, sid, 'rd', 'mock-plan.md'))
399
399
  .filter((file) => mtimeOf(file) >= 0);
@@ -428,7 +428,7 @@ export function findRecordedInterfaceFiles(projectRoot, mockPlan) {
428
428
  }
429
429
  /** Source 3: the newest TXT handoff that actually carries an `## API Migration` section. */
430
430
  export function findHandoffWithApiMigration(projectRoot) {
431
- const runtime = join(projectRoot, '.peaks', '_runtime');
431
+ const runtime = defaultStateRoot(projectRoot);
432
432
  const candidates = [];
433
433
  for (const sid of listDirs(runtime))
434
434
  candidates.push(...listFiles(join(runtime, sid, 'txt'), '.md'));
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { existsSync } from 'node:fs';
23
23
  import { join } from 'node:path';
24
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
24
25
  import { readBinding } from './binding-store.js';
25
26
  import { getSessionMeta } from './session-manager.js';
26
27
  /**
@@ -29,7 +30,7 @@ import { getSessionMeta } from './session-manager.js';
29
30
  */
30
31
  export function loadBindingStatus(projectRoot) {
31
32
  const binding = readBinding(projectRoot);
32
- const canonicalExists = existsSync(join(projectRoot, '.peaks', '_runtime', 'session.json'));
33
+ const canonicalExists = existsSync(join(defaultStateRoot(projectRoot), 'session.json'));
33
34
  const legacyExists = existsSync(join(projectRoot, '.peaks', '.session.json'));
34
35
  const source = canonicalExists
35
36
  ? 'canonical'
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { constants as fsConstants, copyFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
20
20
  import { dirname, join } from 'node:path';
21
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
21
22
  import { z } from 'zod';
22
23
  export const InstanceRecordSchema = z.object({
23
24
  startedAt: z.string().datetime(),
@@ -33,9 +34,8 @@ export const BindingSchema = z.object({
33
34
  instances: z.record(z.string(), InstanceRecordSchema)
34
35
  });
35
36
  const LEGACY_SESSION_FILE = '.session.json';
36
- const CANONICAL_SESSION_FILE = join('_runtime', 'session.json');
37
37
  function getCanonicalPath(projectRoot) {
38
- return join(projectRoot, '.peaks', CANONICAL_SESSION_FILE);
38
+ return join(defaultStateRoot(projectRoot), 'session.json');
39
39
  }
40
40
  function getLegacyPath(projectRoot) {
41
41
  return join(projectRoot, '.peaks', LEGACY_SESSION_FILE);
@@ -373,17 +373,16 @@ function generateSid() {
373
373
  const rand = Math.random().toString(36).slice(2, 8);
374
374
  return `${yyyy}-${mm}-${dd}-session-${rand}`;
375
375
  }
376
+ const REBUILD_LOCK_NAME = '.rebuild-binding.lock';
376
377
  function acquireRebuildLock(projectRoot) {
377
- const lockPath = join(projectRoot, '.peaks', '_runtime', '.rebuild-binding.lock');
378
+ const lockPath = join(defaultStateRoot(projectRoot), REBUILD_LOCK_NAME);
378
379
  const dir = dirname(lockPath);
379
380
  if (!existsSync(dir)) {
380
381
  mkdirSync(dir, { recursive: true });
381
382
  }
382
383
  try {
383
- // O_EXCL (`wx` in Node): atomic create-or-fail. If the lock file
384
- // already exists, another `rebuildBindingFromLegacy` invocation
385
- // holds it. The holder is expected to release it via
386
- // `closeSync` + `unlinkSync` (see `releaseRebuildLock`).
384
+ // O_EXCL (`wx` in Node): atomic create-or-fail; an existing lock means
385
+ // another `rebuildBindingFromLegacy` invocation holds it.
387
386
  const fd = openSync(lockPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL);
388
387
  return { fd, path: lockPath };
389
388
  }
@@ -18,9 +18,12 @@
18
18
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
19
19
  import { createHash } from 'node:crypto';
20
20
  import { join, resolve } from 'node:path';
21
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
21
22
  import { atomicWriteJson } from '../ide/shared/atomic-json.js';
22
23
  import { CALLER_ID_REGEX } from './caller-id-types.js';
23
24
  import { getSessionDir } from './getSessionDir.js';
25
+ /** The runtime root's non-session `callers/` child (registry name). */
26
+ const CALLERS_DIR = 'callers';
24
27
  /**
25
28
  * On-disk location of the per-caller binding file. P4 invariant:
26
29
  * the `callers/<callerId>.json` lives at `.peaks/_runtime/callers/`,
@@ -32,7 +35,7 @@ export function getCallerBindingFile(projectRoot, callerId) {
32
35
  // The caller is expected to validate via `resolveCallerId` first.
33
36
  throw new Error(`getCallerBindingFile: invalid callerId "${callerId}"`);
34
37
  }
35
- return join(projectRoot, '.peaks', '_runtime', 'callers', `${callerId}.json`);
38
+ return join(defaultStateRoot(projectRoot), CALLERS_DIR, `${callerId}.json`);
36
39
  }
37
40
  /**
38
41
  * On-disk location of the per-(peak, caller) active-skill file. D6:
@@ -166,7 +169,7 @@ export function updateCallerBindingSessionId(projectRoot, callerId, peakSessionI
166
169
  * re-reading).
167
170
  */
168
171
  export function listCallerBindings(projectRoot) {
169
- const dir = join(projectRoot, '.peaks', '_runtime', 'callers');
172
+ const dir = join(defaultStateRoot(projectRoot), CALLERS_DIR);
170
173
  if (!existsSync(dir))
171
174
  return [];
172
175
  let names;
@@ -4,6 +4,10 @@
4
4
  * checked here as well. The session dir is ONE directory name under
5
5
  * `_runtime/`.
6
6
  *
7
+ * Stricter than the workspace-runtime package's `isSinglePathSegment` on
8
+ * purpose (it also rejects drive-letter, scheme and UNC shapes) and equal to it
9
+ * on the NUL axis; the guard stays here and the PATH is what gets delegated.
10
+ *
7
11
  * EXPORTED because the session id is the last caller-supplied segment of
8
12
  * more than one session-scoped path: the runtime dir here, and the dispatch
9
13
  * ledger's dir under `.peaks/_sub_agents/` (read by
@@ -9,9 +9,11 @@
9
9
  * in `src/services/sc/sc-service.ts`).
10
10
  *
11
11
  * `tests/unit/services/session/session-dir-canonical.test.ts` enforces
12
- * three invariants:
12
+ * four invariants:
13
13
  *
14
- * (a) `getSessionDir(root, sid)` returns `<root>/.peaks/_runtime/<sid>`.
14
+ * (a) `getSessionDir(root, sid)` delegates to the workspace-runtime
15
+ * package's `sessionRuntimeDir({ stateRoot: defaultStateRoot(root),
16
+ * sessionId })`, and still refuses a non-segment id.
15
17
  * (b) A static scan of `src/**` flags any `join()` chain that names
16
18
  * `.peaks` plus a session id without routing through this resolver,
17
19
  * wherever the id sits in the chain. The back-compat **read** sites
@@ -20,29 +22,38 @@
20
22
  * (c) A static scan of every markdown file under `skills/` flags a
21
23
  * legacy `.peaks/<sid>/...` artifact path that a sub-agent would
22
24
  * follow verbatim.
25
+ * (d) A static scan of `src/**` flags a direct `.peaks` + `_runtime`
26
+ * composition. The only permitted composition is `defaultStateRoot`;
27
+ * pre-existing hand-rolled call sites are a ratchet baseline in
28
+ * `session-runtime-composition-baseline.json`, so a NEW one fails.
23
29
  *
24
30
  * `sessionId` is the last caller-supplied segment of every session-scoped
25
31
  * path here, so its segment check lives at this join rather than being
26
32
  * re-derived at each call site: `../../x` used to be joined verbatim, and
27
33
  * the CLI wrote outside the project root while still returning `ok: true`.
28
34
  *
29
- * The predicate is `isUnsafePathInput` plus a separator check, NOT
30
- * `SESSION_ID_PATTERN` / `validateSessionId`. The latter are stricter than
31
- * the segment axis and reject ids that are legal today (`sid-1`, a request
35
+ * The predicate is `isUnsafePathInput` plus a separator check and the NUL
36
+ * axis, NOT `SESSION_ID_PATTERN` / `validateSessionId`. The latter are stricter
37
+ * than the segment axis and reject ids that are legal today (`sid-1`, a request
32
38
  * id reused as the session-dir name), so adopting them would change results
33
39
  * for well-formed callers.
34
40
  *
35
- * Not covered, recorded rather than implied: the `\0` axis
36
- * (`isUnsafePathInput` admits a NUL, and `execFileSync` raises EINVAL
37
- * before it can be exercised), and callers that hand-roll
38
- * `join(root, '.peaks', '_runtime', sid, ...)` instead of calling this.
41
+ * The NUL axis used to be admitted here and fail at the OS. It is now checked
42
+ * in this predicate because the path is produced by the workspace-runtime
43
+ * package, which refuses a NUL segment by throwing — and a throw here would
44
+ * escape `tryGetSessionDir`, whose whole contract is to be total. Refusing in
45
+ * the predicate keeps the refusal a VALUE for the total entry and the message
46
+ * the same one every other bad id gets.
47
+ *
48
+ * Callers that hand-roll `join(root, '.peaks', '_runtime', sid, ...)` instead
49
+ * of calling this are counted by invariant (d) and held at their current set.
39
50
  *
40
51
  * @param projectRoot - Absolute path to the project root.
41
52
  * @param sessionId - The session identifier (e.g. `2026-06-06-session-5b1095`).
42
53
  * @returns Absolute path to the canonical session directory.
43
54
  * @throws Error when `sessionId` is not a single path segment.
44
55
  */
45
- import { join } from 'node:path';
56
+ import { defaultStateRoot, sessionRuntimeDir } from 'peaks-loop-workspace-runtime';
46
57
  import { isUnsafePathInput } from '../../shared/path-safety.js';
47
58
  /**
48
59
  * The documented contract: one path segment. `isUnsafePathInput` is a
@@ -50,6 +61,10 @@ import { isUnsafePathInput } from '../../shared/path-safety.js';
50
61
  * checked here as well. The session dir is ONE directory name under
51
62
  * `_runtime/`.
52
63
  *
64
+ * Stricter than the workspace-runtime package's `isSinglePathSegment` on
65
+ * purpose (it also rejects drive-letter, scheme and UNC shapes) and equal to it
66
+ * on the NUL axis; the guard stays here and the PATH is what gets delegated.
67
+ *
53
68
  * EXPORTED because the session id is the last caller-supplied segment of
54
69
  * more than one session-scoped path: the runtime dir here, and the dispatch
55
70
  * ledger's dir under `.peaks/_sub_agents/` (read by
@@ -57,7 +72,10 @@ import { isUnsafePathInput } from '../../shared/path-safety.js';
57
72
  * users, so the two cannot drift apart.
58
73
  */
59
74
  export function isSinglePathSegment(sessionId) {
60
- return !isUnsafePathInput(sessionId) && !sessionId.includes('/') && !sessionId.includes('\\');
75
+ return (!isUnsafePathInput(sessionId) &&
76
+ !sessionId.includes('/') &&
77
+ !sessionId.includes('\\') &&
78
+ !sessionId.includes('\0'));
61
79
  }
62
80
  export function getSessionDir(projectRoot, sessionId) {
63
81
  // Throwing, not `null` / a tagged result: those widen the return type
@@ -67,7 +85,11 @@ export function getSessionDir(projectRoot, sessionId) {
67
85
  if (!isSinglePathSegment(sessionId)) {
68
86
  throw new Error(`Invalid session id: ${sessionId} (must be a single path segment)`);
69
87
  }
70
- return join(projectRoot, '.peaks', '_runtime', sessionId);
88
+ // The ONE composition of the state root and the session segment, shared
89
+ // with peaks-harness. Emitted with forward slashes; no caller compares this
90
+ // string with a `join()`-built one (measured — every call site joins onto
91
+ // it, feeds it to a path API, or compares through `path.relative`).
92
+ return sessionRuntimeDir({ stateRoot: defaultStateRoot(projectRoot), sessionId });
71
93
  }
72
94
  /**
73
95
  * The TOTAL entry to the same axis. Same predicate, same path; the only
@@ -105,5 +127,8 @@ export function tryGetSessionDir(projectRoot, sessionId) {
105
127
  reason: `Invalid session id: ${sessionId} (must be a single path segment)`
106
128
  };
107
129
  }
108
- return { ok: true, dir: join(projectRoot, '.peaks', '_runtime', sessionId) };
130
+ return {
131
+ ok: true,
132
+ dir: sessionRuntimeDir({ stateRoot: defaultStateRoot(projectRoot), sessionId })
133
+ };
109
134
  }
@@ -11,12 +11,9 @@
11
11
  *
12
12
  * `session-manager.ts` re-exports the two functions and the two result
13
13
  * types so the 5 external callers (`request-artifact-service.ts`,
14
- * `upgrade-commands.ts`, `init-command.ts`, plus 2 test files) do NOT
15
- * need to change their import path. The re-export shim is the only
16
- * added code in `session-manager.ts`.
17
- *
18
- * Body of every function moved verbatim per Karpathy #3 (Surgical
19
- * Changes). No behavior change. The bridge adds nothing of its own.
14
+ * `upgrade-commands.ts`, `init-command.ts`, plus 2 test files) keep
15
+ * their import path.
16
+ * Body of every function moved verbatim per Karpathy #3 (Surgical Changes).
20
17
  */
21
18
  /**
22
19
  * Test-only seam: reset the module-scoped `lastResolvedOuter` so