peaks-loop 4.2.0 → 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 (42) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +108 -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/skill-presence-housekeeping-commands.js +7 -1
  6. package/dist/cli/commands/mut-commands-helpers.js +42 -36
  7. package/dist/cli/commands/project-context-command.js +7 -2
  8. package/dist/cli/commands/workspace/init-actions.js +5 -0
  9. package/dist/cli/commands/workspace/init-context.js +1 -0
  10. package/dist/services/code/auto-compact-artifacts.js +42 -10
  11. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  12. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  13. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  14. package/dist/services/code/auto-compact-envelopes.js +18 -4
  15. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  16. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  17. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  18. package/dist/services/mcp/context-tool.d.ts +3 -0
  19. package/dist/services/mcp/context-tool.js +135 -0
  20. package/dist/services/mcp/surface.js +7 -1
  21. package/dist/services/mcp/tools.js +3 -1
  22. package/dist/services/memory/project-context-service.d.ts +10 -1
  23. package/dist/services/memory/project-context-service.js +13 -6
  24. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  25. package/dist/services/prd/project-scan-body-tables.js +185 -0
  26. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  27. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  28. package/dist/services/prd/project-scan-content.d.ts +24 -0
  29. package/dist/services/prd/project-scan-content.js +207 -0
  30. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  31. package/dist/services/prd/project-scan-existing-state.js +61 -0
  32. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  33. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  34. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  35. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  36. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  37. package/dist/services/prd/project-scan-library-versions.js +135 -0
  38. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  39. package/dist/services/prd/project-scan-techstack.js +167 -0
  40. package/package.json +6 -6
  41. package/skills/peaks-code/SKILL.md +1 -1
  42. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
@@ -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) {
@@ -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),
@@ -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;
@@ -119,7 +119,7 @@ function buildSessionHistory(projectRoot) {
119
119
  body += `\n${MANAGED_BLOCK_END}`;
120
120
  return body;
121
121
  }
122
- export async function generateProjectContext(projectRoot) {
122
+ export async function generateProjectContext(projectRoot, options = {}) {
123
123
  const peaksDir = join(projectRoot, '.peaks');
124
124
  if (!existsSync(peaksDir)) {
125
125
  mkdirSync(peaksDir, { recursive: true });
@@ -152,11 +152,18 @@ export async function generateProjectContext(projectRoot) {
152
152
  }
153
153
  writeFileSync(contextPath, content, 'utf8');
154
154
  // After writing PROJECT.md, also bootstrap `.peaks/project-scan/`
155
- // (project-scan.md + 4 bundled audit/business templates). Idempotent
156
- // — re-running this call does not overwrite existing files (unless
157
- // the caller passes `force` / `forceTemplates`, which we do NOT do
158
- // here; peaks workspace init owns the force variants).
159
- const projectScan = await bootstrapProjectScan({ projectRoot });
155
+ // (project-scan.md + 4 bundled audit/business templates). The 4 templates
156
+ // are sediment-protected (skipped when present). The scan's OWN machine
157
+ // fields are refreshed by default, because this command already regenerates
158
+ // `.peaks/PROJECT.md` unconditionally on every run: a frozen
159
+ // `libraryVersions` map makes peaks-rd's breaking-change cross-check pass on
160
+ // stale input. `refreshMachineFields` rewrites only `capturedAt` /
161
+ // `techStack` / `libraryVersions` and preserves every other byte, so the
162
+ // hand-authored prose survives. Pass `refreshProjectScan: false` to skip.
163
+ const projectScan = await bootstrapProjectScan({
164
+ projectRoot,
165
+ refreshMachineFields: options.refreshProjectScan !== false
166
+ });
160
167
  return {
161
168
  path: contextPath,
162
169
  content,
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Keeping the body tables of `.peaks/project-scan/project-scan.md` in step with
3
+ * the frontmatter a refresh just rewrote.
4
+ *
5
+ * WHY THIS EXISTS — a measured defect, not a guess. `peaks-rd`'s own reference
6
+ * (`references/library-version-awareness.md`) tells RD to read the `## Library
7
+ * versions` TABLE, while `readProjectScan` reads the FRONTMATTER. A refresh that
8
+ * only touched the frontmatter left the two disagreeing: measured 2026-11-16 on
9
+ * this repository's own scan — 32 names in the frontmatter, 21 rows in the
10
+ * table, 11 names (including `typescript`) present in only one of them. RD would
11
+ * then cross-check a breaking-change table against rows that never moved.
12
+ *
13
+ * WHAT MAY BE REWRITTEN. Only the version CELL of a row whose package is in the
14
+ * refreshed map, plus whole rows appended for packages the table lacks. The
15
+ * Notes column, the header, the row order and every other prose table are
16
+ * untouched — those are sediment.
17
+ */
18
+ export declare function refreshLibraryVersionsTable(body: string, versions: Readonly<Record<string, string>>): string;
19
+ /**
20
+ * Fill the `## Tech stack` table's EMPTY value cells from `techStack`.
21
+ *
22
+ * WHY IT ONLY FILLS, NEVER OVERWRITES. These cells are prose, not a machine
23
+ * record: this repository's own scan reads
24
+ * `| Build | \`tsc -p tsconfig.build.json\` (root, via \`pnpm build\`) + per-package ... |`.
25
+ * An earlier version of this function replaced that with the bare derived
26
+ * `tsc -p tsconfig.build.json`, and did the same to the Language, Package manager
27
+ * and Node runtime rows — measured 2026-11-16, on the very file this slice
28
+ * exists to protect. The derived value is strictly less informative than what an
29
+ * author writes here, so it may only take a cell that is empty or a placeholder.
30
+ * The machine-readable copy is the FRONTMATTER, which is refreshed in full; this
31
+ * table is for humans and stays theirs.
32
+ */
33
+ export declare function refreshTechStackTable(body: string, techStack: Readonly<Record<string, string>>): string;