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
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { deserializeLease, finalizeLease, isLeaseActive, isLeaseGcEligible, leaseFilePath, leaseStoreDir, listLeasesSync, markReleased, recordConsumption, renewLease, serializeLease, ttlForRole } from '../../worktree/worktree-lease.js';
4
+ import { deserializeLease, finalizeLease, isLeaseActive, isLeaseGcEligible, leaseFilePath, leaseStoreDir, listLeasesSync, markReleased, recordConsumption, renewLease, serializeLease, ttlForRole } from 'peaks-loop-workspace-runtime';
5
5
  import { combineProbes, fail, missingSourceFiles, pass, probe, requireBaselineRow } from './_shared.js';
6
6
  const NOW = 1_700_000_000_000;
7
7
  const DRAFT = {
@@ -68,7 +68,7 @@ export async function runJ12Contract(ctx) {
68
68
  probe(isLeaseGcEligible(finalizeLease({ ...DRAFT, expiresAt: NOW - 1 }), NOW), 'an expired lease is gc-eligible'),
69
69
  probe(ttlForRole('rd') > 0 && ttlForRole('no-such-role') === ttlForRole('rd'), 'unknown roles fall back to the rd TTL')
70
70
  ]);
71
- const artifact = row.sourceFiles[0] ?? 'src/services/worktree/worktree-lease.ts';
71
+ const artifact = row.sourceFiles[0] ?? 'packages/peaks-loop-workspace-runtime/src/lease/store.ts';
72
72
  if (result.ok)
73
73
  return pass(ctx, artifact);
74
74
  return fail(ctx, artifact, 'the lease lifecycle is complete: release is idempotent and gc never touches an in-flight lease', result.detail, 'J12 invariant broken: the lease release lifecycle or its gc guard no longer holds');
@@ -5,9 +5,11 @@
5
5
  * orchestrator re-exports every name declared here, so existing importers keep
6
6
  * using `./auto-compact-orchestrator.js` unchanged.
7
7
  */
8
+ import { spawnSync } from 'node:child_process';
8
9
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
10
  import { join } from 'node:path';
10
11
  import { getSessionDir } from '../session/getSessionDir.js';
12
+ import { buildCheckpointContent } from './auto-compact-checkpoint-content.js';
11
13
  import { describeHarnessWindowSync } from '../context/harness-window-config.js';
