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
@@ -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');
@@ -46,9 +46,19 @@ export declare const AUTO_COMPACT_HOOK_MATCHER = "Bash|Task";
46
46
  * hook exited with `error: required option '--project <path>' not
47
47
  * specified` on EVERY matching tool call — a non-blocking failure, so
48
48
  * the hook looked installed while the zero-human-intervention
49
- * auto-compact contract never once fired. `.` is promoted to the git
50
- * root by `resolveCanonicalProjectRoot`, the same convention the
51
- * `post-compact-detect` hook already documents in its own option help.
49
+ * auto-compact contract never once fired.
50
+ *
51
+ * WHY `.` AND NOT `${CLAUDE_PROJECT_DIR}`. A shell variable was tried first
52
+ * (2026-11-16) and reverted: on this project's Windows hook the value is NOT
53
+ * expanded, so `--project` received the literal `${CLAUDE_PROJECT_DIR:-.}`
54
+ * and the run tried to `mkdir` a directory by that name. The variable is only
55
+ * safe in a hook whose `shell` guarantees POSIX expansion; this matcher is
56
+ * `Bash|Task` and may be served by PowerShell. `.` is expanded by no one, so
57
+ * it is portable — and it is made correct by the CLI instead:
58
+ * `peaks code auto-compact` canonicalises `--project` with
59
+ * `resolveCanonicalProjectRoot`, promoting `.` to the git root whatever
60
+ * directory the intercepted tool call ran in. That is what fixes the
61
+ * `AUTO_COMPACT_NO_SESSION` field failure; it does not depend on this string.
52
62
  *
53
63
  * `npx peaks` is deliberately omitted: the project-local install
54
64
  * puts `peaks` on PATH inside the consumer repo (postinstall step),
@@ -49,9 +49,19 @@ export const AUTO_COMPACT_HOOK_MATCHER = 'Bash|Task';
49
49
  * hook exited with `error: required option '--project <path>' not
50
50
  * specified` on EVERY matching tool call — a non-blocking failure, so
51
51
  * the hook looked installed while the zero-human-intervention
52
- * auto-compact contract never once fired. `.` is promoted to the git
53
- * root by `resolveCanonicalProjectRoot`, the same convention the
54
- * `post-compact-detect` hook already documents in its own option help.
52
+ * auto-compact contract never once fired.
53
+ *
54
+ * WHY `.` AND NOT `${CLAUDE_PROJECT_DIR}`. A shell variable was tried first
55
+ * (2026-11-16) and reverted: on this project's Windows hook the value is NOT
56
+ * expanded, so `--project` received the literal `${CLAUDE_PROJECT_DIR:-.}`
57
+ * and the run tried to `mkdir` a directory by that name. The variable is only
58
+ * safe in a hook whose `shell` guarantees POSIX expansion; this matcher is
59
+ * `Bash|Task` and may be served by PowerShell. `.` is expanded by no one, so
60
+ * it is portable — and it is made correct by the CLI instead:
61
+ * `peaks code auto-compact` canonicalises `--project` with
62
+ * `resolveCanonicalProjectRoot`, promoting `.` to the git root whatever
63
+ * directory the intercepted tool call ran in. That is what fixes the
64
+ * `AUTO_COMPACT_NO_SESSION` field failure; it does not depend on this string.
55
65
  *
56
66
  * `npx peaks` is deliberately omitted: the project-local install
57
67
  * puts `peaks` on PATH inside the consumer repo (postinstall step),
@@ -31,7 +31,7 @@
31
31
  * again — which is exactly the moment the user can say no. Multi-use
32
32
  * is a deliberate opt-in via `--multi`.
33
33
  */
34
- import { type WorktreeLease } from '../worktree/worktree-lease.js';
34
+ import { type WorktreeLease } from 'peaks-loop-workspace-runtime';
35
35
  import { type ContainerLease } from '../container/container-lease.js';
36
36
  export declare const WORKTREE_AUTH_FILE = "worktree-auth.json";
37
37
  /** The narrow surface the gate actually inspects. Keep this list in lock-step with the regex matchers below. */
@@ -34,7 +34,8 @@
34
34
  import { createHash } from 'node:crypto';
35
35
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
36
36
  import { dirname, join } from 'node:path';
