peaks-loop 4.1.25 → 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 +69 -3
  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
@@ -20,6 +20,7 @@
20
20
  import { existsSync, readFileSync } from 'node:fs';
21
21
  import { execFileSync } from 'node:child_process';
22
22
  import { join } from 'node:path';
23
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
23
24
  import { JUDGED_HEADING, parseJudgedDeclaration, sha256OfFile } from './judged-declaration.js';
24
25
  /**
25
26
  * What a refusal means, partitioned by THE ONE QUESTION its codes answer:
@@ -92,7 +93,10 @@ export function securityArtifactTiers(rid) {
92
93
  ];
93
94
  }
94
95
  export function resolveSecurityArtifact(projectRoot, sessionId, rid) {
95
- const root = join(projectRoot, '.peaks', '_runtime', sessionId);
96
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
97
+ if (!resolved.ok)
98
+ return null;
99
+ const root = resolved.dir;
96
100
  for (const relative of securityArtifactTiers(rid)) {
97
101
  const absolute = join(root, ...relative.split('/'));
98
102
  if (existsSync(absolute))
@@ -129,11 +129,9 @@ export declare function renderPerfAuditArtifact(env: PerfAuditEnvelope, opts: {
129
129
  verdict: PerfAuditVerdict;
130
130
  };
131
131
  /**
132
- * Write the rendered audit artifact to
133
- * `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
132
+ * Write the rendered audit artifact to `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
134
133
  *
135
- * Atomic write (tmp + rename) to avoid partial writes on crash.
136
- * Returns the absolute path on success.
134
+ * Atomic write (tmp + rename); returns the absolute path on success.
137
135
  */
138
136
  export declare function writePerfAuditArtifact(projectRoot: string, sessionId: string, rid: string, body: string): string;
139
137
  /**
@@ -25,6 +25,7 @@ import { join, resolve, isAbsolute } from 'node:path';
25
25
  import { createHash } from 'node:crypto';
26
26
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
27
27
  import { resolveHandoffPath } from '../prd/handoff-service.js';
28
+ import { getSessionDir } from '../session/getSessionDir.js';
28
29
  import { handoffMissingRefusal } from './handoff-missing-refusal.js';
29
30
  /**
30
31
  * Validate a raw value as a PerfAuditEnvelope. Mirrors the
@@ -282,11 +283,9 @@ export function renderPerfAuditArtifact(env, opts) {
282
283
  };
283
284
  }
284
285
  /**
285
- * Write the rendered audit artifact to
286
- * `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
286
+ * Write the rendered audit artifact to `.peaks/_runtime/<sid>/audit/perf-<rid>.md`.
287
287
  *
288
- * Atomic write (tmp + rename) to avoid partial writes on crash.
289
- * Returns the absolute path on success.
288
+ * Atomic write (tmp + rename); returns the absolute path on success.
290
289
  */