12
14
  /**
13
15
  * What the caller is told to do next. The harness-window notice rides along because
@@ -111,25 +113,55 @@ export function writePreCompactCheckpoint(input) {
111
113
  const prefix = input.redLine === true ? 'red-line-' : 'pre-compact-';
112
114
  const filename = `${prefix}${input.now.toISOString().replace(/[:.]/g, '-')}.json`;
113
115
  const path = join(dir, filename);
116
+ // D7 reads `mode`, `currentPlan`, `openQuestions`, `recentDecisions` out of
117
+ // this JSON. Until 2026-11-16 every one of those was seeded EMPTY, so the
118
+ // resume the detector enabled had nothing to restore — measured: a checkpoint
119
+ // written from a session with an active request and a populated decisions log
120
+ // still carried seven empty fields. `buildCheckpointContent` reads what the
121
+ // session already wrote to disk and renders it into the shape D7 expects.
122
+ const populated = buildCheckpointContent({
123
+ projectRoot: input.projectRoot,
124
+ sessionId: input.sessionId,
125
+ ...(input.redLine === true ? { redLine: true } : {})
126
+ });
114
127
  const content = {
115
128
  schemaVersion: 1,
116
129
  reason: input.redLine === true ? 'pre-compact-red-line' : PRE_COMPACT_REASON,
117
130
  sessionId: input.sessionId,
118
131
  createdAt: input.now.toISOString(),
119
- // D7 reads `mode`, `currentPlan`, `openQuestions`, `recentDecisions`
120
- // out of this JSON. We seed empty arrays; the post-compact LLM
121
- // rehydrates from the auto-decisions log + open question list.
122
132
  mode: 'full-auto',
123
- currentPlan: input.redLine === true
124
- ? 'RED-LINE compact REQUESTED from the harness (not executed by peaks-loop); work continues'
125
- : 'auto-compact in progress; resume from auto-decisions.md',
126
- openQuestions: [],
127
- recentDecisions: [],
128
- recentArtifactPaths: [],
129
- gitStatus: '',
133
+ currentPlan: populated.currentPlan,
134
+ openQuestions: populated.openQuestions,
135
+ recentDecisions: populated.recentDecisions,
136
+ recentArtifactPaths: populated.recentArtifactPaths,
137
+ gitStatus: readGitStatusQuietly(input.projectRoot),
130
138
  skillsActive: ['peaks-code'],
131
139
  todoState: []
132
140
  };
133
141
  writeFileSync(path, JSON.stringify(content, null, 2), 'utf8');
134
142
  return path;
135
143
  }
144
+ /** Cap on the working-tree lines a checkpoint carries; the rest stay in git. */
145
+ const MAX_GIT_STATUS_LINES = 20;
146
+ /**
147
+ * `git status --porcelain -b` for the checkpoint, or `''`.
148
+ *
149
+ * A checkpoint is written on the compact path, where a few hundred milliseconds
150
+ * spent on git is acceptable and a resume that knows the working tree was dirty
151
+ * is materially better than one that does not. Failure is not an error: a repo
152
+ * without git, or a locked index, simply leaves the field empty.
153
+ */
154
+ function readGitStatusQuietly(projectRoot) {
155
+ const result = spawnSync('git', ['status', '--porcelain', '-b'], {
156
+ cwd: projectRoot,
157
+ encoding: 'utf8',
158
+ timeout: 5_000,
159
+ // Windows: without this the console window flashes on every probe. The
160
+ // repo's spawn-hygiene ratchet requires it on EVERY call site.
161
+ windowsHide: true
162
+ });
163
+ if (result.error !== undefined || result.status !== 0 || typeof result.stdout !== 'string') {
164
+ return '';
165
+ }
166
+ return result.stdout.trim().split('\n').slice(0, MAX_GIT_STATUS_LINES).join('\n');
167
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Building a pre-compact checkpoint that carries enough to resume from.
3
+ *
4
+ * WHY THIS EXISTS. `writePreCompactCheckpoint` used to seed every field empty —
5
+ * `currentPlan` said only "resume from auto-decisions.md", and
6
+ * `openQuestions` / `recentDecisions` / `recentArtifactPaths` were `[]`. The
7
+ * post-compact detector reads exactly those fields, so the resume it enabled had
8
+ * nothing to restore. Measured 2026-11-16: a checkpoint written from a session
9
+ * with an active request and a populated decisions log still contained seven
10
+ * empty fields.
11
+ *
12
+ * The data was never missing — it was on disk and unread. This module reads it
13
+ * and renders it into the shape `post-compact-checkpoint.ts` expects.
14
+ *
15
+ * WHAT THIS DELIBERATELY DOES NOT DO. It does not compress, summarize with a
16
+ * model, or truncate conversation history. peaks-loop cannot read the request
17
+ * body and cannot initiate a compact (see the note on
18
+ * `writeMainSessionCompactIntent`); what it CAN do is leave a complete, truthful
19
+ * record of where the work stands, so the post-compact turn resumes instead of
20
+ * re-deriving.
21
+ */
22
+ /** One `## Auto-compact decision — <ts>` block from `txt/auto-decisions.md`. */
23
+ export type AutoDecisionEntry = {
24
+ readonly decidedAt: string;
25
+ readonly ratio: string | null;
26
+ readonly resumeHint: string | null;
27
+ readonly nextActions: readonly string[];
28
+ };
29
+ /** Read `txt/auto-decisions.md` and return its blocks, newest last. */
30
+ export declare function readAutoDecisions(projectRoot: string, sessionId: string): AutoDecisionEntry[];
31
+ /**
32
+ * The populated fields for a checkpoint.
33
+ *
34
+ * `currentPlan` is built from what the session actually recorded — the newest
35
+ * auto-compact decision's resume hint plus its next actions — and falls back to
36
+ * a sentence that still says something true (no decisions yet) rather than the
37
+ * old "resume from auto-decisions.md", which told a resumed turn to go read a
38
+ * file that this checkpoint is supposed to have already summarized.
39
+ */
40
+ export declare function buildCheckpointContent(input: {
41
+ readonly projectRoot: string;
42
+ readonly sessionId: string;
43
+ readonly redLine?: boolean;
44
+ }): {
45
+ readonly currentPlan: string;
46
+ readonly openQuestions: string[];
47
+ readonly recentDecisions: string[];
48
+ readonly recentArtifactPaths: string[];
49
+ };
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Building a pre-compact checkpoint that carries enough to resume from.
3
+ *
4
+ * WHY THIS EXISTS. `writePreCompactCheckpoint` used to seed every field empty —
5
+ * `currentPlan` said only "resume from auto-decisions.md", and
6
+ * `openQuestions` / `recentDecisions` / `recentArtifactPaths` were `[]`. The
7
+ * post-compact detector reads exactly those fields, so the resume it enabled had
8
+ * nothing to restore. Measured 2026-11-16: a checkpoint written from a session
9
+ * with an active request and a populated decisions log still contained seven
10
+ * empty fields.
11
+ *
12
+ * The data was never missing — it was on disk and unread. This module reads it
13
+ * and renders it into the shape `post-compact-checkpoint.ts` expects.
14
+ *
15
+ * WHAT THIS DELIBERATELY DOES NOT DO. It does not compress, summarize with a
16
+ * model, or truncate conversation history. peaks-loop cannot read the request
17
+ * body and cannot initiate a compact (see the note on
18
+ * `writeMainSessionCompactIntent`); what it CAN do is leave a complete, truthful
19
+ * record of where the work stands, so the post-compact turn resumes instead of
20
+ * re-deriving.
21
+ */
22
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
23
+ import { join, relative, sep } from 'node:path';
24
+ import { getSessionDir } from '../session/getSessionDir.js';
25
+ /** How many decisions/artifacts a checkpoint carries. Bounded on purpose: a
26
+ * resume hint longer than this stops being scannable, and the full log stays
27
+ * on disk for anything older. */
28
+ const MAX_RECENT_DECISIONS = 5;
29
+ const MAX_RECENT_ARTIFACTS = 8;
30
+ const MAX_OPEN_QUESTIONS = 6;
31
+ /** Read `txt/auto-decisions.md` and return its blocks, newest last. */
32
+ export function readAutoDecisions(projectRoot, sessionId) {
33
+ const path = join(getSessionDir(projectRoot, sessionId), 'txt', 'auto-decisions.md');
34
+ if (!existsSync(path))
35
+ return [];
36
+ let raw;
37
+ try {
38
+ raw = readFileSync(path, 'utf8');
39
+ }
40
+ catch {
41
+ return [];
42
+ }
43
+ const entries = [];
44
+ // A block starts at its heading and runs to the next heading or EOF. Parsing
45
+ // line-by-line rather than with a regex keeps a `- key: value` whose value
46
+ // itself contains ` | ` or a colon from being mangled.
47
+ let current = null;
48
+ const flush = () => {
49
+ if (current === null)
50
+ return;
51
+ const nextActionsRaw = current.fields.get('next-actions') ?? '';
52
+ entries.push({
53
+ decidedAt: current.decidedAt,
54
+ ratio: current.fields.get('ratio') ?? null,
55
+ resumeHint: current.fields.get('resume-hint') ?? null,
56
+ nextActions: nextActionsRaw === '' ? [] : nextActionsRaw.split(' | ').filter((s) => s !== '')
57
+ });
58
+ current = null;
59
+ };
60
+ for (const line of raw.split('\n')) {
61
+ const heading = /^## Auto-compact decision — (.+)$/.exec(line.trim());
62
+ if (heading !== null) {
63
+ flush();
64
+ current = { decidedAt: (heading[1] ?? '').trim(), fields: new Map() };
65
+ continue;
66
+ }
67
+ if (current === null)
68
+ continue;
69
+ const field = /^-\s+([a-z-]+):\s*(.*)$/.exec(line.trim());
70
+ if (field !== null && field[1] !== undefined)
71
+ current.fields.set(field[1], (field[2] ?? '').trim());
72
+ }
73
+ flush();
74
+ return entries;
75
+ }
76
+ /** Files a resume would want to open first: the session's request artifacts. */
77
+ function recentArtifactPaths(projectRoot, sessionId) {
78
+ const sessionDir = getSessionDir(projectRoot, sessionId);
79
+ const found = [];
80
+ for (const role of ['rd', 'prd', 'qa', 'sc']) {
81
+ const requestsDir = join(sessionDir, role, 'requests');
82
+ if (!existsSync(requestsDir))
83
+ continue;
84
+ let names;
85
+ try {
86
+ names = readdirSync(requestsDir);
87
+ }
88
+ catch {
89
+ continue;
90
+ }
91
+ for (const name of names) {
92
+ if (name.endsWith('.md')) {
93
+ // DERIVED FROM `sessionDir`, never re-composed. A second hand-rolled
94
+ // `.peaks/_runtime/<sid>` join is the bug class the canonical-path scan
95
+ // exists for: it re-implements the layout instead of going through the
96
+ // one function that validates the id, so a future layout change would
97
+ // silently diverge. `sessionDir` is already the canonical root.
98
+ found.push(relative(projectRoot, join(requestsDir, name)).split(sep).join('/'));
99
+ }
100
+ }
101
+ }
102
+ return found.slice(0, MAX_RECENT_ARTIFACTS);
103
+ }
104
+ /**
105
+ * The populated fields for a checkpoint.
106
+ *
107
+ * `currentPlan` is built from what the session actually recorded — the newest
108
+ * auto-compact decision's resume hint plus its next actions — and falls back to
109
+ * a sentence that still says something true (no decisions yet) rather than the
110
+ * old "resume from auto-decisions.md", which told a resumed turn to go read a
111
+ * file that this checkpoint is supposed to have already summarized.
112
+ */
113
+ export function buildCheckpointContent(input) {
114
+ const decisions = readAutoDecisions(input.projectRoot, input.sessionId);
115
+ const newest = decisions.at(-1);
116
+ const planParts = [];
117
+ if (newest !== undefined) {
118
+ if (newest.resumeHint !== null && newest.resumeHint !== '') {
119
+ planParts.push(newest.resumeHint);
120
+ }
121
+ if (newest.nextActions.length > 0) {
122
+ planParts.push(`Next: ${newest.nextActions.join('; ')}`);
123
+ }
124
+ }
125
+ else {
126
+ planParts.push('No auto-compact decision recorded yet this session; resume from the newest request artifact below.');
127
+ }
128
+ if (input.redLine === true) {
129
+ planParts.push('RED-LINE compact requested from the harness (not executed by peaks-loop).');
130
+ }
131
+ const recentDecisions = decisions
132
+ .slice(-MAX_RECENT_DECISIONS)
133
+ .reverse()
134
+ .map((entry) => {
135
+ const ratio = entry.ratio === null ? '' : ` @ ${entry.ratio}`;
136
+ const hint = entry.resumeHint === null ? '' : ` — ${entry.resumeHint}`;
137
+ return `${entry.decidedAt}${ratio}${hint}`;
138
+ });
139
+ return {
140
+ currentPlan: planParts.join(' '),
141
+ openQuestions: pendingQuestions(decisions),
142
+ recentDecisions,
143
+ recentArtifactPaths: recentArtifactPaths(input.projectRoot, input.sessionId)
144
+ };
145
+ }
146
+ /**
147
+ * Questions still open. The only durable record the session keeps is the
148
+ * `next-actions` list of the newest decision, so an outstanding action IS an
149
+ * open question from the resumed turn's point of view: it does not yet know
150
+ * whether that action succeeded. Bounded so the resume stays short.
151
+ */
152
+ function pendingQuestions(decisions) {
153
+ const newest = decisions.at(-1);
154
+ if (newest === undefined)
155
+ return [];
156
+ return newest.nextActions.slice(0, MAX_OPEN_QUESTIONS);
157
+ }
@@ -8,8 +8,17 @@
8
8
  import { type AutoCompactResult, type CompactDispatchResult, type ConvergencePlan } from '../context/auto-compact-types.js';
9
9
  import type { CompactTarget } from '../context/auto-compact-dispatcher.js';
10
10
  import type { CompactRun } from './auto-compact-run-types.js';
11
- /** No session is bound, so there is nothing to probe. */
12
- export declare function noSessionResult(): AutoCompactResult;
11
+ /**
12
+ * No session is bound, so there is nothing to probe.
13
+ *
14
+ * The message names the LIKELY CAUSE, not just the remedy. This envelope is
15
+ * returned from a PreToolUse hook, where the exit status is ignored, so the
16
+ * text is the only thing a reader ever sees — and the field failure was a
17
+ * wrong `--project` (a `.` resolved against a subdirectory), not a workspace
18
+ * that was never initialised. Telling the user to run `workspace init` in that
19
+ * case sends them to re-initialise a workspace that already exists.
20
+ */
21
+ export declare function noSessionResult(projectRoot?: string): AutoCompactResult;
13
22
  /** The envelope for a probe that did not cross the auto-fire threshold. */
14
23
  export declare function skipResult(ctx: CompactRun): AutoCompactResult;
15
24
  /**
@@ -9,13 +9,27 @@ import { DEPRECATED_ENVELOPE_FIELDS } from '../context/auto-compact-types.js';
9
9
  import { describeHarnessWindowSync, harnessWindowSyncWarning } from '../context/harness-window-config.js';
10
10
  import { describeMode, thresholdFor } from './auto-compact-modes.js';
11
11
  import { summarizeLifecycleError } from './auto-compact-lifecycle.js';
12
- /** No session is bound, so there is nothing to probe. */
13
- export function noSessionResult() {
12
+ /**
13
+ * No session is bound, so there is nothing to probe.
14
+ *
15
+ * The message names the LIKELY CAUSE, not just the remedy. This envelope is
16
+ * returned from a PreToolUse hook, where the exit status is ignored, so the
17
+ * text is the only thing a reader ever sees — and the field failure was a
18
+ * wrong `--project` (a `.` resolved against a subdirectory), not a workspace
19
+ * that was never initialised. Telling the user to run `workspace init` in that
20
+ * case sends them to re-initialise a workspace that already exists.
21
+ */
22
+ export function noSessionResult(projectRoot) {
14
23
  return {
15
24
  ok: false,
16
25
  code: 'AUTO_COMPACT_NO_SESSION',
17
- message: 'No active session; cannot run auto-compact. Run `peaks workspace init` first.',
18
- nextActions: ['Run `peaks workspace init --change-id <id>` to bind a session']
26
+ message: `No active session under '${projectRoot ?? '(unknown)'}'; cannot run auto-compact. ` +
27
+ 'A workspace that IS initialised usually means --project resolved to the wrong directory ' +
28
+ '(it defaults to the current working directory).',
29
+ nextActions: [
30
+ `Confirm the workspace exists: ls ${projectRoot ?? '.'}/.peaks/_runtime/session.json`,
31
+ 'If it does not, run `peaks workspace init` there to bind a session'
32
+ ]
19
33
  };
20
34
  }
21
35
  /** The envelope for a probe that did not cross the auto-fire threshold. */
@@ -113,7 +113,7 @@ function settleBelowThreshold(ctx) {
113
113
  export async function runAutoCompact(input) {
114
114
  const sessionId = input.sessionId ?? getSessionIdCanonical(input.projectRoot);
115
115
  if (sessionId === null)
116
- return noSessionResult();
116
+ return noSessionResult(input.projectRoot);
117
117
  const mode = input.mode ?? resolveAutoCompactProfile(input.projectRoot);
118
118
  const ctx = await openRun(input, sessionId, mode);
119
119
  if (!ctx.decision.shouldCompact) {
@@ -29,6 +29,7 @@
29
29
  import { existsSync, readFileSync } from 'node:fs';
30
30
  import { join } from 'node:path';
31
31
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
32
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
32
33
  import { readJobShapeDecision, JobShapeDecisionError, JOB_SHAPE_NOT_DECIDED } from './job-shape-decision.js';
33
34
  export const JOB_NOT_INITIALIZED = 'JOB_NOT_INITIALIZED';
34
35
  export const JOB_REMAINING_BLOCKED = 'JOB_REMAINING_BLOCKED';
@@ -52,8 +53,14 @@ function countRemaining(statePath) {
52
53
  return Number.NaN;
53
54
  return parsed.slices.filter((sl) => sl.status !== 'done' && sl.status !== 'skipped').length;
54
55
  }
56
+ /**
57
+ * The Job state file. An id that cannot name a session dir names no file, and
58
+ * the empty string is what `existsSync` already reads as "nothing here" — the
59
+ * frame's existing answer, kept as a value so no new branch appears in it.
60
+ */
55
61
  function statePath(projectRoot, sessionId, jobId) {
56
- return join(projectRoot, '.peaks', '_runtime', sessionId, 'job', jobId, 'state.json');
62
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
63
+ return resolved.ok ? join(resolved.dir, 'job', jobId, 'state.json') : '';
57
64
  }
58
65
  /**
59
66
  * Which session a memory came from, as the memory index records it.
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
20
20
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
21
21
  import { join } from 'node:path';
22
22
  import { z } from 'zod';
23
+ import { getSessionDir, tryGetSessionDir } from '../session/getSessionDir.js';
23
24
  export const JOB_SHAPE_SCHEMA_VERSION = 1;
24
25
  export const JOB_SHAPE_FILE_NAME = 'job-shape.json';
25
26
  export const JOB_SHAPE_ALREADY_DECIDED = 'JOB_SHAPE_ALREADY_DECIDED';
@@ -54,7 +55,7 @@ export class JobShapeDecisionError extends Error {
54
55
  }
55
56
  }
56
57
  function runtimeDir(projectRoot, sessionId) {
57
- return join(projectRoot, '.peaks', '_runtime', sessionId);
58
+ return getSessionDir(projectRoot, sessionId);
58
59
  }
59
60
  function decisionPath(projectRoot, sessionId) {
60
61
  return join(runtimeDir(projectRoot, sessionId), JOB_SHAPE_FILE_NAME);
@@ -71,7 +72,17 @@ function validateRecord(input) {
71
72
  }
72
73
  /** Read the canonical record; throws JOB_SHAPE_NOT_DECIDED if absent or malformed. */
73
74
  export function readJobShapeDecision(projectRoot, sessionId) {
74
- const path = decisionPath(projectRoot, sessionId);
75
+ // A frame that promises a typed refusal, not a throw: an id that names no
76
+ // session directory is the same "no record" answer as an absent file.
77
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
78
+ if (!resolved.ok) {
79
+ throw new JobShapeDecisionError({
80
+ code: JOB_SHAPE_NOT_DECIDED,
81
+ message: `No Job-shape decision recorded for session ${sessionId}. Run \`peaks code detect-job\` to record a decision.`,
82
+ details: { reason: resolved.reason }
83
+ });
84
+ }
85
+ const path = join(resolved.dir, JOB_SHAPE_FILE_NAME);
75
86
  if (!existsSync(path)) {
76
87
  throw new JobShapeDecisionError({
77
88
  code: JOB_SHAPE_NOT_DECIDED,
@@ -22,6 +22,7 @@
22
22
  */
23
23
  import { existsSync } from 'node:fs';
24
24
  import { join } from 'node:path';
25
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
25
26
  import { JobShapeDecisionError, JOB_SHAPE_ALREADY_DECIDED, JOB_SHAPE_FILE_NAME, readJobShapeDecision, writeJobShapeDecision } from './job-shape-decision.js';
26
27
  function provisionalRationale(jobId) {
27
28
  return (`Provisional decision written by \`peaks job init\` when it created the Job ledger for ` +
@@ -40,7 +41,14 @@ function provisionalRationale(jobId) {
40
41
  * folded into `already-decided` — the winner's decision stands.
41
42
  */
42
43
  export function ensureProvisionalJobShapeDecision(projectRoot, sessionId, input) {
43
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, JOB_SHAPE_FILE_NAME);
44
+ // The function's contract is "any failure is RETURNED, never thrown", so the
45
+ // id is resolved through the total entry; an unresolvable id is the same
46
+ // `write-failed` outcome as a refused write, with no path to name.
47
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
48
+ if (!resolved.ok) {
49
+ return { written: false, path: '', reason: 'write-failed', error: resolved.reason };
50
+ }
51
+ const path = join(resolved.dir, JOB_SHAPE_FILE_NAME);
44
52
  if (existsSync(path)) {
45
53
  try {
46
54
  readJobShapeDecision(projectRoot, sessionId);
@@ -24,6 +24,7 @@
24
24
  import { existsSync, readdirSync } from 'node:fs';
25
25
  import { join } from 'node:path';
26
26
  import { getSkillPresence } from '../skills/skill-presence-service.js';
27
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
27
28
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
28
29
  import { emitObservabilityEvent } from '../observability/observability-service.js';
29
30
  import { CHECKPOINT_EXT, CHECKPOINTS_DIR, isToday, safeReadCheckpoint } from './post-compact-checkpoint.js';
@@ -89,7 +90,14 @@ export async function detectPostCompactResume(opts) {
89
90
  if (!opts.sessionId || opts.sessionId.trim().length === 0) {
90
91
  return { shouldAutoResume: false, reason: 'sid-unbound', warnings };
91
92
  }
92
- const runtimeDir = join(opts.projectRoot, '.peaks', '_runtime', opts.sessionId);
93
+ // The TOTAL entry: this probe reports its own misses as reasons, and an id
94
+ // that cannot name a session dir has no directory to probe — the same
95
+ // answer `existsSync` gives for a directory that is not there.
96
+ const sessionDir = tryGetSessionDir(opts.projectRoot, opts.sessionId);
97
+ if (!sessionDir.ok) {
98
+ return { shouldAutoResume: false, reason: 'runtime-dir-missing', warnings };
99
+ }
100
+ const runtimeDir = sessionDir.dir;
93
101
  if (!existsSync(runtimeDir)) {
94
102
  return { shouldAutoResume: false, reason: 'runtime-dir-missing', warnings };
95
103
  }
@@ -8,9 +8,11 @@
8
8
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
9
  import { join } from 'node:path';
10
10
  import { isExpectedFsMiss } from '../../shared/fs-utils.js';
11
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
11
12
  const STEP_08_PROGRESS_FILE_NAME = 'progress.json';
12
13
  function runtimeSessionDir(projectRoot, sessionId) {
13
- return join(projectRoot, '.peaks', '_runtime', sessionId);
14
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
15
+ return resolved.ok ? resolved.dir : null;
14
16
  }
15
17
  function progressPath(projectRoot, sessionId, jid) {
16
18
  // The progress file lives under job/<jid>/progress.json. The jid
@@ -19,11 +21,12 @@ function progressPath(projectRoot, sessionId, jid) {
19
21
  // the matching path directly rather than enumerating the job/ dir.
20
22
  // (Rotating mode spawns new jids but only one is "active" at a time;
21
23
  // the active jid is the latest write to job-shape.json.)
22
- return join(runtimeSessionDir(projectRoot, sessionId), 'job', jid, STEP_08_PROGRESS_FILE_NAME);
24
+ const dir = runtimeSessionDir(projectRoot, sessionId);
25
+ return dir === null ? null : join(dir, 'job', jid, STEP_08_PROGRESS_FILE_NAME);
23
26
  }
24
27
  export function readProgressIfAny(projectRoot, sessionId, jid) {
25
28
  const path = progressPath(projectRoot, sessionId, jid);
26
- if (!existsSync(path))
29
+ if (path === null || !existsSync(path))
27
30
  return null;
28
31
  try {
29
32
  const raw = readFileSync(path, 'utf8');
@@ -57,7 +60,10 @@ export function readProgressIfAny(projectRoot, sessionId, jid) {
57
60
  }
58
61
  }
59
62
  export function readPromptFromLastPromptFile(projectRoot, sessionId) {
60
- const path = join(runtimeSessionDir(projectRoot, sessionId), 'txt', 'last-prompt.txt');
63
+ const dir = runtimeSessionDir(projectRoot, sessionId);
64
+ if (dir === null)
65
+ return '';
66
+ const path = join(dir, 'txt', 'last-prompt.txt');
61
67
  if (!existsSync(path))
62
68
  return '';
63
69
  try {
@@ -87,7 +93,10 @@ export function readPromptFromLastPromptFile(projectRoot, sessionId) {
87
93
  * or a provisional write that failed — not proof the decision step was skipped.
88
94
  */
89
95
  export function ledgerJobIds(projectRoot, sessionId) {
90
- const jobDir = join(runtimeSessionDir(projectRoot, sessionId), 'job');
96
+ const dir = runtimeSessionDir(projectRoot, sessionId);
97
+ if (dir === null)
98
+ return [];
99
+ const jobDir = join(dir, 'job');
91
100
  if (!existsSync(jobDir))
92
101
  return [];
93
102
  let names;
@@ -21,6 +21,7 @@
21
21
  */
22
22
  import { existsSync, readFileSync } from 'node:fs';
23
23
  import { join } from 'node:path';
24
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
24
25
  import { writeCheckpoint } from '../session/session-checkpoint-service.js';
25
26
  import { AUTO_COMPACT_PRE_COMPACT_RATIO, AUTO_COMPACT_RED_LINE_RATIO } from '../context/auto-compact-types.js';
26
27
  const PRE_COMPACT_ZONE = {
@@ -28,7 +29,11 @@ const PRE_COMPACT_ZONE = {
28
29
  redLine: AUTO_COMPACT_RED_LINE_RATIO
29
30
  };
30
31
  function readLatestUsageRow(projectRoot, sessionId) {
31
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, 'usage.jsonl');
32
+ // An unresolvable id has no usage row — the same answer as a missing file.
33
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
34
+ if (!resolved.ok)
35
+ return null;
36
+ const path = join(resolved.dir, 'usage.jsonl');
32
37
  if (!existsSync(path))
33
38
  return null;
34
39
  try {
@@ -24,13 +24,20 @@
24
24
  */
25
25
  import { existsSync, readFileSync } from 'node:fs';
26
26
  import { join } from 'node:path';
27
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
27
28
  import { lookupPhaseTransition, buildSuggestedCompactMessage, SURVIVAL_TABLE } from './decision-tables.js';
28
29
  import { DEFAULT_TOOL_CALL_THRESHOLD, DEFAULT_CONTEXT_THRESHOLD_200K, DEFAULT_CONTEXT_THRESHOLD_1M, DEFAULT_CONTEXT_INTERVAL } from './suggest-types.js';
29
30
  /** Snapshot of the survival table for the dry-run envelope. */
30
31
  const SURVIVAL_TABLE_PERSISTS = SURVIVAL_TABLE.persists;
31
32
  const SURVIVAL_TABLE_LOST = SURVIVAL_TABLE.lost;
32
33
  function readLatestUsageRow(projectRoot, sessionId) {
33
- const path = join(projectRoot, '.peaks', '_runtime', sessionId, 'usage.jsonl');
34
+ // Total by contract — "never throws" is this module's documented surface —
35
+ // so an id that cannot name a session dir reads as "no usage row", which is
36
+ // the same answer an absent file gets.
37
+ const sessionDir = tryGetSessionDir(projectRoot, sessionId);
38
+ if (!sessionDir.ok)
39
+ return null;
40
+ const path = join(sessionDir.dir, 'usage.jsonl');
34
41
  if (!existsSync(path))
35
42
  return null;
36
43
  try {
@@ -63,6 +63,7 @@ import { readdirSync, statSync } from 'node:fs';
63
63
  import { join } from 'node:path';
64
64
  import { readJobShapeDecision } from '../code/job-shape-decision.js';
65
65
  import { describeNextSlice, tryReadJobProgress } from '../job/job-progress-store.js';
66
+ import { tryGetSessionDir } from '../session/getSessionDir.js';
66
67
  import { getSessionIdCanonical } from '../session/session-manager.js';
67
68
  /**
68
69
  * Hard ceiling on the card's size, in UTF-8 bytes.
@@ -231,25 +232,25 @@ function toPosix(p) {
231
232
  /**
232
233
  * Find the most recently modified request artifact under the session tree.
233
234
  *
234
- * This is a POINTER RESOLVER, not a content reader: it returns the artifact's
235
- * name so the card can name it, and never opens it. Deliberately limited to
236
- * `<session>/<role>/requests/*.md` — the tree every role already writes to —
237
- * rather than a repo-wide search, so the answer cannot be some unrelated
238
- * markdown file that happens to be newer.
235
+ * A POINTER RESOLVER, not a content reader: it returns the artifact's name so
236
+ * the card can name it, and never opens it. Deliberately limited to
237
+ * `<session>/<role>/requests/*.md` — the tree every role already writes to — so
238
+ * the answer cannot be some unrelated newer markdown file.
239
239
  *
240
- * Returns its failures alongside the answer instead of swallowing them. The
241
- * tempting shape here — a bare `catch { continue }` — makes two very different
242
- * states indistinguishable to the caller: "this role has no requests yet"
243
- * (ordinary, most roles) and "this role's requests directory exists but could
244
- * not be read" (a real problem worth reporting). Only `ENOENT` is the ordinary
245
- * one, so only `ENOENT` is silent.
240
+ * Returns its failures alongside the answer instead of swallowing them: a bare
241
+ * `catch { continue }` makes "no requests yet" (ordinary, most roles) and "the
242
+ * directory exists but could not be read" (a real problem worth reporting)
243
+ * indistinguishable. Only `ENOENT` is the ordinary one, so only `ENOENT` is
244
+ * silent.
246
245
  */
247
246
  function findLatestRequestArtifact(projectRoot, sessionId) {
248
- const sessionDir = join(projectRoot, '.peaks', '_runtime', sessionId);
247
+ const resolved = tryGetSessionDir(projectRoot, sessionId);
248
+ if (!resolved.ok)
249
+ return { rel: null, warnings: [] };
249
250
  const warnings = [];
250
251
  let roles;
251
252
  try {
252
- roles = readdirSync(sessionDir, { withFileTypes: true })
253
+ roles = readdirSync(resolved.dir, { withFileTypes: true })
253
254
  .filter((entry) => entry.isDirectory())
254
255
  .map((entry) => entry.name)
255
256
  .sort();
@@ -263,7 +264,7 @@ function findLatestRequestArtifact(projectRoot, sessionId) {
263
264
  }
264
265
  let best = null;
265
266
  for (const role of roles) {
266
- const requestsDir = join(sessionDir, role, 'requests');
267
+ const requestsDir = join(resolved.dir, role, 'requests');
267
268
  let files;
268
269
  try {
269
270
  files = readdirSync(requestsDir).filter((name) => name.endsWith('.md'));
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { isAbsolute, join, relative } from 'node:path';
4
+ import { getSessionDir } from '../session/getSessionDir.js';
4
5
  import { SPILL_TTL_MS } from './spillover-types.js';
5
6
  const SAFE_SEGMENT = /^[A-Za-z0-9._-]+$/;
6
7
  function assertSafeSegment(value, name) {
@@ -38,7 +39,7 @@ export function assertNotSymlink(path) {
38
39
  }
39
40
  export function spillDir(projectRoot, sessionId) {
40
41
  assertSafeSegment(sessionId, 'sessionId');
41
- return join(projectRoot, '.peaks', '_runtime', sessionId, 'spill');
42
+ return join(getSessionDir(projectRoot, sessionId), 'spill');
42
43
  }
43
44
  export function spillPath(projectRoot, sessionId, spillId) {
44
45
  assertSafeSegment(spillId, 'spillId');