37
- import { deserializeLease, isLeaseActive, leaseFilePath } from '../worktree/worktree-lease.js';
37
+ import { deserializeLease, isLeaseActive, leaseFilePath } from 'peaks-loop-workspace-runtime';
38
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
38
39
  import { readDispatchProvenance } from '../worktree/dispatch-provenance.js';
39
40
  import { containerLeaseFilePath, deserializeContainerLease, isContainerLeaseActive } from '../container/container-lease.js';
40
41
  import { consumedGrantsDenial, expiredGrantsDenial, noAuthorizationDenial, noGrantForOperationDenial, requestMismatchDenial } from './worktree-refusal-messages.js';
@@ -48,7 +49,7 @@ export function currentAuthFingerprint(input) {
48
49
  }
49
50
  /** The file the gate reads. Default location: `.peaks/_runtime/<sessionId>/worktree-auth.json`. */
50
51
  export function worktreeAuthFilePath(projectRoot, sessionId) {
51
- return join(projectRoot, '.peaks', '_runtime', sessionId, WORKTREE_AUTH_FILE);
52
+ return join(getSessionDir(projectRoot, sessionId), WORKTREE_AUTH_FILE);
52
53
  }
53
54
  /**
54
55
  * Read + validate the on-disk grant file. Returns `null` for "no file" (not an error — just no auth
@@ -327,12 +328,14 @@ export function evaluateWorktreeAuth(input) {
327
328
  */
