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
@@ -11,25 +11,24 @@
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
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
22
19
  import { dirname, join } from 'node:path';
23
20
  import { randomBytes } from 'node:crypto';
21
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
24
22
  import { initWorkspace } from '../workspace/workspace-service.js';
25
23
  import { projectRootsMatch, stableRealPath } from '../../shared/path-utils.js';
26
24
  import { tryParseJson } from '../../shared/json-parse.js';
27
25
  import { SessionBindingSchema, SessionFileSchema } from './session-file-schema.js';
28
26
  import { resolveCallerBinding, setCallerBinding } from './caller-binding-service.js';
29
27
  import { resolveCallerProjection } from './resolve-caller-id.js';
28
+ import { getSessionDir, tryGetSessionDir } from './getSessionDir.js';
30
29
  import { getSessionId, getSessionIdCanonical, getSessionMeta, rotateSessionBinding, setSessionMeta } from './session-manager.js';
31
30
  // --- Lower-level helpers the bridge needs (moved verbatim) ---
32
- const SESSION_FILE = join('_runtime', 'session.json');
31
+ const SESSION_FILE = 'session.json';
33
32
  const LEGACY_SESSION_FILE = '.session.json';
34
33
  const META_FILE = 'session.json';
35
34
  // outer (Claude Code / Trae / IDE) session id. Written by the
@@ -37,7 +36,7 @@ const META_FILE = 'session.json';
37
36
  // sub-processes (which do NOT inherit CLAUDE_CODE_SESSION_ID) can still
38
37
  // resolve the current outer session. Lives under the gitignored
39
38
  // `.peaks/_runtime/` tree, so no .gitignore change is required.
40
- const OUTER_SESSION_CACHE_FILE = join('_runtime', '.outer-session-cache.json');
39
+ const OUTER_SESSION_CACHE_FILE = '.outer-session-cache.json';
41
40
  function getLegacySessionFilePath(projectRoot) {
42
41
  return join(projectRoot, '.peaks', LEGACY_SESSION_FILE);
43
42
  }
@@ -51,7 +50,7 @@ function generateSessionId() {
51
50
  return `${date}-session-${random}`;
52
51
  }
53
52
  function getSessionFilePath(projectRoot) {
54
- return join(projectRoot, '.peaks', SESSION_FILE);
53
+ return join(defaultStateRoot(projectRoot), SESSION_FILE);
55
54
  }
