peaks-loop 4.1.26 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +160 -0
  3. package/contracts/readonly-argv-whitelist.json +116 -0
  4. package/dist/cli/commands/code-auto-compact-command.js +15 -3
  5. package/dist/cli/commands/core/session-info-command.js +3 -4
  6. package/dist/cli/commands/core/skill-presence-housekeeping-commands.js +7 -1
  7. package/dist/cli/commands/dashboard-long-run.js +2 -1
  8. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  9. package/dist/cli/commands/job-state-root.js +4 -2
  10. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  11. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  12. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  13. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  14. package/dist/cli/commands/mut-commands-helpers.js +53 -80
  15. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  16. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  17. package/dist/cli/commands/outer-cache-commands.js +3 -2
  18. package/dist/cli/commands/playwright-session-store.js +5 -2
  19. package/dist/cli/commands/project-context-command.js +7 -2
  20. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  21. package/dist/cli/commands/request-transition-preflight.js +2 -2
  22. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  23. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  24. package/dist/cli/commands/workspace/init-actions.js +5 -0
  25. package/dist/cli/commands/workspace/init-context.js +1 -0
  26. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  27. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  28. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  29. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  30. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  31. package/dist/cli/commands/worktree-lease-git.js +21 -44
  32. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  33. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  34. package/dist/cli/commands/worktree-lease-load.js +37 -9
  35. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  36. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  37. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  38. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  39. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  40. package/dist/cli/commands/worktree-lease-session.js +9 -6
  41. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  42. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  43. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  44. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  45. package/dist/cli/commands/worktree-lease-store.js +3 -2
  46. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  47. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  48. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  49. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  50. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  51. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  52. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  53. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  54. package/dist/services/capability-audit-service/runner.js +4 -1
  55. package/dist/services/capability-baseline/store.js +2 -1
  56. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  57. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  58. package/dist/services/code/auto-compact-artifacts.js +42 -10
  59. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  60. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  61. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  62. package/dist/services/code/auto-compact-envelopes.js +18 -4
  63. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  64. package/dist/services/code/emit-handoff.js +8 -1
  65. package/dist/services/code/job-shape-decision.js +13 -2
  66. package/dist/services/code/job-shape-provisional.js +9 -1
  67. package/dist/services/code/post-compact-detector.js +9 -1
  68. package/dist/services/code/step-08-session-readers.js +14 -5
  69. package/dist/services/compact/request-transition-hook.js +6 -1
  70. package/dist/services/compact/suggest-service.js +8 -1
  71. package/dist/services/context/post-compact-reinjection.js +15 -14
  72. package/dist/services/context/spillover-store.js +2 -1
  73. package/dist/services/dispatch/contract-store.d.ts +11 -4
  74. package/dist/services/dispatch/contract-store.js +21 -8
  75. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  76. package/dist/services/doctor/doctor-service/index.js +2 -1
  77. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  78. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  79. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  80. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  81. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  82. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  83. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  84. package/dist/services/loop/monotonic-runner.js +2 -1
  85. package/dist/services/loop/spec-service.js +10 -9
  86. package/dist/services/mcp/context-tool.d.ts +3 -0
  87. package/dist/services/mcp/context-tool.js +135 -0
  88. package/dist/services/mcp/surface.js +7 -1
  89. package/dist/services/mcp/tools.js +3 -1
  90. package/dist/services/memory/project-context-service.d.ts +10 -1
  91. package/dist/services/memory/project-context-service.js +13 -6
  92. package/dist/services/observability/jsonl-store.js +4 -1
  93. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  94. package/dist/services/prd/prd-blocks-checker.js +12 -6
  95. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  96. package/dist/services/prd/project-scan-body-tables.js +185 -0
  97. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  98. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  99. package/dist/services/prd/project-scan-content.d.ts +24 -0
  100. package/dist/services/prd/project-scan-content.js +207 -0
  101. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  102. package/dist/services/prd/project-scan-existing-state.js +61 -0
  103. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  104. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  105. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  106. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  107. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  108. package/dist/services/prd/project-scan-library-versions.js +135 -0
  109. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  110. package/dist/services/prd/project-scan-techstack.js +167 -0
  111. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  112. package/dist/services/sc/sc-service.js +8 -8
  113. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  114. package/dist/services/scan/api-diff-recorded.js +5 -5
  115. package/dist/services/session/binding-status-service.js +2 -1
  116. package/dist/services/session/binding-store.js +6 -7
  117. package/dist/services/session/caller-binding-service.js +5 -2
  118. package/dist/services/session/getSessionDir.d.ts +4 -0
  119. package/dist/services/session/getSessionDir.js +38 -13
  120. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  121. package/dist/services/session/session-binding-bridge.js +13 -13
  122. package/dist/services/session/session-checkpoint-service.js +22 -3
  123. package/dist/services/session/session-manager.js +16 -20
  124. package/dist/services/skills/presence-lease-resolver.js +3 -2
  125. package/dist/services/skills/presence-lease-service.js +7 -15
  126. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  127. package/dist/services/skills/presence-lease-store.js +60 -5
  128. package/dist/services/skills/skill-presence-service.js +13 -20
  129. package/dist/services/skills/skill-statusline-model.js +7 -2
  130. package/dist/services/slice/slice-archive-service.js +4 -1
  131. package/dist/services/standards/missing-standards-detector.js +2 -1
  132. package/dist/services/test-cache/test-cache-service.js +2 -1
  133. package/dist/services/workflow/artifact-paths.js +6 -2
  134. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  135. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  136. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  137. package/dist/services/workflow/workflow-state-store.js +11 -4
  138. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  139. package/dist/services/workspace/reconcile-migrate.js +2 -2
  140. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  141. package/dist/services/workspace/reconcile-service.js +11 -11
  142. package/dist/services/workspace/workspace-service.js +5 -5
  143. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  144. package/dist/services/worktree/dispatch-provenance.js +9 -2
  145. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  146. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  147. package/dist/shared/runtime-root.js +6 -1
  148. package/package.json +6 -5
  149. package/skills/peaks-code/SKILL.md +1 -1
  150. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
  151. package/skills/peaks-mut/SKILL.md +6 -2
  152. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  153. package/dist/services/worktree/git-worktree-parser.js +0 -55
  154. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  155. package/dist/services/worktree/worktree-lease-types.js +0 -9
  156. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  157. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The `techStack` snapshot a project scan records, derived from the project's