328
329
  export function decideFromContainerLease(input) {
329
330
  const containerLeaseId = input.containerLeaseId ?? '';
330
- const file = containerLeaseFilePath(`${input.projectRoot}/.peaks/_runtime/${input.sessionId}`, containerLeaseId);
331
- if (!existsSync(file)) {
331
+ // Total: a bad id is "no lease" — this function's existing fail-closed branch.
332
+ const sessionDir = tryGetSessionDir(input.projectRoot, input.sessionId);
333
+ const file = sessionDir.ok ? containerLeaseFilePath(sessionDir.dir, containerLeaseId) : null;
334
+ if (file === null || !existsSync(file)) {
332
335
  return {
333
336
  allow: false,
334
337
  code: 'CONTAINER_LEASE_FILE_INVALID',
335
- reason: `No container lease at ${file} (leaseId=${containerLeaseId}).`,
338
+ reason: `No container lease at ${file ?? 'an unresolved session directory'} (leaseId=${containerLeaseId}).`,
336
339
  remediation: `Run \`peaks container spawn --rid <rid> --role <role> --purpose "<why>"\` to create the lease, then re-run. The PEAKS_CONTAINER_LEASE_ID env is the source of truth (dispatch injects it).`
337
340
  };
338
341
  }
@@ -375,15 +378,15 @@ export function decideFromContainerLease(input) {
375
378
  export function decideFromLease(input) {
376
379
  const leaseId = input.leaseId ?? '';
377
380
  // `leaseFilePath` expects the per-session runtime dir as its first
378
- // argument, NOT the project root. Compose the same path the spawn
379
- // CLI writes to (`<projectRoot>/.peaks/_runtime/<sid>`).
380
- const runtimeDir = `${input.projectRoot.replace(/[\\/]+$/, '')}/.peaks/_runtime/${input.sessionId}`;
381
- const file = leaseFilePath(runtimeDir, leaseId);
382
- if (!existsSync(file)) {
381
+ // argument, NOT the project root. Total: a bad id resolves to "no lease",
382
+ // the same fail-closed branch as a missing file.
383
+ const sessionDir = tryGetSessionDir(input.projectRoot, input.sessionId);
384
+ const file = sessionDir.ok ? leaseFilePath(sessionDir.dir, leaseId) : null;
385
+ if (file === null || !existsSync(file)) {
383
386
  return {
384
387
  allow: false,
385
388
  code: 'WORKTREE_USER_AUTH_REQUIRED',
386
- reason: `No worktree auth grant AND no lease at ${file} (leaseId=${leaseId}).`,
389
+ reason: `No worktree auth grant AND no lease at ${file ?? 'an unresolved session directory'} (leaseId=${leaseId}).`,
387
390
  remediation: `Either run \`peaks worktree auth grant --operation <op> --reason "<why>"\` or ` +
388
391
  `run \`peaks worktree spawn --rid <rid> --role <role> --purpose "<why>"\` to create the lease.`
389
392
  };
@@ -8,15 +8,14 @@
8
8
  * `verdict-aggregator` envelope union (`karpathy` / `security` / `perf`).
9
9
  *
10
10
  * Karpathy §2 Simplicity First: no new dependencies, no LLM scheduling,
11
- * one binary per evaluator. Each evaluator returns the same envelope
12
- * shape the existing reviewer fan-out produces; verdict-aggregator
13
- * accepts them via `envelopesToAggregatorInput` unchanged (BC).
14
- *
15
- * File budget: ≤ 800 lines.
11
+ * one binary per evaluator. Each returns the same envelope shape the
12
+ * reviewer fan-out produces; verdict-aggregator accepts them via
13
+ * `envelopesToAggregatorInput` unchanged (BC). File budget: ≤ 800 lines.
16
14
  */
17
15
  import { execFileSync } from 'node:child_process';
18
16
  import { existsSync, readFileSync } from 'node:fs';
19
17
  import { join } from 'node:path';
18
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
20
19
  import { runMonotonicCheck } from './monotonic-runner.js';
21
20
  /** Dispatch a single evaluator against the given rid and project. */
22
21
  export function dispatchEvaluator(kind, options) {
@@ -581,8 +580,9 @@ function extractSection(body, heading) {
581
580
  * and project it to an `EvaluatorVerdictEnvelope`. Used by workflow yaml
582
581
  * evaluators that point at on-disk artifacts. */
583
582
  export function loadEnvelopeFromDisk(projectRoot, sid, rel, kind) {
584
- const path = join(projectRoot, '.peaks', '_runtime', sid, rel);
585
- if (!existsSync(path))
583
+ const dir = tryGetSessionDir(projectRoot, sid);
584
+ const path = dir.ok ? join(dir.dir, rel) : '';
585
+ if (!path || !existsSync(path))
586
586
  return null;
587
587
  const md = readFileSync(path, 'utf8');
588
588
  return parseAuditMarkdownEnvelope(md, kind);
@@ -26,6 +26,7 @@ import { join } from 'node:path';
26
26
  import { dispatchEvaluator } from './evaluator-dispatcher.js';
27
27
  import { checkMonotonicImprovement, toScoreRow, DEFAULT_MONOTONIC_THRESHOLD } from './monotonic-guard.js';
28
28
  import { appendMetricLine, readMetricLines } from '../observability/jsonl-store.js';
29
+ import { getSessionDir } from '../session/getSessionDir.js';
29
30
  import { emitMonotonicReport } from './loop-observability.js';
30
31
  import { findProjectRoot } from '../config/config-safety.js';
31
32
  import { classifyFsError, MONOTONIC_CYCLE_KIND, WALKED_EVALUATORS } from './monotonic-runner-types.js';
@@ -33,7 +34,7 @@ import { classifyFsError, MONOTONIC_CYCLE_KIND, WALKED_EVALUATORS } from './mono
33
34
  * derive `cyclesDir`). The monotonic-runner writer no longer writes
34
35
  * here; the jsonl-store is the new persistence layer. */
35
36
  export function sliceDir(projectRoot, sid, rid) {
36
- return join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid);
37
+ return join(getSessionDir(projectRoot, sid), 'loop', rid);
37
38
  }
38
39
  /** Load the most recent prior cycle for `(sid, rid)` from the
39
40
  * per-session jsonl store (tail scan, O(N) where N = total jsonl
@@ -4,8 +4,7 @@
4
4
  * Spec-as-first-class CLI backing service. Reads / writes / lints
5
5
  * `.peaks/_runtime/<sid>/loop/<rid>/spec.yaml` — the project-level
6
6
  * (third-tier) spec origin per Slice A resolver (project → global →
7
- * bundled). Authors may also pass an explicit file path to `peaks loop
8
- * spec lint`.
7
+ * bundled). Authors may also pass an explicit path to `peaks loop spec lint`.
9
8
  *
10
9
  * Spec schema (v1):
11
10
  * - evaluators[].kind (native EvaluatorKind)
@@ -14,18 +13,17 @@
14
13
  * - sla[].evaluator (must match an evaluator.kind above)
15
14
  * - sla[].maxScore (0..1; the floor above which the evaluator is
16
15
  * considered to have held its SLA)
17
- * - termination.strategy ("max-cycles" | "monotonic-violation" |
18
- * "manual")
16
+ * - termination.strategy ("max-cycles" | "monotonic-violation" | "manual")
19
17
  * - termination.maxCycles? (positive integer when strategy = max-cycles)
20
18
  *
21
- * Karpathy §2 Simplicity First: pure data + a single hand-rolled
22
- * YAML parser inline; no new deps.
19
+ * Karpathy §2 Simplicity First: pure data + a single hand-rolled YAML parser.
23
20
  *
24
21
  * File budget: ≤ 800 lines.
25
22
  */
26
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
27
24
  import { dirname, join, isAbsolute } from 'node:path';
28
25
  import { isArray } from '../../shared/array-guards.js';
26
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
29
27
  /** Default termination strategy — wired by `peaks loop run` so a
30
28
  * spec.yaml produced by `loop spec bootstrap` actually drives the
31
29
  * loop driver. Previously the string was declared-and-validated but
@@ -39,7 +37,10 @@ export const DEFAULT_MAX_CYCLES = 5;
39
37
  * `{kind:'missing'}` when no file exists. The CLI layer then chooses
40
38
  * to bootstrap a fresh spec or fail. */
41
39
  export function resolveLoopSpec(projectRoot, sid, rid) {
42
- const path = join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'spec.yaml');
40
+ const resolved = tryGetSessionDir(projectRoot, sid);
41
+ if (!resolved.ok)
42
+ return { origin: { kind: 'missing' }, spec: null };
43
+ const path = join(resolved.dir, 'loop', rid, 'spec.yaml');
43
44
  if (!existsSync(path))
44
45
  return { origin: { kind: 'missing' }, spec: null };
45
46
  const raw = readFileSync(path, 'utf8');
@@ -201,7 +202,7 @@ export function serializeSpec(spec) {
201
202
  /** Persist a LoopSpec to disk at the project-level path; ensures the
202
203
  * parent directory exists. Returns the resolved path. */
203
204
  export function persistSpec(projectRoot, sid, spec) {
204
- const path = join(projectRoot, '.peaks', '_runtime', sid, 'loop', spec.rid, 'spec.yaml');
205
+ const path = join(getSessionDir(projectRoot, sid), 'loop', spec.rid, 'spec.yaml');
205
206
  mkdirSync(dirname(path), { recursive: true });
206
207
  writeFileSync(path, serializeSpec(spec), 'utf8');
207
208
  return path;
@@ -562,7 +563,7 @@ function parseScalarNumber(raw) {
562
563
  return null;
563
564
  }
564
565
  export function specPath(projectRoot, sid, rid) {
565
- return join(projectRoot, '.peaks', '_runtime', sid, 'loop', rid, 'spec.yaml');
566
+ return join(getSessionDir(projectRoot, sid), 'loop', rid, 'spec.yaml');
566
567
  }
567
568
  /** Force a path to be inside the project root — guards against the
568
569
  * `peaks loop spec lint <file>` flag accepting arbitrary paths. The
@@ -0,0 +1,3 @@
1
+ import type { McpToolDefinition } from './surface.js';
2
+ import { type ToolCallContext, type ToolCallResult } from './tool-core.js';
3
+ export declare function callContextCompressTool(tool: McpToolDefinition, args: Readonly<Record<string, unknown>>, context: ToolCallContext): Promise<ToolCallResult>;
@@ -0,0 +1,135 @@
1
+ // src/services/mcp/context-tool.ts
2
+ //
3
+ // `peaks_context_compress`: build the resume summary an LLM can carry forward
4
+ // after folding older turns out of its working set.
5
+ //
6
+ // WHAT THIS IS, AND WHAT IT IS NOT — the distinction is the whole point.
7
+ //
8
+ // This is NOT a compaction. Nothing here rewrites a request, shrinks a context
9
+ // window, or reduces token billing; a Model Context Protocol tool returns a
10
+ // VALUE, and the value it returns is text. billion-context achieves real
11
+ // compression by sitting in the network path and rewriting the outgoing body,
12
+ // which peaks-loop is not positioned to do (see `writeMainSessionCompactIntent`'s
13
+ // own header: hooks can observe or veto, never initiate).
14
+ //
15
+ // What it DOES is give the model a bounded, factual statement of where the work
16
+ // stands, so that after it decides to drop older turns it is working from
17
+ // recorded facts instead of from recollection. The saving is in what the model
18
+ // no longer needs to re-read, not in what the API is billed.
19
+ //
20
+ // READ-ONLY, BY COMPOSITION. Every argv it runs is already in the whitelist for
21
+ // `peaks_status`; this tool adds no CLI command and no argv. Section §3.2 of the
22
+ // design permits a composite to arrange and reshape, and forbids it to CONCLUDE.
23
+ // So the reply carries the envelopes' own words — presence, gate, ratio, the
24
+ // request's state — and never a judgement about whether the work is going well.
25
+ import { buildArgv } from '../readonly-surface/argv-guard.js';
26
+ import { rejectedResult, runArgv, valuesForEntry } from './tool-core.js';
27
+ /** Bound on how much of each source the summary quotes. */
28
+ const MAX_TEXT = 400;
29
+ /** The `data` object of a CLI envelope, or `null` when the shape is not one. */
30
+ function envelopeData(outcome) {
31
+ const envelope = outcome.envelope;
32
+ if (typeof envelope !== 'object' || envelope === null)
33
+ return null;
34
+ const data = envelope['data'];
35
+ return typeof data === 'object' && data !== null ? data : null;
36
+ }
37
+ /** A field from `data`, stringified and bounded; `null` when absent. */
38
+ function field(data, key) {
39
+ if (data === null)
40
+ return null;
41
+ const value = data[key];
42
+ if (typeof value === 'string')
43
+ return value.slice(0, MAX_TEXT);
44
+ if (typeof value === 'number' || typeof value === 'boolean')
45
+ return String(value);
46
+ return null;
47
+ }
48
+ /** A field nested one level under `data[parent]` — where `skill presence` keeps
49
+ * its `context` block (`{ ratioPct, action, mode }`). */
50
+ function nestedField(data, parent, key) {
51
+ if (data === null)
52
+ return null;
53
+ const container = data[parent];
54
+ if (typeof container !== 'object' || container === null)
55
+ return null;
56
+ return field(container, key);
57
+ }
58
+ /** The `skill presence` facts, from `data` and its nested `context` block. */
59
+ function presenceLines(data) {
60
+ const lines = [];
61
+ const skill = field(data, 'skill');
62
+ const gate = field(data, 'gate');
63
+ // `skill presence` nests these under `data.context`; reading them off the top
64
+ // level silently produced nothing, which is why the first live run of this
65
+ // tool omitted the ratio entirely.
66
+ const ratio = nestedField(data, 'context', 'ratioPct');
67
+ const action = nestedField(data, 'context', 'action');
68
+ if (skill !== null)
69
+ lines.push(`- active skill: ${skill}`);
70
+ if (gate !== null)
71
+ lines.push(`- gate: ${gate}`);
72
+ if (ratio !== null)
73
+ lines.push(`- context used: ${ratio}`);
74
+ if (action !== null && action !== 'none')
75
+ lines.push(`- context action: ${action}`);
76
+ return lines;
77
+ }
78
+ /** The `request show` facts. */
79
+ function requestLines(data) {
80
+ const lines = [];
81
+ const requestId = field(data, 'requestId');
82
+ const state = field(data, 'state');
83
+ const path = field(data, 'path');
84
+ if (requestId !== null)
85
+ lines.push(`- request: ${requestId}`);
86
+ if (state !== null)
87
+ lines.push(`- request state: ${state}`);
88
+ if (path !== null)
89
+ lines.push(`- request artifact: ${path}`);
90
+ return lines;
91
+ }
92
+ /** The summary lines one ran entry contributes. Never concludes — see the header. */
93
+ function linesForEntry(entryId, data) {
94
+ if (entryId === 'ctx-skill-presence')
95
+ return presenceLines(data);
96
+ if (entryId === 'ctx-request-show')
97
+ return requestLines(data);
98
+ return [];
99
+ }
100
+ export async function callContextCompressTool(tool, args, context) {
101
+ const lines = [];
102
+ let ran = 0;
103
+ for (const entry of tool.entries) {
104
+ const values = valuesForEntry(entry, args, context);
105
+ if (values === undefined)
106
+ continue;
107
+ const built = buildArgv(entry, values);
108
+ if (!built.ok) {
109
+ return rejectedResult(entry, `Parameter ${built.param} was refused: ${built.message}`);
110
+ }
111
+ const outcome = await runArgv(entry.id, built.argv, context);
112
+ if (outcome.failure !== undefined) {
113
+ // A source that failed is REPORTED, never silently dropped: a summary
114
+ // missing its request state reads as "there is no request".
115
+ lines.push(`- ${entry.id}: unavailable (${outcome.failure.slice(0, MAX_TEXT)})`);
116
+ continue;
117
+ }
118
+ ran += 1;
119
+ lines.push(...linesForEntry(entry.id, envelopeData(outcome)));
120
+ }
121
+ if (ran === 0 && lines.length === 0) {
122
+ const entry = tool.entries[0];
123
+ return entry === undefined
124
+ ? { content: [{ type: 'text', text: '{"reason":"no entry"}' }], isError: true }
125
+ : rejectedResult(entry, 'No source was runnable; supply a rid and role to include the request.');
126
+ }
127
+ const body = [
128
+ 'Peaks-Loop resume summary (facts only; no judgement).',
129
+ ...lines,
130
+ '',
131
+ 'Use this in place of re-reading the turns it describes. Anything it does not',
132
+ 'state is NOT recorded here — read the artifact paths above rather than assume.'
133
+ ].join('\n');
134
+ return { content: [{ type: 'text', text: body }] };
135
+ }
@@ -36,7 +36,13 @@ const TOOL_DESCRIPTIONS = {
36
36
  '(a `.peaks/` directory) as the working directory.',
37
37
  peaks_memory_search: 'Search this project’s durable memory for a term, and get back NAMES and short excerpts — ' +
38
38
  'never note bodies. Read-only. Use it to answer "has this project settled anything about X?" ' +
39
- 'Requires a Peaks-Loop project (a `.peaks/` directory) as the working directory.'
39
+ 'Requires a Peaks-Loop project (a `.peaks/` directory) as the working directory.',
40
+ peaks_context_compress: 'Build a short, factual resume summary of where this Peaks-Loop workflow stands — active ' +
41
+ 'skill, gate, context ratio and (given a rid and role) the request state. Read-only. ' +
42
+ 'Use it BEFORE folding older turns out of your working set, so what you keep is recorded ' +
43
+ 'fact rather than recollection. It does NOT compact anything: it changes no request, ' +
44
+ 'reduces no token count, and replaces no `/compact`. Anything it omits is not recorded — ' +
45
+ 'follow the artifact paths it returns. Requires a Peaks-Loop project as the working directory.'
40
46
  };
41
47
  /** Per-parameter prose, by placeholder name. Absent names simply carry no description. */
42
48
  const PARAM_DESCRIPTIONS = {
@@ -12,6 +12,7 @@
12
12
  // returned.
13
13
  import { buildArgv } from '../readonly-surface/argv-guard.js';
14
14
  import { callMemorySearchTool } from './memory-tool.js';
15
+ import { callContextCompressTool } from './context-tool.js';
15
16
  import { rejectedResult, resultOf, runArgv, valuesForEntry } from './tool-core.js';
16
17
  /**
17
18
  * `peaks_status`: run every argv the caller supplied enough for, and return each
@@ -46,7 +47,8 @@ export async function callStatusTool(tool, args, context) {
46
47
  */
47
48
  const TOOL_HANDLERS = {
48
49
  peaks_status: callStatusTool,
49
- peaks_memory_search: callMemorySearchTool
50
+ peaks_memory_search: callMemorySearchTool,
51
+ peaks_context_compress: callContextCompressTool
50
52
  };
51
53
  /** Tools the surface declares that no handler can serve. Non-empty = refuse to start. */
52
54
  export function missingHandlers(tools) {
@@ -15,6 +15,15 @@ export type ProjectContextEnvelope = {
15
15
  sessionCount: number;
16
16
  projectScan: BootstrapProjectScanEnvelope;
17
17
  };
18
- export declare function generateProjectContext(projectRoot: string): Promise<ProjectContextEnvelope>;
18
+ export type GenerateProjectContextOptions = {
19
+ /**
20
+ * Refresh the machine-derivable frontmatter fields of an existing
21
+ * `project-scan.md` (default `true` — `peaks project context` is itself the
22
+ * refresh command). `false` reproduces the pre-refresh behaviour, where an
23
+ * existing file is skipped untouched.
24
+ */
25
+ readonly refreshProjectScan?: boolean;
26
+ };
27
+ export declare function generateProjectContext(projectRoot: string, options?: GenerateProjectContextOptions): Promise<ProjectContextEnvelope>;
19
28
  export declare function readProjectContext(projectRoot: string): string | null;
20
29
  export declare function getProjectContextPath(projectRoot: string): string;