291
290
  export function writePerfAuditArtifact(projectRoot, sessionId, rid, body) {
292
291
  // The rid is a filename below, and the write is tmp+rename, so an
@@ -295,7 +294,7 @@ export function writePerfAuditArtifact(projectRoot, sessionId, rid, body) {
295
294
  if (!REQUEST_ID_PATTERN.test(rid)) {
296
295
  throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
297
296
  }
298
- const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
297
+ const targetDir = join(getSessionDir(projectRoot, sessionId), 'audit');
299
298
  mkdirSync(targetDir, { recursive: true });
300
299
  const targetPath = join(targetDir, `perf-${rid}.md`);
301
300
  // tmp + rename for atomicity
@@ -6,6 +6,7 @@
6
6
  import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { REQUEST_ID_PATTERN } from '../artifacts/request-artifact-service.js';
9
+ import { getSessionDir } from '../session/getSessionDir.js';
9
10
  /**
10
11
  * Render a SecurityAuditEnvelope to the canonical audit artifact body
11
12
  * (markdown). Produce a markdown body with all required sections, ready to
@@ -78,7 +79,10 @@ export function writeSecurityAuditArtifact(projectRoot, sessionId, rid, body) {
78
79
  if (!REQUEST_ID_PATTERN.test(rid)) {
79
80
  throw new Error(`Invalid request id: ${rid} (expected letters, digits, dots, underscores, or dashes)`);
80
81
  }
81
- const targetDir = join(projectRoot, '.peaks', '_runtime', sessionId, 'audit');
82
+ // This is a WRITE target and is one segment below the session dir, so it
83
+ // takes the throwing entry: a bad sid refuses here the same way a bad rid
84
+ // does above, instead of composing a path outside the session.
85
+ const targetDir = join(getSessionDir(projectRoot, sessionId), 'audit');
82
86
  mkdirSync(targetDir, { recursive: true });
83
87
  const targetPath = join(targetDir, `security-${rid}.md`);
84
88
  // tmp + rename for atomicity
@@ -1,5 +1,6 @@
1
1
  import { mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { getSessionDir } from '../session/getSessionDir.js';
3
4
  import { crossCheck } from './cross-check.js';
4
5
  import { runIndependentCheck } from './independent-checker.js';
5
6
  function scoreFor(status) {
@@ -102,7 +103,9 @@ export async function runAudit(input) {
102
103
  findings: check === null ? null : check.findings,
103
104
  coverage: check === null ? null : check.coverage
104
105
  };
105
- const dir = join(input.projectRoot, '.peaks', '_runtime', input.sessionId, 'capability-audit');
106
+ // Write target: the throwing entry, so a refused sid cannot produce a
107
+ // directory outside the session.
108
+ const dir = join(getSessionDir(input.projectRoot, input.sessionId), 'capability-audit');
106
109
  mkdirSync(dir, { recursive: true });
107
110
  writeFileSync(join(dir, `${auditId}.json`), JSON.stringify(out, null, 2));
108
111
  return out;
@@ -2,10 +2,11 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { existsSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs';
4
4
  import { dirname, join } from 'node:path';
5
+ import { getSessionDir } from '../session/getSessionDir.js';
5
6
  const CURRENT_DIR = (root) => join(root, 'openspec', 'baselines', 'current');
6
7
  const FILE_PATH = (root) => join(CURRENT_DIR(root), 'capability-baseline.json');
7
8
  const LOCK_PATH = (root) => join(CURRENT_DIR(root), 'capability-baseline.lock');
8
- const POINTER = (root, sessionId) => join(root, '.peaks', '_runtime', sessionId, 'baselines', 'current.json');
9
+ const POINTER = (root, sessionId) => join(getSessionDir(root, sessionId), 'baselines', 'current.json');
9
10
  function hashFor(file) {
10
11
  const stripped = {
11
12
  schemaVersion: file.schemaVersion,
@@ -2,6 +2,7 @@ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { IncompleteFinalReviewError, MAX_EVIDENCE_BYTES_PER_FILE, outputBudgetForEvidence, prepareFinalReview, resolveOutputBudget, undeliverableDimensions } from '../../final-review/final-review-service.js';
5
+ import { getSessionDir } from '../../session/getSessionDir.js';
5
6
  import { combineProbes, fail, missingSourceFiles, pass, probe, requireBaselineRow } from './_shared.js';
6
7
  /** The four dimensions the frozen baseline names. The 5th is NOT one of them. */
7
8
  const FOUR_DIMENSIONS = [
@@ -84,8 +85,9 @@ async function probePrepareFinalReview() {
84
85
  const root = mkdtempSync(join(tmpdir(), 'cbl-J05-'));
85
86
  try {
86
87
  const sessionId = 'guard-J05';
87
- mkdirSync(join(root, '.peaks', '_runtime', sessionId, 'audit-goal'), { recursive: true });
88
- writeFileSync(join(root, '.peaks', '_runtime', sessionId, 'audit-goal', 'J05-fixture.json'), JSON.stringify({ successCriteria: ['c'] }));
88
+ const fixtureDir = join(getSessionDir(root, sessionId), 'audit-goal');
89
+ mkdirSync(fixtureDir, { recursive: true });
90
+ writeFileSync(join(fixtureDir, 'J05-fixture.json'), JSON.stringify({ successCriteria: ['c'] }));
89
91
  const opts = { projectRoot: root, sessionId };
90
92
  let rejected = false;
91
93
  let rejectName = 'none';
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { deserializeLease, finalizeLease, isLeaseActive, isLeaseGcEligible, leaseFilePath, leaseStoreDir, listLeasesSync, markReleased, recordConsumption, renewLease, serializeLease, ttlForRole } from '../../worktree/worktree-lease.js';
4
+ import { deserializeLease, finalizeLease, isLeaseActive, isLeaseGcEligible, leaseFilePath, leaseStoreDir, listLeasesSync, markReleased, recordConsumption, renewLease, serializeLease, ttlForRole } from 'peaks-loop-workspace-runtime';
5
5
  import { combineProbes, fail, missingSourceFiles, pass, probe, requireBaselineRow } from './_shared.js';
6
6
  const NOW = 1_700_000_000_000;
7
7
  const DRAFT = {
@@ -68,7 +68,7 @@ export async function runJ12Contract(ctx) {
68
68
  probe(isLeaseGcEligible(finalizeLease({ ...DRAFT, expiresAt: NOW - 1 }), NOW), 'an expired lease is gc-eligible'),
69
69
  probe(ttlForRole('rd') > 0 && ttlForRole('no-such-role') === ttlForRole('rd'), 'unknown roles fall back to the rd TTL')
70
70
  ]);
71
- const artifact = row.sourceFiles[0] ?? 'src/services/worktree/worktree-lease.ts';
71
+ const artifact = row.sourceFiles[0] ?? 'packages/peaks-loop-workspace-runtime/src/lease/store.ts';
72
72
  if (result.ok)
73
73
  return pass(ctx, artifact);
74
74
  return fail(ctx, artifact, 'the lease lifecycle is complete: release is idempotent and gc never touches an in-flight lease', result.detail, 'J12 invariant broken: the lease release lifecycle or its gc guard no longer holds');
@@ -29,6 +29,7 @@
29
29
  import { existsSync, readFileSync } from 'node:fs';
30
30
  import { join } from 'node:path';
31
31
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
32
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
32
33
  import { readJobShapeDecision, JobShapeDecisionError, JOB_SHAPE_NOT_DECIDED } from './job-shape-decision.js';
33
34
  export const JOB_NOT_INITIALIZED = 'JOB_NOT_INITIALIZED';
34
35
  export const JOB_REMAINING_BLOCKED = 'JOB_REMAINING_BLOCKED';
@@ -52,8 +53,14 @@ function countRemaining(statePath) {
52
53
  return Number.NaN;
53
54
  return parsed.slices.filter((sl) => sl.status !== 'done' && sl.status !== 'skipped').length;
54
55
  }
56
+ /**
57
+ * The Job state file. An id that cannot name a session dir names no file, and
58
+ * the empty string is what `existsSync` already reads as "nothing here" — the
59
+ * frame's existing answer, kept as a value so no new branch appears in it.
60
+ */
55
61
  function statePath(projectRoot, sessionId, jobId) {
56
- return join(projectRoot, '.peaks', '_runtime', sessionId, 'job', jobId, 'state.json');
62
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
63
+ return resolved.ok ? join(resolved.dir, 'job', jobId, 'state.json') : '';
57
64
  }
58
65
  /**
59
66
  * Which session a memory came from, as the memory index records it.
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
20
20
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
21
21
  import { join } from 'node:path';
22
22
  import { z } from 'zod';
23
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
23
24
  export const JOB_SHAPE_SCHEMA_VERSION = 1;
24
25
  export const JOB_SHAPE_FILE_NAME = 'job-shape.json';
25
26
  export const JOB_SHAPE_ALREADY_DECIDED = 'JOB_SHAPE_ALREADY_DECIDED';
@@ -54,7 +55,7 @@ export class JobShapeDecisionError extends Error {
54
55
  }
55
56
  }
56
57
  function runtimeDir(projectRoot, sessionId) {
57
- return join(projectRoot, '.peaks', '_runtime', sessionId);
58
+ return getSessionDir(projectRoot, sessionId);
58
59
  }
59
60
  function decisionPath(projectRoot, sessionId) {
60
61
  return join(runtimeDir(projectRoot, sessionId), JOB_SHAPE_FILE_NAME);
@@ -71,7 +72,17 @@ function validateRecord(input) {
71
72
  }
72
73
  /** Read the canonical record; throws JOB_SHAPE_NOT_DECIDED if absent or malformed. */
73
74
  export function readJobShapeDecision(projectRoot, sessionId) {
74
- const path = decisionPath(projectRoot, sessionId);
75
+ // A frame that promises a typed refusal, not a throw: an id that names no
76
+ // session directory is the same "no record" answer as an absent file.
77
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
78
+ if (!resolved.ok) {
79
+ throw new JobShapeDecisionError({
80
+ code: JOB_SHAPE_NOT_DECIDED,
81
+ message: `No Job-shape decision recorded for session ${sessionId}. Run \`peaks code detect-job\` to record a decision.`,
82
+ details: { reason: resolved.reason }
83
+ });
84
+ }
85
+ const path = join(resolved.dir, JOB_SHAPE_FILE_NAME);
75
86
  if (!existsSync(path)) {
76
87
  throw new JobShapeDecisionError({
77
88
  code: JOB_SHAPE_NOT_DECIDED,
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import { existsSync } from 'node:fs';
24
24
  import { join } from 'node:path';
25
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
25
26
  import { JobShapeDecisionError, JOB_SHAPE_ALREADY_DECIDED, JOB_SHAPE_FILE_NAME, readJobShapeDecision, writeJobShapeDecision } from './job-shape-decision.js';
26
27
  function provisionalRationale(jobId) {
27
28
  return (`Provisional decision written by \`peaks job init\` when it created the Job ledger for ` +
@@ -40,7 +41,14 @@ function provisionalRationale(jobId) {
40
41
  * folded into `already-decided` — the winner's decision stands.
41
42
  */
42
43
  export function ensureProvisionalJobShapeDecision(projectRoot, sessionId, input) {
43
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, JOB_SHAPE_FILE_NAME);
44
+ // The function's contract is "any failure is RETURNED, never thrown", so the
45
+ // id is resolved through the total entry; an unresolvable id is the same
46
+ // `write-failed` outcome as a refused write, with no path to name.
47
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
48
+ if (!resolved.ok) {
49
+ return { written: false, path: '', reason: 'write-failed', error: resolved.reason };
50
+ }
51
+ const path = join(resolved.dir, JOB_SHAPE_FILE_NAME);
44
52
  if (existsSync(path)) {
45
53
  try {
46
54
  readJobShapeDecision(projectRoot, sessionId);
@@ -24,6 +24,7 @@
24
24
  import { existsSync, readdirSync } from 'node:fs';
25
25
  import { join } from 'node:path';
26
26
  import { getSkillPresence } from '../skills/skill-presence-service.js';
27
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
27
28
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
28
29
  import { emitObservabilityEvent } from '../observability/observability-service.js';
29
30
  import { CHECKPOINT_EXT, CHECKPOINTS_DIR, isToday, safeReadCheckpoint } from './post-compact-checkpoint.js';
@@ -89,7 +90,14 @@ export async function detectPostCompactResume(opts) {
89
90
  if (!opts.sessionId || opts.sessionId.trim().length === 0) {
90
91
  return { shouldAutoResume: false, reason: 'sid-unbound', warnings };
91
92
  }
92
- const runtimeDir = join(opts.projectRoot, '.peaks', '_runtime', opts.sessionId);
93
+ // The TOTAL entry: this probe reports its own misses as reasons, and an id
94
+ // that cannot name a session dir has no directory to probe — the same
95
+ // answer `existsSync` gives for a directory that is not there.
96
+ const sessionDir = tryGetSessionDir(opts.projectRoot, opts.sessionId);
97
+ if (!sessionDir.ok) {
98
+ return { shouldAutoResume: false, reason: 'runtime-dir-missing', warnings };
99
+ }
100
+ const runtimeDir = sessionDir.dir;
93
101
  if (!existsSync(runtimeDir)) {
94
102
  return { shouldAutoResume: false, reason: 'runtime-dir-missing', warnings };
95
103
  }
@@ -8,9 +8,11 @@
8
8
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
10
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
11
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
11
12
  const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
12
13
  function runtimeSessionDir(projectRoot, sessionId) {
13
- return join(projectRoot, '.peaks', '_runtime', sessionId);
14
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
15
+ return resolved.ok ? resolved.dir : null;
14
16
  }
15
17
  function progressPath(projectRoot, sessionId, jid) {
16
18
  // The progress file lives under job/<jid>/progress.json. The jid
@@ -19,11 +21,12 @@ function progressPath(projectRoot, sessionId, jid) {
19
21
  // the matching path directly rather than enumerating the job/ dir.
20
22
  // (Rotating mode spawns new jids but only one is "active" at a time;
21
23
  // the active jid is the latest write to job-shape.json.)
22
- return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
24
+ const dir = runtimeSessionDir(projectRoot, sessionId);
25
+ return dir === null ? null : join(dir, 'job', jid, STEP_08_PROGRESS_FILE_NAME);
23
26
  }
24
27
  export function readProgressIfAny(projectRoot, sessionId, jid) {
25
28
  const path = progressPath(projectRoot, sessionId, jid);
26
- if (!existsSync(path))
29
+ if (path === null || !existsSync(path))
27
30
  return null;
28
31
  try {
29
32
  const raw = readFileSync(path, 'utf8');
@@ -57,7 +60,10 @@ export function readProgressIfAny(projectRoot, sessionId, jid) {
57
60
  }
58
61
  }
59
62
  export function readPromptFromLastPromptFile(projectRoot, sessionId) {
60
- const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
63
+ const dir = runtimeSessionDir(projectRoot, sessionId);
64
+ if (dir === null)
65
+ return '';
66
+ const path = join(dir, 'txt', 'last-prompt.txt');
61
67
  if (!existsSync(path))
62
68
  return '';
63
69
  try {
@@ -87,7 +93,10 @@ export function readPromptFromLastPromptFile(projectRoot, sessionId) {
87
93
  * or a provisional write that failed — not proof the decision step was skipped.
88
94
  */
89
95
  export function ledgerJobIds(projectRoot, sessionId) {
90
- const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
96
+ const dir = runtimeSessionDir(projectRoot, sessionId);
97
+ if (dir === null)
98
+ return [];
99
+ const jobDir = join(dir, 'job');
91
100
  if (!existsSync(jobDir))
92
101
  return [];
93
102
  let names;
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { existsSync, readFileSync } from 'node:fs';
23
23
  import { join } from 'node:path';
24
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
24
25
  import { writeCheckpoint } from '../session/session-checkpoint-service.js';
25
26
  import { AUTO_COMPACT_PRE_COMPACT_RATIO, AUTO_COMPACT_RED_LINE_RATIO } from '../context/auto-compact-types.js';
26
27
  const PRE_COMPACT_ZONE = {
@@ -28,7 +29,11 @@ const PRE_COMPACT_ZONE = {
28
29
  redLine: AUTO_COMPACT_RED_LINE_RATIO
29
30
  };
30
31
  function readLatestUsageRow(projectRoot, sessionId) {
31
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, 'usage.jsonl');
32
+ // An unresolvable id has no usage row — the same answer as a missing file.
33
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
34
+ if (!resolved.ok)
35
+ return null;
36
+ const path = join(resolved.dir, 'usage.jsonl');
32
37
  if (!existsSync(path))
33
38
  return null;
34
39
  try {
@@ -24,13 +24,20 @@
24
24
  */
25
25
  import { existsSync, readFileSync } from 'node:fs';
26
26
  import { join } from 'node:path';
27
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
27
28
  import { lookupPhaseTransition, buildSuggestedCompactMessage, SURVIVAL_TABLE } from './decision-tables.js';
28
29
  import { DEFAULT_TOOL_CALL_THRESHOLD, DEFAULT_CONTEXT_THRESHOLD_200K, DEFAULT_CONTEXT_THRESHOLD_1M, DEFAULT_CONTEXT_INTERVAL } from './suggest-types.js';
29
30
  /** Snapshot of the survival table for the dry-run envelope. */
30
31
  const SURVIVAL_TABLE_PERSISTS = SURVIVAL_TABLE.persists;
31
32
  const SURVIVAL_TABLE_LOST = SURVIVAL_TABLE.lost;
32
33
  function readLatestUsageRow(projectRoot, sessionId) {
33
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, 'usage.jsonl');
34
+ // Total by contract — "never throws" is this module's documented surface —
35
+ // so an id that cannot name a session dir reads as "no usage row", which is
36
+ // the same answer an absent file gets.
37
+ const sessionDir = tryGetSessionDir(projectRoot, sessionId);
38
+ if (!sessionDir.ok)
39
+ return null;
40
+ const path = join(sessionDir.dir, 'usage.jsonl');
34
41
  if (!existsSync(path))
35
42
  return null;
36
43
  try {
@@ -63,6 +63,7 @@ import { readdirSync, statSync } from 'node:fs';
63
63
  import { join } from 'node:path';
64
64
  import { readJobShapeDecision } from '../code/job-shape-decision.js';
65
65
  import { describeNextSlice, tryReadJobProgress } from '../job/job-progress-store.js';
66
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
66
67
  import { getSessionIdCanonical } from '../session/session-manager.js';
67
68
  /**
68
69
  * Hard ceiling on the card's size, in UTF-8 bytes.
@@ -231,25 +232,25 @@ function toPosix(p) {
231
232
  /**
232
233
  * Find the most recently modified request artifact under the session tree.
233
234
  *
234
- * This is a POINTER RESOLVER, not a content reader: it returns the artifact's
235
- * name so the card can name it, and never opens it. Deliberately limited to
236
- * `<session>/<role>/requests/*.md` — the tree every role already writes to —
237
- * rather than a repo-wide search, so the answer cannot be some unrelated
238
- * markdown file that happens to be newer.
235
+ * A POINTER RESOLVER, not a content reader: it returns the artifact's name so
236
+ * the card can name it, and never opens it. Deliberately limited to
237
+ * `<session>/<role>/requests/*.md` — the tree every role already writes to — so
238
+ * the answer cannot be some unrelated newer markdown file.
239
239
  *
240
- * Returns its failures alongside the answer instead of swallowing them. The
241
- * tempting shape here — a bare `catch { continue }` — makes two very different
242
- * states indistinguishable to the caller: "this role has no requests yet"
243
- * (ordinary, most roles) and "this role's requests directory exists but could
244
- * not be read" (a real problem worth reporting). Only `ENOENT` is the ordinary
245
- * one, so only `ENOENT` is silent.
240
+ * Returns its failures alongside the answer instead of swallowing them: a bare
241
+ * `catch { continue }` makes "no requests yet" (ordinary, most roles) and "the
242
+ * directory exists but could not be read" (a real problem worth reporting)
243
+ * indistinguishable. Only `ENOENT` is the ordinary one, so only `ENOENT` is
244
+ * silent.
246
245
  */
247
246
  function findLatestRequestArtifact(projectRoot, sessionId) {
248
- const sessionDir = join(projectRoot, '.peaks', '_runtime', sessionId);
247
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
248
+ if (!resolved.ok)
249
+ return { rel: null, warnings: [] };
249
250
  const warnings = [];
250
251
  let roles;
251
252
  try {
252
- roles = readdirSync(sessionDir, { withFileTypes: true })
253
+ roles = readdirSync(resolved.dir, { withFileTypes: true })
253
254
  .filter((entry) => entry.isDirectory())
254
255
  .map((entry) => entry.name)
255
256
  .sort();
@@ -263,7 +264,7 @@ function findLatestRequestArtifact(projectRoot, sessionId) {
263
264
  }
264
265
  let best = null;
265
266
  for (const role of roles) {
266
- const requestsDir = join(sessionDir, role, 'requests');
267
+ const requestsDir = join(resolved.dir, role, 'requests');
267
268
  let files;
268
269
  try {
269
270
  files = readdirSync(requestsDir).filter((name) => name.endsWith('.md'));
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { isAbsolute, join, relative } from 'node:path';
4
+ import { getSessionDir } from '../session/getSessionDir.js';
4
5
  import { SPILL_TTL_MS } from './spillover-types.js';
5
6
  const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
6
7
  function assertSafeSegment(value, name) {
@@ -38,7 +39,7 @@ export function assertNotSymlink(path) {
38
39
  }
39
40
  export function spillDir(projectRoot, sessionId) {
40
41
  assertSafeSegment(sessionId, 'sessionId');
41
- return join(projectRoot, '.peaks', '_runtime', sessionId, 'spill');
42
+ return join(getSessionDir(projectRoot, sessionId), 'spill');
42
43
  }
43
44
  export function spillPath(projectRoot, sessionId, spillId) {
44
45
  assertSafeSegment(spillId, 'spillId');
@@ -35,10 +35,17 @@ export declare function isOrphanContract(opts: {
35
35
  sliceId: string;
36
36
  now?: Date;
37
37
  }): boolean;
38
- /** Resolve the contracts directory for a session. */
39
- export declare function contractsDir(projectRoot: string, sessionId: string): string;
40
- /** Resolve a single contract file path. */
41
- export declare function contractPath(projectRoot: string, sessionId: string, sliceId: string): string;
38
+ /**
39
+ * Resolve the contracts directory for a session, or `null` when the session id
40
+ * cannot name a session dir.
41
+ *
42
+ * The TOTAL entry: every reader here answers "no contract" for a directory it
43
+ * cannot reach, and an unresolvable id is that same answer. The writer is the
44
+ * one frame that cannot proceed, and it says so with its own typed error.
45
+ */
46
+ export declare function contractsDir(projectRoot: string, sessionId: string): string | null;
47
+ /** Resolve a single contract file path, or `null` on an unresolvable session id. */
48
+ export declare function contractPath(projectRoot: string, sessionId: string, sliceId: string): string | null;
42
49
  /** Hash a contract payload. */
43
50
  export declare function hashContract(c: WriteContractInput | SliceContract): string;
44
51
  /**
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
20
20
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
21
21
  import { join } from 'node:path';
22
22
  import { isArray } from '../../shared/array-guards.js';
23
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
23
24
  /** Thrown when contract IO fails. */
24
25
  export class ContractStoreError extends Error {
25
26
  code = 'CONTRACT_STORE_ERROR';
@@ -37,7 +38,7 @@ export const CONTRACT_TTL_DAYS = 30;
37
38
  */
38
39
  export function isOrphanContract(opts) {
39
40
  const path = contractPath(opts.projectRoot, opts.sessionId, opts.sliceId);
40
- if (!existsSync(path))
41
+ if (path === null || !existsSync(path))
41
42
  return true;
42
43
  const s = statSync(path);
43
44
  const now = opts.now ?? new Date();
@@ -45,13 +46,22 @@ export function isOrphanContract(opts) {
45
46
  const ttlMs = CONTRACT_TTL_DAYS * 24 * 60 * 60 * 1000;
46
47
  return ageMs > ttlMs;
47
48
  }
48
- /** Resolve the contracts directory for a session. */
49
+ /**
50
+ * Resolve the contracts directory for a session, or `null` when the session id
51
+ * cannot name a session dir.
52
+ *
53
+ * The TOTAL entry: every reader here answers "no contract" for a directory it
54
+ * cannot reach, and an unresolvable id is that same answer. The writer is the
55
+ * one frame that cannot proceed, and it says so with its own typed error.
56
+ */
49
57
  export function contractsDir(projectRoot, sessionId) {
50
- return join(projectRoot, '.peaks', '_runtime', sessionId, 'dispatch', 'contracts');
58
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
59
+ return resolved.ok ? join(resolved.dir, 'dispatch', 'contracts') : null;
51
60
  }
52
- /** Resolve a single contract file path. */
61
+ /** Resolve a single contract file path, or `null` on an unresolvable session id. */
53
62
  export function contractPath(projectRoot, sessionId, sliceId) {
54
- return join(contractsDir(projectRoot, sessionId), `${sliceId}.json`);
63
+ const dir = contractsDir(projectRoot, sessionId);
64
+ return dir === null ? null : join(dir, `${sliceId}.json`);
55
65
  }
56
66
  /** Canonicalize a contract for hashing. Keys sorted; arrays preserved. */
57
67
  function canonicalize(c) {
@@ -102,17 +112,20 @@ export function writeContract(projectRoot, sessionId, input) {
102
112
  contractHash
103
113
  };
104
114
  const dir = contractsDir(projectRoot, sessionId);
115
+ const path = contractPath(projectRoot, sessionId, input.sliceId);
116
+ if (dir === null || path === null) {
117
+ throw new ContractStoreError(`Invalid session id: ${sessionId} (must be a single path segment)`);
118
+ }
105
119
  if (!existsSync(dir)) {
106
120
  mkdirSync(dir, { recursive: true });
107
121
  }
108
- const path = contractPath(projectRoot, sessionId, input.sliceId);
109
122
  writeFileSync(path, JSON.stringify(contract, null, 2) + '\n', 'utf8');
110
123
  return { path, contract };
111
124
  }
112
125
  /** Read a contract from disk. Returns null if missing. */
113
126
  export function readContract(projectRoot, sessionId, sliceId) {
114
127
  const path = contractPath(projectRoot, sessionId, sliceId);
115
- if (!existsSync(path))
128
+ if (path === null || !existsSync(path))
116
129
  return null;
117
130
  try {
118
131
  const raw = readFileSync(path, 'utf8');
@@ -125,7 +138,7 @@ export function readContract(projectRoot, sessionId, sliceId) {
125
138
  /** List all contracts for a session. */
126
139
  export function listContracts(projectRoot, sessionId) {
127
140
  const dir = contractsDir(projectRoot, sessionId);
128
- if (!existsSync(dir))
141
+ if (dir === null || !existsSync(dir))
129
142
  return [];
130
143
  const files = readdirSync(dir).filter((f) => f.endsWith('.json'));
131
144
  const out = [];
@@ -20,8 +20,9 @@
20
20
  * non-fatal probe path never escalates into a doctor failure.
21
21
  */
22
22
  import { existsSync, lstatSync, readdirSync } from 'node:fs';
23
- import { join } from 'node:path';
23
+ import { join, relative } from 'node:path';
24
24
  import { getErrorMessage } from 'peaks-loop-shared/result';
25
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
25
26
  const SESSION_DIR_PATTERN = /^\d{4}-\d{2}-\d{2}-session-[a-f0-9]+$/;
26
27
  /**
27
28
  * F3-canonical (pre-canonicalization) layout the 5 already-shipped
@@ -133,12 +134,16 @@ function defaultLegacyDotfileScanner(projectRoot) {
133
134
  */
134
135
  function defaultStaleSingleSlotScanner(projectRoot) {
135
136
  const offenders = [];
137
+ const runtimeRoot = defaultStateRoot(projectRoot);
138
+ // The reported path is the project-relative form the doctor prints, derived
139
+ // from the same state root rather than re-composing `.peaks` + `_runtime`.
140
+ const runtimeRootRelative = relative(projectRoot, runtimeRoot);
136
141
  const candidates = [
137
- join(projectRoot, '.peaks', '_runtime', 'active-skill.json'),
142
+ join(runtimeRoot, 'active-skill.json'),
138
143
  join(projectRoot, '.peaks', '.active-skill.json')
139
144
  ];
140
145
  const reported = [
141
- join('.peaks', '_runtime', 'active-skill.json'),
146
+ join(runtimeRootRelative, 'active-skill.json'),
142
147
  join('.peaks', '.active-skill.json')
143
148
  ];
144
149
  for (let i = 0; i < candidates.length; i++) {
@@ -31,6 +31,7 @@
31
31
  import { existsSync } from 'node:fs';
32
32
  import { dirname, join } from 'node:path';
33
33
  import { schemasDir, skillsDir } from 'peaks-loop-shared/paths';
34
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
34
35
  import { PLUGINS } from './plugin-registry.js';
35
36
  import { buildReport } from './report/final-summary.js';
36
37
  /**
@@ -78,7 +79,7 @@ function defaultProjectRootResolver() {
78
79
  * `.peaks/.session.json` exists.
79
80
  */
80
81
  export function isWorkspaceInitializedAt(projectRoot) {
81
- return (existsSync(join(projectRoot, '.peaks', '_runtime', 'session.json')) ||
82
+ return (existsSync(join(defaultStateRoot(projectRoot), 'session.json')) ||
82
83
  existsSync(join(projectRoot, '.peaks', '.session.json')));
83
84
  }
84
85
  function defaultWorkspaceInitializedProbe(projectRootResolver) {
@@ -15,6 +15,7 @@ import { GATE_SOURCE_FOR_DIMENSION } from './final-review-evidence-sources.js';
15
15
  import { blankEvidence, foundEvidence, omittedEvidence, readFailureEvidence } from './final-review-evidence-records.js';
16
16
  import { MAX_EVIDENCE_BYTES_TOTAL, REQUIRED_DIMENSIONS, assertFloorReservationAffordable, sourceUnit } from './final-review-evidence-budget.js';
17
17
  import { evidenceSourcesFor } from './final-review-service.js';
18
+ import { getSessionDir } from '../session/getSessionDir.js';
18
19
  /**
19
20
  * ENOENT is "no such file"; every other errno is "the file is there and this
20
21
  * read failed". Only the first means the source does not exist for this run.
@@ -25,7 +26,10 @@ function classifyReadFailure(error) {
25
26
  }
26
27
  /** Pure read: no commands, no git, no test execution — files only. */
27
28
  export function readEvidence(projectRoot, sessionId, rid, prePostDiffAvailable) {
28
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime', sessionId);
29
+ // The throwing entry: this read phase cannot proceed without a session dir,
30
+ // and its only production caller (`final-review-prepare-command`) refuses
31
+ // the empty / traversal / separator id shapes before reaching here.
32
+ const runtimeRoot = getSessionDir(projectRoot, sessionId);
29
33
  return evidenceSourcesFor(rid, prePostDiffAvailable).map((source) => {
30
34
  // The canonical location first; an older one is tried only when the
31
35
  // canonical file is genuinely ABSENT (see `legacySegments`). A file that
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { readFileSync } from 'node:fs';
10
10
  import { join } from 'node:path';
11
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
11
12
  const FRESH_CONTEXT_HEADING = '## Fresh context';
12
13
  /**
13
14
  * Extract the `## Fresh context` section from a markdown body. Returns the
@@ -27,7 +28,10 @@ export function extractFreshContextBlock(content) {
27
28
  * callers treat `null` as "no block", never a hard error.
28
29
  */
29
30
  export function readFreshContextBlock(projectRoot, sessionId) {
30
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, 'fresh-context.md');
31
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
32
+ if (!resolved.ok)
33
+ return null;
34
+ const path = join(resolved.dir, 'fresh-context.md');
31
35
  let content;
32
36
  try {
33
37
  content = readFileSync(path, 'utf-8');