3
+ * own `package.json` plus its lockfile sentinels.
4
+ *
5
+ * WHY IT IS DERIVED AND NOT WRITTEN AS A LITERAL. The create path used to
6
+ * hard-code `techStack: {}` and a `Language | TypeScript (best-effort — re-confirm
7
+ * via package.json devDeps)` table row, so the FIRST write was already
8
+ * uninformative and a refresh had nothing better to say. Every value here is read
9
+ * from the project, which is what makes a refresh worth running.
10
+ *
11
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
12
+ * 300-line cap; the refresh path imports `deriveTechStack` from here.
13
+ */
14
+ /** The `techStack` snapshot, derived from `package.json` + lockfile sentinels. */
15
+ export declare function deriveTechStack(projectRoot: string): Record<string, string>;
16
+ /**
17
+ * Merge a freshly derived snapshot into the one already on disk.
18
+ *
19
+ * WHY A REFRESH MERGES. `techStack` is the one managed field whose values a
20
+ * human also edits: a project owner routinely adds a row the derivation knows
21
+ * nothing about (`lintTool`, a pinned-version note), and rewrites `buildTool`
22
+ * into something more useful than the raw script. Rewriting the map wholesale
23
+ * would silently undo that on the next `peaks project context` — the same class
24
+ * of sediment loss the refresh exists to prevent on every other field.
25
+ *
26
+ * The rule, stated so it can be checked against the code:
27
+ * - a key the derivation produces → the derived value wins, EXCEPT when that
28
+ * value is a truncated build script and the file already carries a fuller
29
+ * one (`isTruncated` above: less information must not displace more);
30
+ * - a key the derivation CAN produce but did not → dropped (it is stale, not
31
+ * sediment — see DERIVED_KEYS);
32
+ * - any other key → carried over untouched (the derivation has no opinion).
33
+ */
34
+ export declare function mergeTechStack(existing: Readonly<Record<string, string>>, derived: Readonly<Record<string, string>>): Record<string, string>;
@@ -0,0 +1,167 @@
1
+ /**
2
+ * The `techStack` snapshot a project scan records, derived from the project's
3
+ * own `package.json` plus its lockfile sentinels.
4
+ *
5
+ * WHY IT IS DERIVED AND NOT WRITTEN AS A LITERAL. The create path used to
6
+ * hard-code `techStack: {}` and a `Language | TypeScript (best-effort — re-confirm
7
+ * via package.json devDeps)` table row, so the FIRST write was already
8
+ * uninformative and a refresh had nothing better to say. Every value here is read
9
+ * from the project, which is what makes a refresh worth running.
10
+ *
11
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
12
+ * 300-line cap; the refresh path imports `deriveTechStack` from here.
13
+ */
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { z } from 'zod';
17
+ import { tryParseJson } from '../../shared/json-parse.js';
18
+ /** A derived build script longer than this is truncated in the snapshot. */
19
+ const BUILD_TOOL_MAX = 100;
20
+ /**
21
+ * The `package.json` keys this derivation reads, and nothing more.
22
+ * `looseObject` on purpose: a manifest carries far more than this reader
23
+ * consumes, and validation is not licence to reject the rest of the file.
24
+ */
25
+ const packageManifestSchema = z.looseObject({
26
+ packageManager: z.string().optional(),
27
+ engines: z.looseObject({ node: z.string().optional() }).optional(),
28
+ scripts: z.looseObject({ build: z.string().optional() }).optional(),
29
+ dependencies: z.record(z.string(), z.string()).optional(),
30
+ devDependencies: z.record(z.string(), z.string()).optional()
31
+ });
32
+ /** Lockfiles in precedence order — the first one present names the manager. */
33
+ const LOCKFILE_PACKAGE_MANAGERS = [
34
+ ['pnpm-lock.yaml', 'pnpm'],
35
+ ['package-lock.json', 'npm'],
36
+ ['yarn.lock', 'yarn'],
37
+ ['bun.lockb', 'bun']
38
+ ];
39
+ function readManifestText(manifestPath) {
40
+ let text;
41
+ try {
42
+ text = readFileSync(manifestPath, 'utf8');
43
+ }
44
+ catch {
45
+ text = undefined;
46
+ }
47
+ return text;
48
+ }
49
+ function readManifest(projectRoot) {
50
+ const manifestPath = join(projectRoot, 'package.json');
51
+ if (!existsSync(manifestPath))
52
+ return null;
53
+ // A malformed — or unreadable — manifest is a soft signal, not a failure:
54
+ // `scanLibraries` already reports it as a warning, and the snapshot degrades to
55
+ // the fields that need no manifest rather than failing the whole refresh.
56
+ // Measured 2026-11-16: an unreadable `package.json` (e.g. a directory of that
57
+ // name) threw EISDIR out of `peaks project context`, which is an everyday
58
+ // command and must not fail over a scan snapshot nobody asked for.
59
+ const raw = readManifestText(manifestPath);
60
+ if (raw === undefined)
61
+ return null;
62
+ const parsed = tryParseJson(raw, packageManifestSchema);
63
+ return parsed.ok ? parsed.value : null;
64
+ }
65
+ function detectLanguage(projectRoot, manifest) {
66
+ const declaresTypeScript = manifest?.devDependencies?.['typescript'] !== undefined ||
67
+ manifest?.dependencies?.['typescript'] !== undefined;
68
+ return declaresTypeScript || existsSync(join(projectRoot, 'tsconfig.json'))
69
+ ? 'typescript'
70
+ : 'javascript';
71
+ }
72
+ function detectPackageManager(projectRoot, manifest) {
73
+ const declared = manifest?.packageManager;
74
+ if (declared !== undefined)
75
+ return declared;
76
+ for (const [lockfile, packageManager] of LOCKFILE_PACKAGE_MANAGERS) {
77
+ if (existsSync(join(projectRoot, lockfile)))
78
+ return packageManager;
79
+ }
80
+ return 'unknown';
81
+ }
82
+ /** `node>=24.0.0 (active v24.12.0)` — the floor from `engines`, plus the
83
+ * runtime the snapshot was taken on. */
84
+ function detectRuntime(manifest) {
85
+ const active = process.versions.node;
86
+ const floor = manifest?.engines?.node;
87
+ return floor === undefined ? `node v${active}` : `node${floor} (active v${active})`;
88
+ }
89
+ function detectBuildTool(manifest) {
90
+ const build = manifest?.scripts?.build;
91
+ if (build === undefined)
92
+ return null;
93
+ return build.length <= BUILD_TOOL_MAX ? build : `${build.slice(0, BUILD_TOOL_MAX)}…`;
94
+ }
95
+ /**
96
+ * True when the derived value is a TRUNCATED build script — a value that records
97
+ * "there is a build script, and it starts like this", not what the build is.
98
+ *
99
+ * WHY THIS MATTERS. `buildTool` is the one derived key a project owner
100
+ * realistically rewrites: a hand-written `tsc -p tsconfig.build.json` says what
101
+ * the build IS, while the derived value is the raw `scripts.build` cut at 100
102
+ * chars. Measured 2026-11-16 on this repository: a refresh replaced that owner
103
+ * line with
104
+ * `node ./scripts/sync-version.mjs && node ./scripts/clean-dist.mjs && pnpm -r --filter "./packages/*" …`.
105
+ * A truncated value is strictly LESS informative than the line it would replace,
106
+ * so it yields to whatever is on disk.
107
+ */
108
+ function isTruncated(buildTool) {
109
+ return buildTool.length > BUILD_TOOL_MAX;
110
+ }
111
+ /** The `techStack` snapshot, derived from `package.json` + lockfile sentinels. */
112
+ export function deriveTechStack(projectRoot) {
113
+ const manifest = readManifest(projectRoot);
114
+ const techStack = {
115
+ language: detectLanguage(projectRoot, manifest),
116
+ packageManager: detectPackageManager(projectRoot, manifest),
117
+ runtime: detectRuntime(manifest)
118
+ };
119
+ const buildTool = detectBuildTool(manifest);
120
+ if (buildTool !== null)
121
+ techStack['buildTool'] = buildTool;
122
+ return techStack;
123
+ }
124
+ /**
125
+ * Every key `deriveTechStack` can ever emit. A key in this set that the current
126
+ * derivation did not produce is STALE — the machine fact it recorded has gone
127
+ * away — and must not be carried over. This is the second half of the merge:
128
+ * without it, a project that deletes its `scripts.build` would have the old
129
+ * `buildTool` rewritten back on every refresh, forever, from a machine value
130
+ * that no longer has a source.
131
+ */
132
+ const DERIVED_KEYS = new Set([
133
+ 'language',
134
+ 'packageManager',
135
+ 'runtime',
136
+ 'buildTool'
137
+ ]);
138
+ /**
139
+ * Merge a freshly derived snapshot into the one already on disk.
140
+ *
141
+ * WHY A REFRESH MERGES. `techStack` is the one managed field whose values a
142
+ * human also edits: a project owner routinely adds a row the derivation knows
143
+ * nothing about (`lintTool`, a pinned-version note), and rewrites `buildTool`
144
+ * into something more useful than the raw script. Rewriting the map wholesale
145
+ * would silently undo that on the next `peaks project context` — the same class
146
+ * of sediment loss the refresh exists to prevent on every other field.
147
+ *
148
+ * The rule, stated so it can be checked against the code:
149
+ * - a key the derivation produces → the derived value wins, EXCEPT when that
150
+ * value is a truncated build script and the file already carries a fuller
151
+ * one (`isTruncated` above: less information must not displace more);
152
+ * - a key the derivation CAN produce but did not → dropped (it is stale, not
153
+ * sediment — see DERIVED_KEYS);
154
+ * - any other key → carried over untouched (the derivation has no opinion).
155
+ */
156
+ export function mergeTechStack(existing, derived) {
157
+ const carried = Object.fromEntries(Object.entries(existing).filter(([key]) => !DERIVED_KEYS.has(key)));
158
+ const onDiskBuildTool = existing['buildTool'];
159
+ const derivedBuildTool = derived['buildTool'];
160
+ const keepsOwnerBuildTool = onDiskBuildTool !== undefined &&
161
+ derivedBuildTool !== undefined &&
162
+ isTruncated(derivedBuildTool) &&
163
+ onDiskBuildTool !== derivedBuildTool;
164
+ if (!keepsOwnerBuildTool)
165
+ return { ...carried, ...derived };
166
+ return { ...carried, ...derived, buildTool: onDiskBuildTool };
167
+ }
@@ -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
@@ -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');