peaks-loop 4.2.0 → 4.2.2

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 +165 -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,185 @@
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
+ /** One body table a refresher may touch, and the column that holds its version. */
19
+ const VERSION_CELL_INDEX = 1;
20
+ /** A markdown table row, split into its raw cells (`null` when it is not a row). */
21
+ function cellsOf(line) {
22
+ const trimmed = line.trim();
23
+ if (!trimmed.startsWith('|') || !trimmed.endsWith('|'))
24
+ return null;
25
+ return trimmed.slice(1, -1).split('|');
26
+ }
27
+ /** Re-join cells into a row, preserving the padding style of the original. */
28
+ function joinCells(cells) {
29
+ return `|${cells.join('|')}|`;
30
+ }
31
+ /** The package name a row names, or `null` when the row is not a package row. */
32
+ function packageNameOf(cells) {
33
+ const first = (cells[0] ?? '').trim();
34
+ const backticked = /^`([^`]+)`$/.exec(first);
35
+ if (backticked !== null)
36
+ return backticked[1] ?? null;
37
+ // The create path writes rows without backticks; accept a bare name too.
38
+ return first === '' || first.includes(' ') ? null : first;
39
+ }
40
+ /** True for the `|---|---|` separator row. */
41
+ function isSeparator(cells) {
42
+ return cells.every((cell) => /^\s*:?-{2,}:?\s*$/.test(cell));
43
+ }
44
+ /** The table's first and last line index under the heading, or `null`. */
45
+ function tableBounds(lines, headingAt) {
46
+ let first = -1;
47
+ for (let i = headingAt + 1; i < lines.length; i += 1) {
48
+ if (cellsOf(lines[i] ?? '') !== null) {
49
+ first = i;
50
+ break;
51
+ }
52
+ // A later heading before any table row means there is no table here.
53
+ if (/^#{1,6}\s/.test((lines[i] ?? '').trim()))
54
+ return null;
55
+ }
56
+ if (first < 0)
57
+ return null;
58
+ let last = first;
59
+ while (last + 1 < lines.length && cellsOf(lines[last + 1] ?? '') !== null)
60
+ last += 1;
61
+ return { first, last };
62
+ }
63
+ /** Rewrite one row's version cell, preserving its backtick style. */
64
+ function rewriteVersionCell(cells, spec) {
65
+ const next = [...cells];
66
+ const previous = (next[VERSION_CELL_INDEX] ?? '').trim();
67
+ const backticked = /^`.*`$/.test(previous);
68
+ next[VERSION_CELL_INDEX] = backticked ? ` \`${spec}\` ` : ` ${spec} `;
69
+ return joinCells(next);
70
+ }
71
+ /** Rewrite a single body line against `versions`, or leave it alone. */
72
+ function rewriteRow(line, versions) {
73
+ const cells = cellsOf(line);
74
+ if (cells === null)
75
+ return null;
76
+ if (isSeparator(cells))
77
+ return { line, name: null, width: cells.length };
78
+ const name = packageNameOf(cells);
79
+ if (name === null)
80
+ return { line, name: null, width: cells.length };
81
+ const spec = versions[name];
82
+ return {
83
+ line: spec === undefined ? line : rewriteVersionCell(cells, spec),
84
+ name,
85
+ width: cells.length
86
+ };
87
+ }
88
+ /** A row for a package the table does not carry, shaped like its neighbours. */
89
+ function appendRow(name, spec, width) {
90
+ const row = Array.from({ length: width }, () => ' ');
91
+ row[0] = ` \`${name}\` `;
92
+ row[VERSION_CELL_INDEX] = ` \`${spec}\` `;
93
+ return joinCells(row);
94
+ }
95
+ export function refreshLibraryVersionsTable(body, versions) {
96
+ const lines = body.split('\n');
97
+ const headingAt = lines.findIndex((line) => /^##\s+Library versions\s*$/.test(line.trim()));
98
+ if (headingAt < 0)
99
+ return body;
100
+ const bounds = tableBounds(lines, headingAt);
101
+ if (bounds === null)
102
+ return body;
103
+ const { first, last } = bounds;
104
+ const seen = new Set();
105
+ const rewritten = [];
106
+ let width = VERSION_CELL_INDEX + 1;
107
+ for (let i = first; i <= last; i += 1) {
108
+ const result = rewriteRow(lines[i] ?? '', versions);
109
+ if (result === null)
110
+ continue;
111
+ width = Math.max(width, result.width);
112
+ if (result.name !== null)
113
+ seen.add(result.name);
114
+ rewritten.push(result.line);
115
+ }
116
+ for (const name of Object.keys(versions).sort()) {
117
+ if (!seen.has(name))
118
+ rewritten.push(appendRow(name, versions[name] ?? '', width));
119
+ }
120
+ return [...lines.slice(0, first), ...rewritten, ...lines.slice(last + 1)].join('\n');
121
+ }
122
+ /**
123
+ * Rewrite the `## Tech stack` table's value cells from `techStack`, matched by
124
+ * the row's own label. A label with no derived value keeps whatever the author
125
+ * wrote — the table labels are prose ("Node runtime", "Build"), not machine keys,
126
+ * so this matches on a small label→key map rather than guessing.
127
+ */
128
+ const TECH_STACK_LABELS = [
129
+ [/^language$/i, 'language'],
130
+ [/^package manager$/i, 'packageManager'],
131
+ [/^node runtime$/i, 'runtime'],
132
+ [/^build$/i, 'buildTool']
133
+ ];
134
+ /** Cell text that carries no information — safe to fill. */
135
+ function isPlaceholderCell(text) {
136
+ const stripped = text.replace(/[`*_]/g, '').trim();
137
+ return stripped === '' || /^\(?(empty|unknown|n\/a|—|-)\)?$/i.test(stripped);
138
+ }
139
+ /**
140
+ * Fill the `## Tech stack` table's EMPTY value cells from `techStack`.
141
+ *
142
+ * WHY IT ONLY FILLS, NEVER OVERWRITES. These cells are prose, not a machine
143
+ * record: this repository's own scan reads
144
+ * `| Build | \`tsc -p tsconfig.build.json\` (root, via \`pnpm build\`) + per-package ... |`.
145
+ * An earlier version of this function replaced that with the bare derived
146
+ * `tsc -p tsconfig.build.json`, and did the same to the Language, Package manager
147
+ * and Node runtime rows — measured 2026-11-16, on the very file this slice
148
+ * exists to protect. The derived value is strictly less informative than what an
149
+ * author writes here, so it may only take a cell that is empty or a placeholder.
150
+ * The machine-readable copy is the FRONTMATTER, which is refreshed in full; this
151
+ * table is for humans and stays theirs.
152
+ */
153
+ export function refreshTechStackTable(body, techStack) {
154
+ const lines = body.split('\n');
155
+ const headingAt = lines.findIndex((line) => /^##\s+Tech stack\s*$/.test(line.trim()));
156
+ if (headingAt < 0)
157
+ return body;
158
+ let last = headingAt;
159
+ while (last + 1 < lines.length) {
160
+ const next = lines[last + 1] ?? '';
161
+ if (/^#{1,6}\s/.test(next.trim()) && last > headingAt)
162
+ break;
163
+ if (next.trim() === '' && last > headingAt + 1)
164
+ break;
165
+ last += 1;
166
+ }
167
+ const rewritten = lines.slice(headingAt, last + 1).map((line) => {
168
+ const cells = cellsOf(line);
169
+ if (cells === null || isSeparator(cells))
170
+ return line;
171
+ const label = (cells[0] ?? '').trim();
172
+ const match = TECH_STACK_LABELS.find(([pattern]) => pattern.test(label));
173
+ if (match === undefined)
174
+ return line;
175
+ const value = techStack[match[1]];
176
+ if (value === undefined)
177
+ return line;
178
+ if (!isPlaceholderCell(cells[1] ?? ''))
179
+ return line;
180
+ const next = [...cells];
181
+ next[1] = ` ${value} `;
182
+ return joinCells(next);
183
+ });
184
+ return [...lines.slice(0, headingAt), ...rewritten, ...lines.slice(last + 1)].join('\n');
185
+ }
@@ -11,7 +11,10 @@
11
11
  * `src/services/workspace/templates/project-scan/`) into
12
12
  * `.peaks/project-scan/` (AC9)
13
13
  * - idempotent: skips re-writes when the existing file is at
14
- * schemaVersion:1 (AC3); --force / --force-templates override
14
+ * schemaVersion:1 (AC3); `refreshMachineFields` rewrites only the
15
+ * machine-derivable fields of such a file (see
16
+ * `project-scan-field-refresh.ts`), and `forceTemplates` overrides the
17
+ * 4 bundled templates' skip
15
18
  *
16
19
  * Called by:
17
20
  * - `peaks project context` (via `generateProjectContext`)
@@ -24,8 +27,14 @@
24
27
  */
25
28
  export type BootstrapProjectScanOptions = {
26
29
  readonly projectRoot: string;
27
- /** Override the existing-file skip and rewrite project-scan.md. */
28
- readonly force?: boolean;
30
+ /**
31
+ * Rewrite the machine-derivable frontmatter fields (`capturedAt`,
32
+ * `techStack`, `libraryVersions`) of an existing `schemaVersion: 1`
33
+ * project-scan.md, preserving every other byte. A file that was never
34
+ * populated (empty `architecture` AND empty `techStack`) is refreshed even
35
+ * without this option — it is a shell, not sediment.
36
+ */
37
+ readonly refreshMachineFields?: boolean;
29
38
  /** Override the bundled-template skip and overwrite audit/business files. */
30
39
  readonly forceTemplates?: boolean;
31
40
  };
@@ -34,6 +43,8 @@ export type BootstrapProjectScanEnvelope = {
34
43
  readonly created: boolean;
35
44
  /** True iff project-scan.md existed and was skipped (idempotent). */
36
45
  readonly skipped: boolean;
46
+ /** True iff only the machine-derivable frontmatter fields were rewritten. */
47
+ readonly refreshed: boolean;
37
48
  /** Count of files written to .peaks/project-scan/ (1 project-scan.md + N templates). */
38
49
  readonly templatesBooted: number;
39
50
  /** Count of files already present and skipped (sediment-preserved). */
@@ -42,6 +53,8 @@ export type BootstrapProjectScanEnvelope = {
42
53
  readonly projectScanPath: string;
43
54
  /** Resolved archetype (when existing-project path was taken). */
44
55
  readonly archetype?: string;
56
+ /** Why an existing project-scan.md could not be machine-refreshed. */
57
+ readonly refreshWarning?: string;
45
58
  /** Total wall-time of the bootstrap call. */
46
59
  readonly durationMs: number;
47
60
  };
@@ -11,7 +11,10 @@
11
11
  * `src/services/workspace/templates/project-scan/`) into
12
12
  * `.peaks/project-scan/` (AC9)
13
13
  * - idempotent: skips re-writes when the existing file is at
14
- * schemaVersion:1 (AC3); --force / --force-templates override
14
+ * schemaVersion:1 (AC3); `refreshMachineFields` rewrites only the
15
+ * machine-derivable fields of such a file (see
16
+ * `project-scan-field-refresh.ts`), and `forceTemplates` overrides the
17
+ * 4 bundled templates' skip
15
18
  *
16
19
  * Called by:
17
20
  * - `peaks project context` (via `generateProjectContext`)
@@ -27,6 +30,9 @@ import { join } from 'node:path';
27
30
  import { scanArchetype } from '../scan/archetype-service.js';
28
31
  import { scanLibraries } from '../scan/libraries-service.js';
29
32
  import { TEMPLATE_FILES, readTemplateStrict } from '../workspace/templates/project-scan/index.js';
33
+ import { refreshProjectScanOnDisk } from './project-scan-field-refresh.js';
34
+ import { deriveTechStack } from './project-scan-techstack.js';
35
+ import { buildExistingProjectScan, buildZeroToOneProjectScan } from './project-scan-content.js';
30
36
  const PROJECT_SCAN_DIR = join('.peaks', 'project-scan');
31
37
  const PROJECT_SCAN_FILENAME = 'project-scan.md';
32
38
  const PROJECT_SCAN_PATH = join(PROJECT_SCAN_DIR, PROJECT_SCAN_FILENAME);
@@ -119,11 +125,14 @@ function directoryContainsSourceFiles(rootDir) {
119
125
  * Heuristic for "this directory holds source code".
120
126
  *
121
127
  * 1. `src/` at the root (single-package layout).
122
- * 2. Any of the monorepo source roots: `packages/`, `apps/`, `libs/`,
123
- * `services/`, `workspaces/` — each is checked recursively for at
124
- * test, 2026-07-15): the original implementation only looked at
125
- * `src/` and mis-classified monorepos as 0-1 (pnpm-workspace layout
126
- * puts source under `packages/<pkg>/src/`, not `<root>/src/`).
128
+ * 2. Any of the monorepo / framework source roots: `packages/`, `apps/`,
129
+ * `libs/`, `services/`, `workspaces/`, `app/` (Next.js App Router), and
130
+ * `server/` — each is checked recursively for source files.
131
+ * 3. The project ROOT itself, recursively — which catches the layouts that name
132
+ * none of the above. Measured 2026-11-16: without it, a Next.js `app/*.tsx`
133
+ * tree, a `server/` layout and a flat repo with `index.ts` at the root were
134
+ * all classified 0-1, and because `zeroToOne` gates the refresh their scans
135
+ * stayed stale forever.
127
136
  *
128
137
  * Returns true on the first hit. False when none of the candidate
129
138
  * roots contain source files (genuine 0-1).
@@ -131,7 +140,15 @@ function directoryContainsSourceFiles(rootDir) {
131
140
  function projectHasSourceFiles(projectRoot) {
132
141
  if (directoryContainsSourceFiles(join(projectRoot, 'src')))
133
142
  return true;
134
- const monorepoSourceRoots = ['packages', 'apps', 'libs', 'services', 'workspaces'];
143
+ const monorepoSourceRoots = [
144
+ 'packages',
145
+ 'apps',
146
+ 'libs',
147
+ 'services',
148
+ 'workspaces',
149
+ 'app',
150
+ 'server'
151
+ ];
135
152
  for (const candidate of monorepoSourceRoots) {
136
153
  const dir = join(projectRoot, candidate);
137
154
  if (!existsSync(dir))
@@ -139,7 +156,7 @@ function projectHasSourceFiles(projectRoot) {
139
156
  if (directoryContainsSourceFiles(dir))
140
157
  return true;
141
158
  }
142
- return false;
159
+ return directoryContainsSourceFiles(projectRoot);
143
160
  }
144
161
  /** Detect 0-1: no package.json OR no source files.
145
162
  * source under packages/<pkg>/ are no longer mis-classified as 0-1. */
@@ -159,10 +176,22 @@ function isZeroToOneProject(projectRoot) {
159
176
  }
160
177
  /**
161
178
  * Parse the frontmatter `schemaVersion` from an existing project-scan.md.
162
- * Returns `null` when the file is absent, malformed, or has no version.
163
- * The reader in `services/prd/project-scan-reader.ts` is the canonical
164
- * parser; we re-implement the minimum here to avoid coupling the
165
- * bootstrap path to that reader's strict shape validation.
179
+ *
180
+ * Three answers, and the difference between them is load-bearing:
181
+ * - `null` — no file at all. The caller may create one.
182
+ * - `1` — a file this code understands. Refresh it in place.
183
+ * - `0` — a file IS present but its version could not be read. The caller
184
+ * must NOT regenerate it: `0` exists precisely so that "present,
185
+ * unclassifiable" is never mistaken for "absent", because
186
+ * regenerating destroys whatever prose the file holds.
187
+ *
188
+ * CRLF-TOLERANT. `core.autocrlf=true` is the default on Windows, so a checkout
189
+ * hands this function `---\r\n`. A pattern anchored on `\n` alone read such a
190
+ * file as version 0 — which used to fall through to the CREATE branch and
191
+ * overwrite hand-written architecture notes, pinned-version warnings and memory
192
+ * blocks. Measured on 2026-11-16: a CRLF copy of a hand-authored scan lost all
193
+ * three. Hence the `\r?\n` below, which is what keeps a Windows checkout out of
194
+ * that branch.
166
195
  */
167
196
  function readExistingSchemaVersion(absPath) {
168
197
  if (!existsSync(absPath))
@@ -172,186 +201,17 @@ function readExistingSchemaVersion(absPath) {
172
201
  raw = readFileSync(absPath, 'utf8');
173
202
  }
174
203
  catch {
175
- return null;
204
+ return 0;
176
205
  }
177
- const match = /^---\n([\s\S]*?)\n---/.exec(raw);
206
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(raw);
178
207
  if (!match)
179
- return null;
208
+ return 0;
180
209
  const frontmatter = match[1] ?? '';
181
210
  const versionMatch = /^\s*schemaVersion:\s*(\d+)/m.exec(frontmatter);
182
211
  if (!versionMatch)
183
- return null;
212
+ return 0;
184
213
  const parsed = Number(versionMatch[1]);
185
- return Number.isSafeInteger(parsed) ? parsed : null;
186
- }
187
- /** Build the project-scan.md content for a 0-1 project (empty placeholders). */
188
- function buildZeroToOneProjectScan() {
189
- const now = new Date().toISOString();
190
- return [
191
- '---',
192
- 'schemaVersion: 1',
193
- `capturedAt: ${now}`,
194
- 'archetype: unknown',
195
- 'confidence: low',
196
- 'techStack: {}',
197
- 'libraryVersions: {}',
198
- 'architecture: ""',
199
- 'karpathySelfCheck: {}',
200
- '---',
201
- '',
202
- '# Project Scan (0-1 bootstrap)',
203
- '',
204
- `> Auto-generated by \`peaks workspace init\` / \`peaks project context\` on ${now}. ` +
205
- 'Refresh with `peaks project context --project <repo>` once the project has a `package.json` + source files.',
206
- '',
207
- '## Archetype',
208
- '',
209
- '| Field | Value |',
210
- '|---|---|',
211
- '| Type | `unknown` |',
212
- '| Confidence | `low` |',
213
- '',
214
- '## Project mode',
215
- '',
216
- '| Field | Value |',
217
- '|---|---|',
218
- '| Integration mode | unknown |',
219
- '| Integration mode reason | 0-1 bootstrap — refresh after the first source file lands |',
220
- '| Frontend-only | `false` |',
221
- '| Reason | 0-1 project, no package.json or source files |',
222
- '',
223
- '## Tech stack',
224
- '',
225
- '| Concern | Value |',
226
- '|---|---|',
227
- '| Language | (empty) |',
228
- '| Package manager | (empty) |',
229
- '| Node runtime | (empty) |',
230
- '| Build | (empty) |',
231
- '| Tests | (empty) |',
232
- '',
233
- '## Library versions',
234
- '',
235
- '| Package | Pinned range | Major | Scope | Ecosystem |',
236
- '|---|---|---|---|---|',
237
- '| (empty) | — | — | — | — |',
238
- '',
239
- '## Architecture',
240
- '',
241
- '_No architecture recorded yet — refresh with `peaks project context --project <repo>` once the project has source files._',
242
- '',
243
- '## Karpathy self-check',
244
- '',
245
- '| Guideline | Where enforced |',
246
- '|---|---|',
247
- '| §1 Think Before Coding | (empty) |',
248
- '| §2 Simplicity First | (empty) |',
249
- '| §3 Surgical Changes | (empty) |',
250
- '| §4 Goal-Driven Execution | (empty) |',
251
- '',
252
- '## Refresh procedure',
253
- '',
254
- '1. Add a `package.json` (with `pnpm init` or equivalent).',
255
- '2. Add at least one TypeScript/JavaScript/Vue/Svelte source file under `src/`.',
256
- '3. Re-run `peaks project context --project <repo>` — the empty placeholders are replaced with real archetype + libraryVersions.',
257
- ''
258
- ].join('\n');
259
- }
260
- /** Render a LibraryReport as a markdown table body (header row included). */
261
- function renderLibraryTable(libraryReport) {
262
- const header = '| Package | Pinned range | Major | Scope | Ecosystem |';
263
- const sep = '|---|---|---|---|---|';
264
- if (libraryReport.libraries.length === 0) {
265
- return [header, sep, '| (empty) | — | — | — | — |'].join('\n');
266
- }
267
- const rows = libraryReport.libraries.map((entry) => {
268
- const major = entry.major === null ? '—' : String(entry.major);
269
- return `| \`${entry.name}\` | \`${entry.version}\` | ${major} | ${entry.scope} | ${entry.ecosystem} |`;
270
- });
271
- return [header, sep, ...rows].join('\n');
272
- }
273
- /** Build the project-scan.md content for an existing project. */
274
- async function buildExistingProjectScan(args) {
275
- const { archetypeReport, libraryReport } = args;
276
- const now = new Date().toISOString();
277
- const runtime = (process.versions.node ?? 'unknown').trim();
278
- // Library versions snapshot: a flat {name: version} map. Mirrors the
279
- // shape consumed by `services/prd/project-scan-types.ts`
280
- // `ProjectScanLibraryVersions`.
281
- const libraryVersionsMap = {};
282
- for (const entry of libraryReport.libraries) {
283
- libraryVersionsMap[entry.name] = entry.version;
284
- }
285
- const lines = [
286
- '---',
287
- 'schemaVersion: 1',
288
- `capturedAt: ${now}`,
289
- `archetype: ${archetypeReport.archetype}`,
290
- `confidence: ${archetypeReport.confidence}`,
291
- 'techStack: {}',
292
- `libraryVersions: ${JSON.stringify(libraryVersionsMap, null, 2)
293
- .split('\n')
294
- .map((line, idx) => (idx === 0 ? line : ' ' + line))
295
- .join('\n')}`,
296
- 'architecture: ""',
297
- 'karpathySelfCheck: {}',
298
- '---',
299
- '',
300
- `# Project Scan (refreshed ${now})`,
301
- '',
302
- '> Auto-generated by `peaks workspace init` / `peaks project context`.',
303
- '',
304
- '## Archetype',
305
- '',
306
- '| Field | Value |',
307
- '|---|---|',
308
- `| Type | \`${archetypeReport.archetype}\` |`,
309
- `| Confidence | \`${archetypeReport.confidence}\` |`,
310
- '',
311
- '## Project mode',
312
- '',
313
- '| Field | Value |',
314
- '|---|---|',
315
- `| Integration mode | ${archetypeReport.integrationMode} |`,
316
- `| Integration mode reason | ${archetypeReport.integrationModeReason} |`,
317
- `| Frontend-only | \`${String(archetypeReport.frontendOnly)}\` |`,
318
- `| Reason | ${archetypeReport.frontendOnlyReason} |`,
319
- '',
320
- '## Tech stack',
321
- '',
322
- '| Concern | Value |',
323
- '|---|---|',
324
- '| Language | TypeScript (best-effort — re-confirm via package.json devDeps) |',
325
- '| Package manager | pnpm (best-effort) |',
326
- `| Node runtime | node ${runtime} |`,
327
- '| Build | tsc / package.json `build` script |',
328
- '| Tests | vitest (best-effort) |',
329
- '',
330
- '## Library versions',
331
- '',
332
- renderLibraryTable(libraryReport),
333
- '',
334
- '## Architecture',
335
- '',
336
- `_Auto-generated from \`scanArchetype\` signals — see archetypeReport.backendFrameworks / .backendDirsPresent / .swaggerPaths in \`.peaks/_runtime/<sid>/rd/project-scan.md\` (legacy) or \`.peaks/project-scan/project-scan.md\` (this file) for the raw facts._`,
337
- '',
338
- '## Karpathy self-check',
339
- '',
340
- '| Guideline | Where enforced |',
341
- '|---|---|',
342
- '| §1 Think Before Coding | (refresh with LLM review) |',
343
- '| §2 Simplicity First | (refresh with LLM review) |',
344
- '| §3 Surgical Changes | (refresh with LLM review) |',
345
- '| §4 Goal-Driven Execution | (refresh with LLM review) |',
346
- '',
347
- '## Refresh procedure',
348
- '',
349
- '1. Re-run `peaks scan archetype --project <repo> --json` and `peaks scan libraries --project <repo> --json` after any dependency / archetype change.',
350
- '2. Re-run `peaks project context --project <repo>` to refresh this file.',
351
- '3. Commit the regenerated project-scan.md alongside the dependency bump.',
352
- ''
353
- ];
354
- return lines.join('\n');
214
+ return Number.isSafeInteger(parsed) ? parsed : 0;
355
215
  }
356
216
  /**
357
217
  * Ensure `.peaks/project-scan/` exists. Idempotent.
@@ -377,61 +237,97 @@ async function bootTemplate(args) {
377
237
  return true;
378
238
  }
379
239
  /**
380
- * Public entry point. See the file header for the full contract.
240
+ * Write, refresh, or leave alone the project-scan.md, and say which happened.
241
+ *
242
+ * The three outcomes are mutually exclusive and each has a reason the envelope
243
+ * has to carry:
244
+ * - CREATE only when the file is ABSENT (`existingVersion === null`);
245
+ * - REFRESH when a file is present and editable — at schemaVersion 1, or at an
246
+ * unreadable version (`0`), where the refresh rewrites the machine fields
247
+ * it can find and leaves everything else alone;
248
+ * - SKIP otherwise — including a still-0-1 project, whose placeholder is
249
+ * TRUTHFUL rather than stale.
250
+ *
251
+ * A PRESENT but unclassifiable file never reaches CREATE. That is the rule the
252
+ * `0` return exists for: regenerating a file whose prose nobody can classify is
253
+ * how a hand-written architecture note, a pinned-version warning and a memory
254
+ * block get destroyed, and the file's own body is not something this layer has
255
+ * any right to replace.
381
256
  */
382
- export async function bootstrapProjectScan(options) {
383
- const startedAt = Date.now();
384
- ensureProjectScanDir(options.projectRoot);
385
- const projectScanAbsPath = join(options.projectRoot, PROJECT_SCAN_PATH);
386
- const existingVersion = readExistingSchemaVersion(projectScanAbsPath);
387
- // Decide whether project-scan.md is created or skipped. Idempotency:
388
- // when an existing file already declares schemaVersion:1 we honor
389
- // sediment unless `force=true`.
390
- let created = false;
391
- let skipped = false;
392
- let archetype;
393
- if (existingVersion === 1 && options.force !== true) {
394
- skipped = true;
257
+ async function decideProjectScanWrite(args) {
258
+ if (args.existingVersion !== null) {
259
+ const outcome = await refreshProjectScanOnDisk({
260
+ absolutePath: args.absPath,
261
+ projectRoot: args.projectRoot,
262
+ zeroToOne: args.zeroToOne,
263
+ requested: args.refreshMachineFields
264
+ });
265
+ return {
266
+ created: false,
267
+ skipped: outcome.skipped,
268
+ refreshed: outcome.refreshed,
269
+ ...(outcome.warning !== undefined ? { warning: outcome.warning } : {})
270
+ };
395
271
  }
396
- else {
397
- const zeroToOne = isZeroToOneProject(options.projectRoot);
398
- if (zeroToOne) {
399
- archetype = 'unknown';
400
- writeFileSync(projectScanAbsPath, buildZeroToOneProjectScan(), 'utf8');
401
- }
402
- else {
403
- const archetypeReport = await scanArchetype({ projectRoot: options.projectRoot });
404
- const libraryReport = await scanLibraries({ projectRoot: options.projectRoot });
405
- archetype = archetypeReport.archetype;
406
- const content = await buildExistingProjectScan({ archetypeReport, libraryReport });
407
- writeFileSync(projectScanAbsPath, content, 'utf8');
408
- }
409
- created = true;
272
+ if (args.zeroToOne) {
273
+ writeFileSync(args.absPath, buildZeroToOneProjectScan(), 'utf8');
274
+ return { created: true, skipped: false, refreshed: false, archetype: 'unknown' };
410
275
  }
411
- // Boot the 4 bundled templates (AC9). The project-scan.md we just
412
- // wrote (or preserved) is also counted as 1 template.
413
- let templatesBooted = created ? 1 : 0;
414
- let templatesSkipped = created ? 0 : 1;
276
+ const archetypeReport = await scanArchetype({ projectRoot: args.projectRoot });
277
+ const libraryReport = await scanLibraries({ projectRoot: args.projectRoot });
278
+ const content = buildExistingProjectScan({
279
+ archetypeReport,
280
+ libraryReport,
281
+ techStack: deriveTechStack(args.projectRoot)
282
+ });
283
+ writeFileSync(args.absPath, content, 'utf8');
284
+ return { created: true, skipped: false, refreshed: false, archetype: archetypeReport.archetype };
285
+ }
286
+ /** Boot the 4 bundled templates (AC9) and count what was written vs preserved. */
287
+ async function bootTemplates(args) {
288
+ let booted = 0;
289
+ let skipped = 0;
415
290
  for (const name of TEMPLATE_FILES) {
416
291
  const wrote = await bootTemplate({
417
- projectRoot: options.projectRoot,
292
+ projectRoot: args.projectRoot,
418
293
  name,
419
- force: options.forceTemplates === true
294
+ force: args.force
420
295
  });
421
- if (wrote) {
422
- templatesBooted += 1;
423
- }
424
- else {
425
- templatesSkipped += 1;
426
- }
296
+ if (wrote)
297
+ booted += 1;
298
+ else
299
+ skipped += 1;
427
300
  }
301
+ return { booted, skipped };
302
+ }
303
+ /**
304
+ * Public entry point. See the file header for the full contract.
305
+ */
306
+ export async function bootstrapProjectScan(options) {
307
+ const startedAt = Date.now();
308
+ ensureProjectScanDir(options.projectRoot);
309
+ const projectScanAbsPath = join(options.projectRoot, PROJECT_SCAN_PATH);
310
+ const decision = await decideProjectScanWrite({
311
+ absPath: projectScanAbsPath,
312
+ projectRoot: options.projectRoot,
313
+ existingVersion: readExistingSchemaVersion(projectScanAbsPath),
314
+ zeroToOne: isZeroToOneProject(options.projectRoot),
315
+ refreshMachineFields: options.refreshMachineFields === true
316
+ });
317
+ const templates = await bootTemplates({
318
+ projectRoot: options.projectRoot,
319
+ force: options.forceTemplates === true
320
+ });
321
+ // The project-scan.md this call wrote (or preserved) counts as 1 template.
428
322
  return {
429
- created,
430
- skipped,
431
- templatesBooted,
432
- templatesSkipped,
323
+ created: decision.created,
324
+ skipped: decision.skipped,
325
+ refreshed: decision.refreshed,
326
+ templatesBooted: templates.booted + (decision.created ? 1 : 0),
327
+ templatesSkipped: templates.skipped + (decision.created ? 0 : 1),
433
328
  projectScanPath: projectScanAbsPath,
434
- ...(archetype !== undefined ? { archetype } : {}),
329
+ ...(decision.archetype !== undefined ? { archetype: decision.archetype } : {}),
330
+ ...(decision.warning !== undefined ? { refreshWarning: decision.warning } : {}),
435
331
  durationMs: Date.now() - startedAt
436
332
  };
437
333
  }