56
55
  function readSessionFile(projectRoot) {
57
56
  const sessionFile = getSessionFilePath(projectRoot);
@@ -106,11 +105,12 @@ function writeSessionFile(projectRoot, info) {
106
105
  writeFileSync(sessionFile, JSON.stringify(canonicalInfo, null, 2), 'utf8');
107
106
  }
108
107
  function getMetaFilePath(projectRoot, sessionId) {
109
- return join(projectRoot, '.peaks', '_runtime', sessionId, META_FILE);
108
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
109
+ return resolved.ok ? join(resolved.dir, META_FILE) : null;
110
110
  }
111
111
  function readSessionMeta(projectRoot, sessionId) {
112
112
  const metaPath = getMetaFilePath(projectRoot, sessionId);
113
- if (!existsSync(metaPath))
113
+ if (metaPath === null || !existsSync(metaPath))
114
114
  return null;
115
115
  try {
116
116
  const parsed = tryParseJson(readFileSync(metaPath, 'utf8'), SessionFileSchema);
@@ -122,7 +122,7 @@ function readSessionMeta(projectRoot, sessionId) {
122
122
  }
123
123
  }
124
124
  function writeSessionMeta(projectRoot, sessionId, meta) {
125
- const metaPath = getMetaFilePath(projectRoot, sessionId);
125
+ const metaPath = join(getSessionDir(projectRoot, sessionId), META_FILE);
126
126
  const metaDir = dirname(metaPath);
127
127
  if (!existsSync(metaDir)) {
128
128
  mkdirSync(metaDir, { recursive: true });
@@ -157,7 +157,7 @@ function getCurrentOuterSessionId(projectRoot) {
157
157
  // required. Any IO error or non-string `outerSessionId` field is
158
158
  // treated as a cache miss — never throw.
159
159
  if (projectRoot !== undefined) {
160
- const cachePath = join(projectRoot, '.peaks', OUTER_SESSION_CACHE_FILE);
160
+ const cachePath = join(defaultStateRoot(projectRoot), OUTER_SESSION_CACHE_FILE);
161
161
  if (existsSync(cachePath)) {
162
162
  try {
163
163
  const raw = readFileSync(cachePath, 'utf8');
@@ -12,6 +12,7 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, wri
12
12
  import { join, sep } from 'node:path';
13
13
  import { emitObservabilityEvent } from '../observability/observability-service.js';
14
14
  import { isUnsafePathInput } from '../../shared/path-safety.js';
15
+ import { tryGetSessionDir } from './getSessionDir.js';
15
16
  const CHECKPOINTS_DIR = 'checkpoints';
16
17
  const CHECKPOINT_FILENAME_EXT = '.json';
17
18
  const MAX_CHECKPOINTS = 10;
@@ -25,8 +26,14 @@ export const CHECKPOINT_REASONS = [
25
26
  function toPosix(p) {
26
27
  return p.split(sep).join('/');
27
28
  }
29
+ /**
30
+ * The checkpoints dir, or `null` when the session id cannot name a session
31
+ * dir. The TOTAL entry: the readers here answer "no checkpoints", and the
32
+ * writer — the one frame that cannot proceed — refuses the id itself.
33
+ */
28
34
  function checkpointsDirPath(projectRoot, sessionId) {
29
- return join(projectRoot, '.peaks', '_runtime', sessionId, CHECKPOINTS_DIR);
35
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
36
+ return resolved.ok ? join(resolved.dir, CHECKPOINTS_DIR) : null;
30
37
  }
31
38
  function isoTimestamp(d) {
32
39
  // Replace colons with dashes for filesystem safety. The full ISO is
@@ -38,7 +45,10 @@ export function isValidCheckpointReason(value) {
38
45
  return CHECKPOINT_REASONS.includes(value);
39
46
  }
40
47
  function readSessionLastActivity(projectRoot, sessionId) {
41
- const sessionJsonPath = join(projectRoot, '.peaks', '_runtime', sessionId, 'session.json');
48
+ const sessionDir = tryGetSessionDir(projectRoot, sessionId);
49
+ if (!sessionDir.ok)
50
+ return '';
51
+ const sessionJsonPath = join(sessionDir.dir, 'session.json');
42
52
  if (!existsSync(sessionJsonPath))
43
53
  return '';
44
54
  try {
@@ -87,6 +97,12 @@ export function writeCheckpoint(projectRoot, options) {
87
97
  const createdAt = now.toISOString();
88
98
  const lastActivity = readSessionLastActivity(projectRoot, options.sessionId) || createdAt;
89
99
  const dir = checkpointsDirPath(projectRoot, options.sessionId);
100
+ if (dir === null) {
101
+ // The guard above refuses the traversal shapes; the seam's predicate is
102
+ // also stricter than `isUnsafePathInput` on nesting (`a/b`), and a write
103
+ // cannot proceed without a session dir. Same refusal, same message.
104
+ throw new Error(`Invalid session id: ${options.sessionId} (must be a single path segment)`);
105
+ }
90
106
  mkdirSync(dir, { recursive: true });
91
107
  const snapshot = {
92
108
  sessionId: options.sessionId,
@@ -135,7 +151,10 @@ export function readCheckpoint(path) {
135
151
  return JSON.parse(raw);
136
152
  }
137
153
  export function listCheckpointPaths(projectRoot, sessionId) {
138
- return listCheckpoints(checkpointsDirPath(projectRoot, sessionId))
154
+ const dir = checkpointsDirPath(projectRoot, sessionId);
155
+ if (dir === null)
156
+ return [];
157
+ return listCheckpoints(dir)
139
158
  .sort((a, b) => b.mtimeMs - a.mtimeMs)
140
159
  .map((c) => toPosix(c.path));
141
160
  }
@@ -9,9 +9,11 @@ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, unlinkS
9
9
  import { mkdir as mkdirAsync } from 'node:fs/promises';
10
10
  import { dirname, join, resolve } from 'node:path';
11
11
  import { randomBytes } from 'node:crypto';
12
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
12
13
  import { projectRootsMatch, stableRealPath } from '../../shared/path-utils.js';
13
14
  import { tryParseJson } from '../../shared/json-parse.js';
14
15
  import { SessionBindingSchema, SessionFileSchema } from './session-file-schema.js';
16
+ import { getSessionDir, tryGetSessionDir } from './getSessionDir.js';
15
17
  import { ensureSession } from './session-binding-bridge.js';
16
18
  import { getCallerBinding, getCallerBindingFile, resolveCallerBinding } from './caller-binding-service.js';
17
19
  import { resolveCallerProjection } from './resolve-caller-id.js';
@@ -19,7 +21,7 @@ import { resolveCallerProjection } from './resolve-caller-id.js';
19
21
  // `.peaks/.session.json` path is preserved as a read-only fallback for one
20
22
  // minor release so older CLI versions (or trees that have not been migrated
21
23
  // by `peaks workspace reconcile`) keep working without a forced re-init.
22
- const SESSION_FILE = join('_runtime', 'session.json');
24
+ const SESSION_FILE = 'session.json';
23
25
  const LEGACY_SESSION_FILE = '.session.json';
24
26
  const META_FILE = 'session.json';
25
27
  function getLegacySessionFilePath(projectRoot) {
@@ -86,7 +88,7 @@ function generateSessionId() {
86
88
  * read-only fallback (see `readSessionFile`).
87
89
  */
88
90
  function getSessionFilePath(projectRoot) {
89
- return join(projectRoot, '.peaks', SESSION_FILE);
91
+ return join(defaultStateRoot(projectRoot), SESSION_FILE);
90
92
  }
91
93
  /**
92
94
  * Read existing session info from disk.
@@ -297,17 +299,13 @@ export function setCurrentSessionBinding(projectRoot, sessionId) {
297
299
  return info;
298
300
  }
299
301
  function getMetaFilePath(projectRoot, sessionId) {
300
- // `session.json` (the file written by `setSessionMeta`) lives at the
301
- // canonical runtime home `.peaks/_runtime/<sid>/session.json`, NOT
302
- // at the top-level `.peaks/_runtime/<sid>/session.json` (which would imply
303
- // the legacy session-scoped layout and conflict with the workspace
304
- // service's `_runtime/<sid>/` invariant). The migration in slice
305
- // 003 moved any top-level meta files into the runtime home.
306
- return join(projectRoot, '.peaks', '_runtime', sessionId, META_FILE);
302
+ // Canonical runtime home: `.peaks/_runtime/<sid>/session.json`.
303
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
304
+ return resolved.ok ? join(resolved.dir, META_FILE) : null;
307
305
  }
308
306
  function readSessionMeta(projectRoot, sessionId) {
309
307
  const metaPath = getMetaFilePath(projectRoot, sessionId);
310
- if (!existsSync(metaPath))
308
+ if (metaPath === null || !existsSync(metaPath))
311
309
  return null;
312
310
  try {
313
311
  const parsed = tryParseJson(readFileSync(metaPath, 'utf8'), SessionFileSchema);
@@ -319,13 +317,11 @@ function readSessionMeta(projectRoot, sessionId) {
319
317
  }
320
318
  }
321
319
  function writeSessionMeta(projectRoot, sessionId, meta) {
322
- const metaPath = getMetaFilePath(projectRoot, sessionId);
323
- // The parent dir of that file is the canonical runtime session dir.
324
- const metaDir = dirname(metaPath);
320
+ const metaDir = getSessionDir(projectRoot, sessionId);
325
321
  if (!existsSync(metaDir)) {
326
322
  mkdirSync(metaDir, { recursive: true });
327
323
  }
328
- writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8');
324
+ writeFileSync(join(metaDir, META_FILE), JSON.stringify(meta, null, 2), 'utf8');
329
325
  }
330
326
  /**
331
327
  * Read metadata for a specific session directory.
@@ -368,7 +364,7 @@ export function setSessionTitle(projectRoot, sessionId, title) {
368
364
  * release) but is not authoritative.
369
365
  */
370
366
  export function listSessionMetas(projectRoot) {
371
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
367
+ const runtimeRoot = defaultStateRoot(projectRoot);
372
368
  const peaksRoot = join(projectRoot, '.peaks');
373
369
  const seen = new Set();
374
370
  const result = [];
@@ -526,7 +522,7 @@ export function resolveCallerBoundSession(projectRoot) {
526
522
  */
527
523
  export async function getCurrentSessionDir(projectRoot) {
528
524
  const sessionId = await ensureSession(projectRoot);
529
- return join(projectRoot, '.peaks', '_runtime', sessionId);
525
+ return getSessionDir(projectRoot, sessionId);
530
526
  }
531
527
  /**
532
528
  * List all session directories in the .peaks folder.
@@ -540,7 +536,7 @@ export async function getCurrentSessionDir(projectRoot) {
540
536
  * @returns Array of session IDs
541
537
  */
542
538
  export function listSessions(projectRoot) {
543
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
539
+ const runtimeRoot = defaultStateRoot(projectRoot);
544
540
  const peaksRoot = join(projectRoot, '.peaks');
545
541
  const seen = new Set();
546
542
  const result = [];
@@ -585,7 +581,7 @@ export async function getProjectScanPath(projectRoot) {
585
581
  // ephemeral state under `_runtime/`. The parent `rd/` subdir is
586
582
  // created on demand so the first scanner call has a place to land
587
583
  // (consistent with the legacy behavior pre-1.3.1).
588
- const scanPath = join(projectRoot, '.peaks', '_runtime', sessionId, 'rd', 'project-scan.md');
584
+ const scanPath = join(getSessionDir(projectRoot, sessionId), 'rd', 'project-scan.md');
589
585
  await mkdirAsync(dirname(scanPath), { recursive: true });
590
586
  return scanPath;
591
587
  }
@@ -599,6 +595,6 @@ export function hasProjectScan(projectRoot) {
599
595
  const info = readSessionFile(projectRoot);
600
596
  if (!info)
601
597
  return false;
602
- const scanPath = join(projectRoot, '.peaks', '_runtime', info.sessionId, 'rd', 'project-scan.md');
603
- return existsSync(scanPath);
598
+ const resolved = tryGetSessionDir(projectRoot, info.sessionId);
599
+ return resolved.ok && existsSync(join(resolved.dir, 'rd', 'project-scan.md'));
604
600
  }
@@ -19,7 +19,8 @@
19
19
  * over it may be touched, but never grown. The read half moved here.
20
20
  */
21
21
  import { readdirSync } from 'node:fs';
22
- import { join, resolve } from 'node:path';
22
+ import { resolve } from 'node:path';
23
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
23
24
  import { findProjectRoot } from '../config/config-safety.js';
24
25
  import { getSessionId } from '../session/session-manager.js';
25
26
  import { listPresenceLeases } from './presence-lease-service.js';
@@ -68,7 +69,7 @@ export function resolveBoundSessionId(projectRoot) {
68
69
  */
69
70
  export function collectPresenceLeaseCandidates(projectRoot, boundSessionId) {
70
71
  const candidates = [];
71
- const runtimeRoot = join(projectRoot, '.peaks', '_runtime');
72
+ const runtimeRoot = defaultStateRoot(projectRoot);
72
73
  let entries = [];
73
74
  try {
74
75
  entries = readdirSync(runtimeRoot, { withFileTypes: true })
@@ -12,7 +12,7 @@ import { existsSync, readdirSync, writeFileSync } from 'node:fs';
12
12
  import { join } from 'node:path';
13
13
  import { STALE_HEARTBEAT_MS, STALE_STARTED_AFTER_MS } from './presence-lease-types.js';
14
14
  import { normalizePresenceGate, readPresenceGate } from './presence-gate.js';
15
- import { callerIndexPath, leaseDir, leaseFilePath, presenceError, readJsonStrict, sessionRuntimeRoot, writeAtomic } from './presence-lease-store.js';
15
+ import { applyStaleLease, callerIndexPath, leaseDir, leaseFilePath, presenceError, readJsonStrict, sessionRuntimeRoot, writeAtomic } from './presence-lease-store.js';
16
16
  import { WORKFLOW_ID_REGEX } from '../workflow/workflow-graph-types.js';
17
17
  import { PEAKS_SESSION_NOT_BOUND, PEAKS_CALLER_NOT_RESOLVED, PEAKS_GRAPH_REF_BROKEN } from '../workflow/workflow-graph-store.js';
18
18
  import { ensureGraphExists } from '../workflow/workflow-graph-ensure.js';
@@ -277,22 +277,14 @@ export function gcStalePresenceLeases(input) {
277
277
  const heartbeatStale = Number.isFinite(lastHeartbeatMs) && now - lastHeartbeatMs > STALE_HEARTBEAT_MS;
278
278
  const startedStale = Number.isFinite(startedAtMs) && now - startedAtMs > STALE_STARTED_AFTER_MS;
279
279
  if (heartbeatStale && startedStale) {
280
- // Verify graphRef exists before removing; missing graph is a typed
281
- // warning, not a silent removal.
282
- const graphPath = join(sessionRuntimeRoot(input.projectRoot, lease.workflowId), lease.graphRef);
283
- // For test seams, `lease.workflowId` may not match a real session; we
284
- // skip the existsSync check when the lease points at a non-canonical
285
- // path (the test seam is responsible for surfacing its own warning).
286
- if (lease.graphRef === 'graphs/missing.json') {
287
- warnings.push({
288
- code: PEAKS_GRAPH_REF_BROKEN,
289
- leaseRef: lease.graphRef,
290
- message: 'graph file missing'
291
- });
280
+ // The per-lease decision — resolve the graph path, or report why it
281
+ // cannot be resolved — lives in the store with the path helper it calls.
282
+ if (applyStaleLease(input.projectRoot, lease, warnings) === 'removed') {
283
+ removed += 1;
284
+ }
285
+ else {
292
286
  retained += 1;
293
- continue;
294
287
  }
295
- removed += 1;
296
288
  }
297
289
  else {
298
290
  retained += 1;
@@ -31,3 +31,29 @@ export declare function callerIndexPath(projectRoot: string, sessionId: string,
31
31
  export declare function writeAtomic(path: string, body: string): void;
32
32
  /** Read JSON safely; throws with `code` set. */
33
33
  export declare function readJsonStrict<T>(path: string, codeOnError: string): T;
34
+ /** A GC warning row — the same shape `GcResult.warnings` carries. */
35
+ export interface LeaseWarningRow {
36
+ readonly code: string;
37
+ readonly leaseRef: string;
38
+ readonly message: string;
39
+ }
40
+ /**
41
+ * Decide what ONE stale lease contributes to a GC sweep: `removed`, or
42
+ * `retained` with a warning row pushed onto `warnings`.
43
+ *
44
+ * A lease is read off disk and never re-validated, so `workflowId` can hold a
45
+ * shape `sessionRuntimeRoot` refuses — `'.'` passes `WORKFLOW_ID_REGEX`. That
46
+ * helper was a total `join` before the workspace-runtime extraction and throws
47
+ * now, so the refusal is caught HERE and turned back into the value GC already
48
+ * reports for an unreadable lease: a retained count plus a warning row. The
49
+ * sweep stays total, and the reason travels in the row rather than being
50
+ * swallowed.
51
+ *
52
+ * Lives beside the path helper it calls rather than in the service, which is
53
+ * over the raw-line cap and may only shrink. Structurally typed on the two
54
+ * fields it reads, so the store needs no dependency on the lease record.
55
+ */
56
+ export declare function applyStaleLease(projectRoot: string, lease: {
57
+ readonly workflowId: string;
58
+ readonly graphRef: string;
59
+ }, warnings: LeaseWarningRow[]): 'removed' | 'retained';
@@ -12,7 +12,10 @@
12
12
  * decisions the service made before, in the same place in the flow.
13
13
  */
14
14
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
15
- import { dirname, join, resolve, sep } from 'node:path';
15
+ import { dirname, join, resolve } from 'node:path';
16
+ import { normalizePath } from '../../shared/path-utils.js';
17
+ import { getSessionDir } from '../session/getSessionDir.js';
18
+ import { PEAKS_GRAPH_REF_BROKEN } from '../workflow/workflow-graph-store.js';
16
19
  export function presenceError(code, message) {
17
20
  const err = new Error(message);
18
21
  err.name = 'PresenceError';
@@ -21,8 +24,19 @@ export function presenceError(code, message) {
21
24
  }
22
25
  /** Resolve the session runtime root. */
23
26
  export function sessionRuntimeRoot(projectRoot, sessionId) {
24
- const root = resolve(projectRoot);
25
- return join(root, '.peaks', '_runtime', sessionId);
27
+ // `resolve` first: callers may hand a relative root and this helper has
28
+ // always returned an absolute path. Then the canonical session-dir entry.
29
+ return getSessionDir(resolve(projectRoot), sessionId);
30
+ }
31
+ /**
32
+ * Is `path` the session root itself, or under it? Compared through
33
+ * `normalizePath`: the session dir is emitted with forward slashes while
34
+ * `join()` emits the platform separator, so the raw strings differ on Windows.
35
+ */
36
+ function isUnderSessionRoot(path, root) {
37
+ const pathKey = normalizePath(path);
38
+ const rootKey = normalizePath(root);
39
+ return pathKey === rootKey || pathKey.startsWith(`${rootKey}/`);
26
40
  }
27
41
  /** Resolve the lease directory. */
28
42
  export function leaseDir(projectRoot, sessionId) {
@@ -42,7 +56,7 @@ export function leaseFilePath(projectRoot, sessionId, callerId, workflowId) {
42
56
  const safeWorkflow = workflowId.replace(/[^a-zA-Z0-9._-]/g, '_');
43
57
  const path = join(leaseDir(projectRoot, sessionId), `presence-${safeCaller}-${safeWorkflow}.json`);
44
58
  const root = sessionRuntimeRoot(projectRoot, sessionId);
45
- if (!path.startsWith(root + sep) && path !== root) {
59
+ if (!isUnderSessionRoot(path, root)) {
46
60
  throw presenceError('PEAKS_GRAPH_REF_BROKEN', `lease path escapes session root: ${path}`);
47
61
  }
48
62
  return path;
@@ -52,7 +66,7 @@ export function callerIndexPath(projectRoot, sessionId, callerId) {
52
66
  const safeCaller = callerId.replace(/[^a-zA-Z0-9._-]/g, '_');
53
67
  const path = join(presenceIndexDir(projectRoot, sessionId), `${safeCaller}.json`);
54
68
  const root = sessionRuntimeRoot(projectRoot, sessionId);
55
- if (!path.startsWith(root + sep) && path !== root) {
69
+ if (!isUnderSessionRoot(path, root)) {
56
70
  throw presenceError('PEAKS_GRAPH_REF_BROKEN', `index path escapes session root: ${path}`);
57
71
  }
58
72
  return path;
@@ -92,3 +106,44 @@ export function readJsonStrict(path, codeOnError) {
92
106
  throw presenceError(codeOnError, `JSON malformed: ${err.message}`);
93
107
  }
94
108
  }
109
+ /**
110
+ * Decide what ONE stale lease contributes to a GC sweep: `removed`, or
111
+ * `retained` with a warning row pushed onto `warnings`.
112
+ *
113
+ * A lease is read off disk and never re-validated, so `workflowId` can hold a
114
+ * shape `sessionRuntimeRoot` refuses — `'.'` passes `WORKFLOW_ID_REGEX`. That
115
+ * helper was a total `join` before the workspace-runtime extraction and throws
116
+ * now, so the refusal is caught HERE and turned back into the value GC already
117
+ * reports for an unreadable lease: a retained count plus a warning row. The
118
+ * sweep stays total, and the reason travels in the row rather than being
119
+ * swallowed.
120
+ *
121
+ * Lives beside the path helper it calls rather than in the service, which is
122
+ * over the raw-line cap and may only shrink. Structurally typed on the two
123
+ * fields it reads, so the store needs no dependency on the lease record.
124
+ */
125
+ export function applyStaleLease(projectRoot, lease, warnings) {
126
+ try {
127
+ sessionRuntimeRoot(projectRoot, lease.workflowId);
128
+ }
129
+ catch (err) {
130
+ warnings.push({
131
+ code: PEAKS_GRAPH_REF_BROKEN,
132
+ leaseRef: lease.graphRef,
133
+ message: `lease workflowId cannot be resolved: ${err.message}`
134
+ });
135
+ return 'retained';
136
+ }
137
+ // For test seams, `workflowId` may not match a real session; the
138
+ // graph-exists check is skipped for the sentinel a seam points at, because
139
+ // the seam is responsible for surfacing its own warning.
140
+ if (lease.graphRef === 'graphs/missing.json') {
141
+ warnings.push({
142
+ code: PEAKS_GRAPH_REF_BROKEN,
143
+ leaseRef: lease.graphRef,
144
+ message: 'graph file missing'
145
+ });
146
+ return 'retained';
147
+ }
148
+ return 'removed';
149
+ }
@@ -1,7 +1,9 @@
1
1
  import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join, resolve } from 'node:path';
3
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
3
4
  import { tryParseJson } from '../../shared/json-parse.js';
4
5
  import { ensureMemoryBootstrap } from '../memory/project-memory-service.js';
6
+ import { getSessionDir } from '../session/getSessionDir.js';
5
7
  import { getSessionId, getSessionMeta } from '../session/session-manager.js';
6
8
  import { SessionIdentitySchema } from '../session/session-file-schema.js';
7
9
  // Slice 4.0.8 compat shim: the canonical write path lives in
@@ -81,8 +83,10 @@ function getCurrentOuterSessionId() {
81
83
  // projection (`.peaks/_runtime/<sid>/leases/presence-*.json`) is the
82
84
  // only source of truth. The legacy constants `PRESENCE_FILE` and
83
85
  // `PRESENCE_FILE_LEGACY` are deleted; readers use `listPresenceLeases`.
84
- const SESSION_FILE = join('.peaks', '_runtime', 'session.json');
86
+ const SESSION_FILE = 'session.json';
85
87
  const SESSION_FILE_LEGACY = '.peaks/.session.json';
88
+ // Deprecated single-slot marker; a module constant for the runtime-layout drift guard.
89
+ const STALE_RUNTIME_PRESENCE_FILE = 'active-skill.json';
86
90
  /**
87
91
  * Resolve the active peaks session id.
88
92
  *
@@ -115,7 +119,7 @@ export function getCurrentSessionId(projectRootOverride) {
115
119
  const callerBound = getSessionId(projectRoot);
116
120
  if (callerBound !== null)
117
121
  return callerBound;
118
- const sessionPath = resolve(projectRoot, SESSION_FILE);
122
+ const sessionPath = resolve(defaultStateRoot(projectRoot), SESSION_FILE);
119
123
  const legacyPath = resolve(projectRoot, SESSION_FILE_LEGACY);
120
124
  // Back-compat window: prefer the new canonical path; fall back to the
121
125
  // legacy `.peaks/.session.json` for one minor release.
@@ -255,7 +259,7 @@ export function setSkillPresenceForCaller(projectRootOverride, callerId, peakSes
255
259
  * future slices; the inverse import would deadlock).
256
260
  */
257
261
  function getActiveSkillFileForCallerPath(projectRoot, peakSessionId, callerId) {
258
- return resolve(projectRoot, '.peaks', '_runtime', peakSessionId, `active-skill-${callerId}.json`);
262
+ return join(getSessionDir(projectRoot, peakSessionId), `active-skill-${callerId}.json`);
259
263
  }
260
264
  /**
261
265
  * Record the informational outer-session mismatch on the presence envelope.
@@ -570,25 +574,14 @@ export function clearSkillPresence(projectRootOverride) {
570
574
  // `cleared` / `reason`). Do not read the paragraph above as a
571
575
  // promise about this function.
572
576
  //
573
- // The shim still removes the legacy `active-skill.json` /
574
- // `.peaks/.active-skill.json` so a stale marker from a prior CLI
575
- // version cannot resurrect after a fresh `clear`. The canonical
576
- // lease + index entries are NOT touched by this shim — they
577
- // Slice 4.0.11 statusline-sid-scoped-lease C: the deprecated
578
- // single-slot presence files (`.peaks/_runtime/active-skill.json`
579
- // and `.peaks/.active-skill.json`) are removed. The canonical
580
- // sid-scoped lease projection (under
581
- // `.peaks/_runtime/<sid>/leases/`) is untouched here — workflow
582
- // leases route through `terminalizeWorkflow`, NOT this shim.
583
- //
584
- // This shim remains as a best-effort stale-file cleanup for
585
- // projects that still carry the deprecated single-slot file from
586
- // a pre-4.0.11 CLI version. After one minor release the legacy
587
- // paths are gone and the loop is a no-op. Returns true when a
588
- // stale file was actually removed.
577
+ // Best-effort cleanup of the deprecated single-slot presence files
578
+ // (`.peaks/_runtime/active-skill.json` and `.peaks/.active-skill.json`); the
579
+ // canonical lease + index entries are untouched — workflow leases route
580
+ // through `terminalizeWorkflow`, NOT this shim. Returns true when a stale
581
+ // file was actually removed.
589
582
  const projectRoot = resolveProjectRoot(projectRootOverride);
590
583
  const candidates = [
591
- resolve(projectRoot, '.peaks', '_runtime', 'active-skill.json'),
584
+ join(defaultStateRoot(projectRoot), STALE_RUNTIME_PRESENCE_FILE),
592
585
  resolve(projectRoot, '.peaks', '.active-skill.json')
593
586
  ];
594
587
  let cleared = false;
@@ -10,6 +10,7 @@
10
10
  import { readFileSync } from 'node:fs';
11
11
  import { join, resolve } from 'node:path';
12
12
  import { decideCompactStatusline } from '../compact-statusline/compact-statusline-service.js';
13
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
13
14
  import { getSessionIdCanonical } from '../session/session-manager.js';
14
15
  import { readActiveDispatchIndex } from '../dispatch/dispatch-record-writer.js';
15
16
  /**
@@ -26,9 +27,13 @@ import { readActiveDispatchIndex } from '../dispatch/dispatch-record-writer.js';
26
27
  * - `state` is missing, non-string, or empty string
27
28
  */
28
29
  export function read24hOverlay(projectRoot, sessionId) {
29
- if (!projectRoot || !sessionId)
30
+ // An empty id is refused by the total entry below like any other bad id.
31
+ if (!projectRoot)
30
32
  return null;
31
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, '24h-state.json');
33
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
34
+ if (!resolved.ok)
35
+ return null;
36
+ const path = join(resolved.dir, '24h-state.json');
32
37
  let raw;
33
38
  try {
34
39
  raw = readFileSync(path, 'utf8');
@@ -17,11 +17,14 @@
17
17
  */
18
18
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';
19
19
  import { join } from 'node:path';
20
+ import { getSessionDir } from '../session/getSessionDir.js';
20
21
  import { isDispatchStatus, isOutcome } from '../dispatch/dispatch-record-writer.js';
21
22
  export const ARCHIVE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
22
23
  /** Build the canonical archive dir for a given session + slice id. */
23
24
  export function archiveDir(projectRoot, sessionId, sliceId) {
24
- return join(projectRoot, '.peaks', '_runtime', sessionId, '_archive', '_sub_agents', sliceId);
25
+ // A write target (mkdir + rename): the throwing entry, so a refused sid
26
+ // cannot produce an archive tree outside the session.
27
+ return join(getSessionDir(projectRoot, sessionId), '_archive', '_sub_agents', sliceId);
25
28
  }
26
29
  /** Build the in-flight subdir (records not yet disposed). */
27
30
  export function inFlightArchiveDir(projectRoot, sessionId, sliceId) {
@@ -26,6 +26,7 @@
26
26
  */
27
27
  import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs';
28
28
  import { isAbsolute, join, sep as pathSep } from 'node:path';
29
+ import { getSessionDir } from '../session/getSessionDir.js';
29
30
  const SUPPORTED_LANGUAGES = new Set([
30
31
  'generic',
31
32
  'typescript',
@@ -139,7 +140,7 @@ export function detectMissingProjectStandards(projectRoot, language) {
139
140
  export function getStandardsCheckedMarkerPath(projectRoot, sessionId) {
140
141
  const normalizedRoot = normalizeProjectRoot(projectRoot);
141
142
  // Canonical session runtime dir — see `.peaks/memory/session-dir-canonical-resolver-must-route-all-writes.md`.
142
- return join(normalizedRoot, '.peaks', '_runtime', sessionId, '.standards-checked');
143
+ return join(getSessionDir(normalizedRoot, sessionId), '.standards-checked');
143
144
  }
144
145
  /**
145
146
  * Mark this session as "standards checked" so subsequent invocations can
@@ -26,9 +26,10 @@
26
26
  import { createHash } from 'node:crypto';
27
27
  import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, unlinkSync, statSync } from 'node:fs';
28
28
  import { join, dirname, resolve } from 'node:path';
29
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
29
30
  export const TEST_CACHE_DIR = 'test-cache';
30
31
  export function testCacheDir(projectRoot) {
31
- return join(projectRoot, '.peaks', '_runtime', TEST_CACHE_DIR);
32
+ return join(defaultStateRoot(projectRoot), TEST_CACHE_DIR);
32
33
  }
33
34
  export function testCachePath(projectRoot, filePath) {
34
35
  const abs = resolve(filePath);
@@ -16,6 +16,8 @@
16
16
  */
17
17
  import { existsSync, renameSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
+ import { defaultStateRoot } from 'peaks-loop-workspace-runtime';
20
+ import { getSessionDir } from '../session/getSessionDir.js';
19
21
  const QA_DIR = 'qa';
20
22
  /** File name (with `<rid>` suffix) for the per-request security findings delta. */
21
23
  export const SECURITY_FINDINGS_SUFFIXED = (rid) => `security-findings-${rid}.md`;
@@ -48,10 +50,12 @@ function canonicalQaDir(projectRoot, sessionId) {
48
50
  // as the on-disk session dir name (it equals the sessionId under
49
51
  // the session-axis layout). Under v2.16.0 layouts the same string
50
52
  // was the change-id dir name.
51
- return join(projectRoot, '.peaks', '_runtime', sessionId, QA_DIR);
53
+ return join(getSessionDir(projectRoot, sessionId), QA_DIR);
52
54
  }
53
55
  function legacyChangeAxisQaDir(projectRoot, sessionId) {
54
- return join(projectRoot, '.peaks', '_runtime', 'change', sessionId, QA_DIR);
56
+ // A NON-session child of the runtime root (`_runtime/change/<id>/`), so the
57
+ // state-root entry is the one that names it; the id is not a session dir.
58
+ return join(defaultStateRoot(projectRoot), 'change', sessionId, QA_DIR);
55
59
  }
56
60
  function legacyMisplacedQaDir(projectRoot, sessionId) {
57
61
  return join(projectRoot, '.peaks', sessionId, QA_DIR);
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { type ArtifactPrerequisite, type RequestType } from '../artifacts/artifact-prerequisites.js';
10
10
  import { rdGatesForType } from './pipeline-verify-rd-phase.js';
11
- import type { RequestArtifactRole, RequestArtifactState } from '../artifacts/request-artifact-service.js';
11
+ import { type RequestArtifactRole, type RequestArtifactState } from '../artifacts/request-artifact-service.js';
12
12
  import type { PipelineGate } from './pipeline-verify-types.js';
13
13
  export declare function extractState(markdown: string): string;
14
14
  /** The rid's artifact file, read from ONE session: `sessionId` is required, and