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,24 @@
1
+ /**
2
+ * The two project-scan.md CONTENT BUILDERS: the 0-1 placeholder and the
3
+ * existing-project scan.
4
+ *
5
+ * Split out of `project-scan-bootstrap-service.ts`. That file owns the
6
+ * create-or-skip decision and the envelope; this one owns what the file says,
7
+ * and nothing here makes a decision. The split is a size split — the bootstrap
8
+ * file carries a lint ceiling that may only shrink, and the refresh feature had
9
+ * to fit under it.
10
+ *
11
+ * Both builders are reached from the CREATE path only. An existing file is never
12
+ * regenerated: its machine fields are refreshed in place
13
+ * (`project-scan-field-refresh.ts`) and its prose is sediment.
14
+ */
15
+ import type { ArchetypeReport } from '../scan/scan-types.js';
16
+ import type { LibraryReport } from '../scan/libraries-types.js';
17
+ /** Build the project-scan.md content for a 0-1 project (empty placeholders). */
18
+ export declare function buildZeroToOneProjectScan(): string;
19
+ /** Build the project-scan.md content for an existing project. */
20
+ export declare function buildExistingProjectScan(args: {
21
+ archetypeReport: ArchetypeReport;
22
+ libraryReport: LibraryReport;
23
+ techStack: Readonly<Record<string, string>>;
24
+ }): string;
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The two project-scan.md CONTENT BUILDERS: the 0-1 placeholder and the
3
+ * existing-project scan.
4
+ *
5
+ * Split out of `project-scan-bootstrap-service.ts`. That file owns the
6
+ * create-or-skip decision and the envelope; this one owns what the file says,
7
+ * and nothing here makes a decision. The split is a size split — the bootstrap
8
+ * file carries a lint ceiling that may only shrink, and the refresh feature had
9
+ * to fit under it.
10
+ *
11
+ * Both builders are reached from the CREATE path only. An existing file is never
12
+ * regenerated: its machine fields are refreshed in place
13
+ * (`project-scan-field-refresh.ts`) and its prose is sediment.
14
+ */
15
+ import { renderFrontmatterField } from './project-scan-field-refresh.js';
16
+ /** Build the project-scan.md content for a 0-1 project (empty placeholders). */
17
+ export function buildZeroToOneProjectScan() {
18
+ const now = new Date().toISOString();
19
+ return [
20
+ ...zeroToOneFrontmatter(now),
21
+ '',
22
+ '# Project Scan (0-1 bootstrap)',
23
+ '',
24
+ `> Auto-generated by \`peaks workspace init\` / \`peaks project context\` on ${now}. ` +
25
+ 'Refresh with `peaks project context --project <repo>` once the project has a `package.json` + source files.',
26
+ '',
27
+ ...ZERO_TO_ONE_SECTIONS,
28
+ ''
29
+ ].join('\n');
30
+ }
31
+ function zeroToOneFrontmatter(now) {
32
+ return [
33
+ '---',
34
+ 'schemaVersion: 1',
35
+ `capturedAt: ${now}`,
36
+ 'archetype: unknown',
37
+ 'confidence: low',
38
+ 'techStack: {}',
39
+ 'libraryVersions: {}',
40
+ 'architecture: ""',
41
+ 'karpathySelfCheck: {}',
42
+ '---'
43
+ ];
44
+ }
45
+ /** The 0-1 body: every value is a placeholder, so it is one constant. */
46
+ const ZERO_TO_ONE_SECTIONS = [
47
+ '## Archetype',
48
+ '',
49
+ '| Field | Value |',
50
+ '|---|---|',
51
+ '| Type | `unknown` |',
52
+ '| Confidence | `low` |',
53
+ '',
54
+ '## Project mode',
55
+ '',
56
+ '| Field | Value |',
57
+ '|---|---|',
58
+ '| Integration mode | unknown |',
59
+ '| Integration mode reason | 0-1 bootstrap — refresh after the first source file lands |',
60
+ '| Frontend-only | `false` |',
61
+ '| Reason | 0-1 project, no package.json or source files |',
62
+ '',
63
+ '## Tech stack',
64
+ '',
65
+ '| Concern | Value |',
66
+ '|---|---|',
67
+ '| Language | (empty) |',
68
+ '| Package manager | (empty) |',
69
+ '| Node runtime | (empty) |',
70
+ '| Build | (empty) |',
71
+ '',
72
+ '## Library versions',
73
+ '',
74
+ '| Package | Pinned range | Major | Scope | Ecosystem |',
75
+ '|---|---|---|---|---|',
76
+ '| (empty) | — | — | — | — |',
77
+ '',
78
+ '## Architecture',
79
+ '',
80
+ '_No architecture recorded yet — refresh with `peaks project context --project <repo>` once the project has source files._',
81
+ '',
82
+ '## Karpathy self-check',
83
+ '',
84
+ '| Guideline | Where enforced |',
85
+ '|---|---|',
86
+ '| §1 Think Before Coding | (empty) |',
87
+ '| §2 Simplicity First | (empty) |',
88
+ '| §3 Surgical Changes | (empty) |',
89
+ '| §4 Goal-Driven Execution | (empty) |',
90
+ '',
91
+ '## Refresh procedure',
92
+ '',
93
+ '1. Add a `package.json` (with `pnpm init` or equivalent).',
94
+ '2. Add at least one TypeScript/JavaScript/Vue/Svelte source file under `src/`.',
95
+ '3. Re-run `peaks project context --project <repo>` — the empty placeholders are replaced with real archetype + libraryVersions.'
96
+ ];
97
+ /** Render a LibraryReport as a markdown table body (header row included). */
98
+ function renderLibraryTable(libraryReport) {
99
+ const header = '| Package | Pinned range | Major | Scope | Ecosystem |';
100
+ const sep = '|---|---|---|---|---|';
101
+ if (libraryReport.libraries.length === 0) {
102
+ return [header, sep, '| (empty) | — | — | — | — |'].join('\n');
103
+ }
104
+ const rows = libraryReport.libraries.map((entry) => {
105
+ const major = entry.major === null ? '—' : String(entry.major);
106
+ return `| \`${entry.name}\` | \`${entry.version}\` | ${major} | ${entry.scope} | ${entry.ecosystem} |`;
107
+ });
108
+ return [header, sep, ...rows].join('\n');
109
+ }
110
+ /** Build the project-scan.md content for an existing project. */
111
+ export function buildExistingProjectScan(args) {
112
+ const { archetypeReport, libraryReport, techStack } = args;
113
+ const now = new Date().toISOString();
114
+ // Library versions snapshot: a flat {name: version} map. Mirrors the shape
115
+ // consumed by `services/prd/project-scan-types.ts`
116
+ // `ProjectScanLibraryVersions`.
117
+ const libraryVersionsMap = {};
118
+ for (const entry of libraryReport.libraries) {
119
+ libraryVersionsMap[entry.name] = entry.version;
120
+ }
121
+ return [
122
+ ...existingFrontmatter({ now, archetypeReport, techStack, libraryVersionsMap }),
123
+ '',
124
+ `# Project Scan (refreshed ${now})`,
125
+ '',
126
+ '> Auto-generated by `peaks workspace init` / `peaks project context`.',
127
+ '',
128
+ ...archetypeSections(archetypeReport),
129
+ ...techStackSection(techStack),
130
+ '## Library versions',
131
+ '',
132
+ renderLibraryTable(libraryReport),
133
+ '',
134
+ '## Architecture',
135
+ '',
136
+ `_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._`,
137
+ '',
138
+ '## Karpathy self-check',
139
+ '',
140
+ '| Guideline | Where enforced |',
141
+ '|---|---|',
142
+ '| §1 Think Before Coding | (refresh with LLM review) |',
143
+ '| §2 Simplicity First | (refresh with LLM review) |',
144
+ '| §3 Surgical Changes | (refresh with LLM review) |',
145
+ '| §4 Goal-Driven Execution | (refresh with LLM review) |',
146
+ '',
147
+ '## Refresh procedure',
148
+ '',
149
+ '1. Re-run `peaks scan archetype --project <repo> --json` and `peaks scan libraries --project <repo> --json` after any dependency / archetype change.',
150
+ '2. Re-run `peaks project context --project <repo>` to refresh this file. Its frontmatter is refreshed in place; the prose below it is yours.',
151
+ '3. Commit the regenerated project-scan.md alongside the dependency bump.',
152
+ ''
153
+ ].join('\n');
154
+ }
155
+ function existingFrontmatter(args) {
156
+ return [
157
+ '---',
158
+ 'schemaVersion: 1',
159
+ `capturedAt: ${args.now}`,
160
+ `archetype: ${args.archetypeReport.archetype}`,
161
+ `confidence: ${args.archetypeReport.confidence}`,
162
+ renderFrontmatterField('techStack', args.techStack),
163
+ renderFrontmatterField('libraryVersions', args.libraryVersionsMap),
164
+ 'architecture: ""',
165
+ 'karpathySelfCheck: {}',
166
+ '---'
167
+ ];
168
+ }
169
+ /** The `## Archetype` and `## Project mode` tables, from the archetype report. */
170
+ function archetypeSections(report) {
171
+ return [
172
+ '## Archetype',
173
+ '',
174
+ '| Field | Value |',
175
+ '|---|---|',
176
+ `| Type | \`${report.archetype}\` |`,
177
+ `| Confidence | \`${report.confidence}\` |`,
178
+ '',
179
+ '## Project mode',
180
+ '',
181
+ '| Field | Value |',
182
+ '|---|---|',
183
+ `| Integration mode | ${report.integrationMode} |`,
184
+ `| Integration mode reason | ${report.integrationModeReason} |`,
185
+ `| Frontend-only | \`${String(report.frontendOnly)}\` |`,
186
+ `| Reason | ${report.frontendOnlyReason} |`,
187
+ ''
188
+ ];
189
+ }
190
+ /**
191
+ * The `## Tech stack` table. Every value here is machine-derived, so the table
192
+ * is a projection of the `techStack` frontmatter — a refresh rewrites that
193
+ * frontmatter and leaves this table to the create path.
194
+ */
195
+ function techStackSection(techStack) {
196
+ return [
197
+ '## Tech stack',
198
+ '',
199
+ '| Concern | Value |',
200
+ '|---|---|',
201
+ `| Language | ${techStack['language'] ?? '(unknown)'} |`,
202
+ `| Package manager | ${techStack['packageManager'] ?? '(unknown)'} |`,
203
+ `| Node runtime | ${techStack['runtime'] ?? '(unknown)'} |`,
204
+ `| Build | ${techStack['buildTool'] ?? '(no package.json build script)'} |`,
205
+ ''
206
+ ];
207
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Reading an existing scan's machine fields back out, and deciding whether it is
3
+ * a shell.
4
+ *
5
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
6
+ * 300-line cap. The distinction this module owns is the one the refresh turns on:
7
+ * a file that was never populated is a SHELL and may be rewritten without asking;
8
+ * a file with either field populated is SEDIMENT and may not.
9
+ */
10
+ /**
11
+ * The on-disk `techStack` map, as string rows. Anything that is not a plain
12
+ * object of scalars is treated as empty, so a malformed value cannot leak into
13
+ * the merge and be written back as a nested blob.
14
+ */
15
+ export declare function readTechStack(content: string): Record<string, string>;
16
+ /**
17
+ * True when the file was never meaningfully populated: empty `architecture` AND
18
+ * an empty `techStack`. Such a file is a shell, not sediment — the installed
19
+ * base of consumer projects holds them, so it is upgraded without any gesture.
20
+ * A file with EITHER field populated is sediment and refreshes only on request.
21
+ */
22
+ export declare function isUnpopulatedProjectScan(content: string): boolean;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Reading an existing scan's machine fields back out, and deciding whether it is
3
+ * a shell.
4
+ *
5
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
6
+ * 300-line cap. The distinction this module owns is the one the refresh turns on:
7
+ * a file that was never populated is a SHELL and may be rewritten without asking;
8
+ * a file with either field populated is SEDIMENT and may not.
9
+ */
10
+ import { isMap, parseDocument } from 'yaml';
11
+ import { frontmatterOf } from './project-scan-frontmatter.js';
12
+ function isEmptyMap(value) {
13
+ if (value === null || value === undefined)
14
+ return true;
15
+ if (typeof value !== 'object' || Array.isArray(value))
16
+ return false;
17
+ return Object.keys(value).length === 0;
18
+ }
19
+ /**
20
+ * The on-disk `techStack` map, as string rows. Anything that is not a plain
21
+ * object of scalars is treated as empty, so a malformed value cannot leak into
22
+ * the merge and be written back as a nested blob.
23
+ */
24
+ export function readTechStack(content) {
25
+ const frontmatter = frontmatterOf(content);
26
+ if (frontmatter === null)
27
+ return {};
28
+ const doc = parseDocument(frontmatter);
29
+ if (doc.errors.length > 0 || !isMap(doc.contents))
30
+ return {};
31
+ const parsed = doc.toJS();
32
+ const techStack = parsed?.['techStack'];
33
+ if (techStack === null || typeof techStack !== 'object' || Array.isArray(techStack))
34
+ return {};
35
+ const rows = {};
36
+ for (const [key, value] of Object.entries(techStack)) {
37
+ if (typeof value === 'string')
38
+ rows[key] = value;
39
+ }
40
+ return rows;
41
+ }
42
+ /**
43
+ * True when the file was never meaningfully populated: empty `architecture` AND
44
+ * an empty `techStack`. Such a file is a shell, not sediment — the installed
45
+ * base of consumer projects holds them, so it is upgraded without any gesture.
46
+ * A file with EITHER field populated is sediment and refreshes only on request.
47
+ */
48
+ export function isUnpopulatedProjectScan(content) {
49
+ const frontmatter = frontmatterOf(content);
50
+ if (frontmatter === null)
51
+ return false;
52
+ const doc = parseDocument(frontmatter);
53
+ if (doc.errors.length > 0 || !isMap(doc.contents))
54
+ return false;
55
+ const fields = doc.toJS();
56
+ if (fields === null)
57
+ return false;
58
+ const architecture = fields['architecture'];
59
+ const architectureEmpty = typeof architecture !== 'string' || architecture.trim() === '';
60
+ return architectureEmpty && isEmptyMap(fields['techStack']);
61
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Machine-field refresh for `.peaks/project-scan/project-scan.md`.
3
+ *
4
+ * WHY THIS MODULE EXISTS. The bootstrap wrote the file once and skipped it
5
+ * forever after (`schemaVersion: 1` on disk => `skipped: true`), so
6
+ * `libraryVersions` froze at the versions present on install day. The file is a
7
+ * CONSUMER CONTRACT — peaks-rd reads `## Library versions` and cross-checks it
8
+ * against `schemas/library-breaking-changes.data.json`, and the file is
9
+ * declared as Gate C evidence — so a frozen map makes that breaking-change gate
10
+ * pass on stale input.
11
+ *
12
+ * WHAT A REFRESH MAY TOUCH. Exactly three frontmatter fields: `capturedAt`,
13
+ * `techStack`, `libraryVersions`. Everything else — `architecture`,
14
+ * `karpathySelfCheck`, key order, comments, and the whole markdown body — is
15
+ * hand-authored sediment and is preserved. That is why this is a TEXT SURGERY
16
+ * over the existing frontmatter and not a re-serialisation: the file's owner
17
+ * wrote prose (a vitest pin note, a c8 removal note, a workspace-package table)
18
+ * that a regeneration would destroy.
19
+ *
20
+ * The surgery replaces each managed `key: value` SOURCE SPAN, read from the yaml
21
+ * AST. The span ENDS AT THE VALUE (`pair.value.range[1]`), not at the line break
22
+ * — a trailing `# note` and the line ending are copied through untouched. A
23
+ * trailing line break the old span consumed is re-emitted, so the file's own line
24
+ * structure survives. Nothing outside those spans is rewritten.
25
+ *
26
+ * One thing a refresh does NOT do: it never writes markdown prose. The
27
+ * `## Tech stack` and `## Library versions` TABLES in the body are the create
28
+ * path's projection and go stale relative to the frontmatter above them. The
29
+ * frontmatter is the machine-read copy; the tables are human-facing and are left
30
+ * exactly as their author left them.
31
+ */
32
+ export type MachineFields = {
33
+ readonly capturedAt: string;
34
+ readonly techStack: Readonly<Record<string, string>>;
35
+ readonly libraryVersions: Readonly<Record<string, string>>;
36
+ };
37
+ export type RefreshResult = {
38
+ readonly ok: true;
39
+ readonly content: string;
40
+ } | {
41
+ readonly ok: false;
42
+ readonly reason: 'frontmatter-unparseable';
43
+ };
44
+ /** What the on-disk refresh decided, in the words the envelope uses. */
45
+ export type RefreshOutcome = {
46
+ readonly skipped: boolean;
47
+ readonly refreshed: boolean;
48
+ readonly warning?: string;
49
+ };
50
+ /**
51
+ * A complete `key: value` field, in the form the frontmatter uses: a scalar or
52
+ * an empty map stays inline (`key: value`, `key: {}`), a populated map goes to
53
+ * BLOCK form (`key:\n nested: value`). A populated map cannot be written
54
+ * inline here without the `{` the old create path hard-coded, and
55
+ * `key: a: b` is not YAML at all — which is why this is one function rather
56
+ * than a string template at each call site.
57
+ */
58
+ export declare function renderFrontmatterField(key: string, value: string | Readonly<Record<string, string>>): string;
59
+ /**
60
+ * Rewrite the three managed frontmatter fields of `content`, preserving every
61
+ * other byte. Returns `ok: false` when the frontmatter cannot be parsed — the
62
+ * caller then leaves the file untouched, because a file this function cannot
63
+ * read is one whose prose must not be risked.
64
+ */
65
+ export declare function refreshProjectScanFields(content: string, fields: MachineFields): RefreshResult;
66
+ /**
67
+ * Refresh an existing `project-scan.md` in place — or report why it was not
68
+ * touched. `requested` is the caller's explicit ask.
69
+ *
70
+ * `zeroToOne` no longer short-circuits the whole call. A project that was 0-1 on
71
+ * install day holds the placeholder, and when it later gains a manifest + source
72
+ * files the placeholder is STALE, not truthful — skipping here left it holding
73
+ * `architecture: ""` forever, because no later run would ever enter this branch
74
+ * again. What `zeroToOne` still suppresses is the meaningless work: there is no
75
+ * stack to derive while the project has no manifest or no source files, so the
76
+ * refresh declines without scanning. An UNPOPULATED shell is never suppressed by
77
+ * it — that is the file the transition needs filled.
78
+ *
79
+ * The file is written only when its content actually changed, so a repeated run
80
+ * on an unchanged project leaves the mtime alone.
81
+ */
82
+ export declare function refreshProjectScanOnDisk(args: {
83
+ readonly absolutePath: string;
84
+ readonly projectRoot: string;
85
+ readonly zeroToOne: boolean;
86
+ readonly requested: boolean;
87
+ }): Promise<RefreshOutcome>;
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Machine-field refresh for `.peaks/project-scan/project-scan.md`.
3
+ *
4
+ * WHY THIS MODULE EXISTS. The bootstrap wrote the file once and skipped it
5
+ * forever after (`schemaVersion: 1` on disk => `skipped: true`), so
6
+ * `libraryVersions` froze at the versions present on install day. The file is a
7
+ * CONSUMER CONTRACT — peaks-rd reads `## Library versions` and cross-checks it
8
+ * against `schemas/library-breaking-changes.data.json`, and the file is
9
+ * declared as Gate C evidence — so a frozen map makes that breaking-change gate
10
+ * pass on stale input.
11
+ *
12
+ * WHAT A REFRESH MAY TOUCH. Exactly three frontmatter fields: `capturedAt`,
13
+ * `techStack`, `libraryVersions`. Everything else — `architecture`,
14
+ * `karpathySelfCheck`, key order, comments, and the whole markdown body — is
15
+ * hand-authored sediment and is preserved. That is why this is a TEXT SURGERY
16
+ * over the existing frontmatter and not a re-serialisation: the file's owner
17
+ * wrote prose (a vitest pin note, a c8 removal note, a workspace-package table)
18
+ * that a regeneration would destroy.
19
+ *
20
+ * The surgery replaces each managed `key: value` SOURCE SPAN, read from the yaml
21
+ * AST. The span ENDS AT THE VALUE (`pair.value.range[1]`), not at the line break
22
+ * — a trailing `# note` and the line ending are copied through untouched. A
23
+ * trailing line break the old span consumed is re-emitted, so the file's own line
24
+ * structure survives. Nothing outside those spans is rewritten.
25
+ *
26
+ * One thing a refresh does NOT do: it never writes markdown prose. The
27
+ * `## Tech stack` and `## Library versions` TABLES in the body are the create
28
+ * path's projection and go stale relative to the frontmatter above them. The
29
+ * frontmatter is the machine-read copy; the tables are human-facing and are left
30
+ * exactly as their author left them.
31
+ */
32
+ import { readFileSync, writeFileSync } from 'node:fs';
33
+ import { isMap, isNode, isPair, isScalar, parseDocument, stringify } from 'yaml';
34
+ import { scanLibraries } from '../scan/libraries-service.js';
35
+ import { refreshLibraryVersionsTable, refreshTechStackTable } from './project-scan-body-tables.js';
36
+ import { isUnpopulatedProjectScan, readTechStack } from './project-scan-existing-state.js';
37
+ import { splitFrontmatter } from './project-scan-frontmatter.js';
38
+ import { libraryVersionsFor } from './project-scan-library-versions.js';
39
+ import { deriveTechStack, mergeTechStack } from './project-scan-techstack.js';
40
+ /** The three frontmatter fields a refresh is allowed to rewrite, in file order. */
41
+ const MANAGED_KEYS = ['capturedAt', 'techStack', 'libraryVersions'];
42
+ /** One YAML nesting level, as the block-form renderer indents it. */
43
+ const INDENT = ' ';
44
+ /** A scalar as it must appear after `key: `. */
45
+ function renderFrontmatterScalar(value) {
46
+ return stringify(value).trimEnd();
47
+ }
48
+ /**
49
+ * A complete `key: value` field, in the form the frontmatter uses: a scalar or
50
+ * an empty map stays inline (`key: value`, `key: {}`), a populated map goes to
51
+ * BLOCK form (`key:\n nested: value`). A populated map cannot be written
52
+ * inline here without the `{` the old create path hard-coded, and
53
+ * `key: a: b` is not YAML at all — which is why this is one function rather
54
+ * than a string template at each call site.
55
+ */
56
+ export function renderFrontmatterField(key, value) {
57
+ if (typeof value === 'string')
58
+ return `${key}: ${renderFrontmatterScalar(value)}`;
59
+ const entries = Object.entries(value);
60
+ if (entries.length === 0)
61
+ return `${key}: {}`;
62
+ const block = stringify(value, { lineWidth: 0 })
63
+ .trimEnd()
64
+ .split('\n')
65
+ .map((line) => `${INDENT}${line}`)
66
+ .join('\n');
67
+ return `${key}:\n${block}`;
68
+ }
69
+ function renderManagedField(key, fields) {
70
+ switch (key) {
71
+ case 'capturedAt':
72
+ return renderFrontmatterField(key, fields.capturedAt);
73
+ case 'techStack':
74
+ return renderFrontmatterField(key, fields.techStack);
75
+ case 'libraryVersions':
76
+ return renderFrontmatterField(key, fields.libraryVersions);
77
+ }
78
+ }
79
+ /**
80
+ * The one edit that rewrites `key`, or `null` when the key is absent from the
81
+ * frontmatter (the caller then appends it). A key that is present but has no
82
+ * usable source range is reported as `broken`, never guessed at.
83
+ */
84
+ function editFor(doc, key, fields, frontmatter) {
85
+ const pair = doc.items.find((item) => isPair(item) && isScalar(item.key) && item.key.value === key);
86
+ if (!isPair(pair) || !isScalar(pair.key))
87
+ return { absent: true };
88
+ const start = pair.key.range?.[0];
89
+ // `range[1]` is the VALUE end; `range[2]` also swallows a trailing comment
90
+ // (`key: value # note`) and the line break. Ending at the value leaves both
91
+ // in place, so a note a human attached to a managed field survives.
92
+ const end = isNode(pair.value) ? pair.value.range?.[1] : undefined;
93
+ if (start === undefined || end === undefined)
94
+ return { broken: true };
95
+ const keepsBreak = frontmatter[end - 1] === '\n';
96
+ const text = renderManagedField(key, fields);
97
+ return { edit: { start, end, text: keepsBreak ? `${text}\n` : text } };
98
+ }
99
+ /**
100
+ * Rewrite the three managed frontmatter fields of `content`, preserving every
101
+ * other byte. Returns `ok: false` when the frontmatter cannot be parsed — the
102
+ * caller then leaves the file untouched, because a file this function cannot
103
+ * read is one whose prose must not be risked.
104
+ */
105
+ export function refreshProjectScanFields(content, fields) {
106
+ const split = splitFrontmatter(content);
107
+ if (split === null)
108
+ return { ok: false, reason: 'frontmatter-unparseable' };
109
+ const { frontmatter } = split;
110
+ const doc = parseDocument(frontmatter);
111
+ if (doc.errors.length > 0 || !isMap(doc.contents)) {
112
+ return { ok: false, reason: 'frontmatter-unparseable' };
113
+ }
114
+ const edits = [];
115
+ const appended = [];
116
+ for (const key of MANAGED_KEYS) {
117
+ const result = editFor(doc.contents, key, fields, frontmatter);
118
+ if ('broken' in result)
119
+ return { ok: false, reason: 'frontmatter-unparseable' };
120
+ if ('absent' in result)
121
+ appended.push(renderManagedField(key, fields));
122
+ else
123
+ edits.push(result.edit);
124
+ }
125
+ // Descending start order, so an earlier replacement cannot shift a later one.
126
+ const updated = [...edits]
127
+ .sort((a, b) => b.start - a.start)
128
+ .reduce((text, edit) => text.slice(0, edit.start) + edit.text + text.slice(edit.end), frontmatter);
129
+ const withAppended = appended.length === 0 ? updated : `${updated}\n${appended.join('\n')}`;
130
+ const emitted = split.crlf ? withAppended.replace(/\n/g, '\r\n') : withAppended;
131
+ const fenceBreak = split.crlf ? '\r\n' : '\n';
132
+ return {
133
+ ok: true,
134
+ content: `---${fenceBreak}${emitted}${fenceBreak}---${content.slice(split.bodyStart)}`
135
+ };
136
+ }
137
+ /**
138
+ * Read the file. An IO failure is reported, never thrown and never swallowed.
139
+ *
140
+ * WHY NOT THROW. This runs on the DEFAULT path of `peaks project context`, which
141
+ * is an everyday command: a locked or permission-denied file would turn a
142
+ * refresh nobody asked for into a failed command with exit 1. It must not vanish
143
+ * either — a read that failed is not "nothing to refresh" — so the failure comes
144
+ * back as a `warning` the caller puts in its envelope.
145
+ */
146
+ function readExisting(absPath) {
147
+ try {
148
+ return { ok: true, existing: readFileSync(absPath, 'utf8') };
149
+ }
150
+ catch (error) {
151
+ return {
152
+ ok: false,
153
+ warning: `project-scan.md could not be read (${error.message}), so its machine ` +
154
+ 'fields were left unrefreshed — the rest of the file was not touched.'
155
+ };
156
+ }
157
+ }
158
+ /**
159
+ * Refresh an existing `project-scan.md` in place — or report why it was not
160
+ * touched. `requested` is the caller's explicit ask.
161
+ *
162
+ * `zeroToOne` no longer short-circuits the whole call. A project that was 0-1 on
163
+ * install day holds the placeholder, and when it later gains a manifest + source
164
+ * files the placeholder is STALE, not truthful — skipping here left it holding
165
+ * `architecture: ""` forever, because no later run would ever enter this branch
166
+ * again. What `zeroToOne` still suppresses is the meaningless work: there is no
167
+ * stack to derive while the project has no manifest or no source files, so the
168
+ * refresh declines without scanning. An UNPOPULATED shell is never suppressed by
169
+ * it — that is the file the transition needs filled.
170
+ *
171
+ * The file is written only when its content actually changed, so a repeated run
172
+ * on an unchanged project leaves the mtime alone.
173
+ */
174
+ export async function refreshProjectScanOnDisk(args) {
175
+ const read = readExisting(args.absolutePath);
176
+ if (!read.ok) {
177
+ return { skipped: true, refreshed: false, warning: read.warning };
178
+ }
179
+ const { existing } = read;
180
+ // A still-0-1 project's placeholder is truthful, not stale, so it is left alone.
181
+ // `zeroToOne` is recomputed from the CURRENT tree on every call, so a project
182
+ // that later gains a manifest and source files arrives here with `false` and is
183
+ // refreshed normally — the placeholder does not survive the transition.
184
+ //
185
+ // What a refresh does NOT do is fill `architecture`: that field is prose, and
186
+ // the shell's `""` stays empty until someone writes it. The three machine
187
+ // fields this module owns are filled on the first post-transition run.
188
+ if (args.zeroToOne)
189
+ return { skipped: true, refreshed: false };
190
+ // No explicit ask (`peaks workspace init`'s path): a populated scan is
191
+ // sediment and is left alone. An UNPOPULATED shell is the exception — it holds
192
+ // no prose worth protecting, so the installed base of such files is repaired
193
+ // without anyone having to ask.
194
+ if (!args.requested && !isUnpopulatedProjectScan(existing)) {
195
+ return { skipped: true, refreshed: false };
196
+ }
197
+ const scanned = (await scanLibraries({ projectRoot: args.projectRoot })).libraries;
198
+ const techStack = mergeTechStack(readTechStack(existing), deriveTechStack(args.projectRoot));
199
+ const libraryVersions = libraryVersionsFor(args.projectRoot, scanned);
200
+ const result = refreshProjectScanFields(existing, {
201
+ capturedAt: new Date().toISOString(),
202
+ techStack,
203
+ libraryVersions
204
+ });
205
+ if (!result.ok) {
206
+ return {
207
+ skipped: true,
208
+ refreshed: false,
209
+ warning: 'project-scan.md frontmatter could not be parsed, so its machine fields were left ' +
210
+ 'unrefreshed — the rest of the file was not touched.'
211
+ };
212
+ }
213
+ const withTables = refreshTechStackTable(refreshLibraryVersionsTable(result.content, libraryVersions), techStack);
214
+ if (withTables !== existing)
215
+ writeFileSync(args.absolutePath, withTables, 'utf8');
216
+ return { skipped: false, refreshed: true };
217
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Reading the frontmatter block out of a `.peaks/project-scan/project-scan.md`.
3
+ *
4
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
5
+ * 300-line cap, and because the CRLF problem is its own subject: every caller
6
+ * that wants the frontmatter needs the same two facts (the block, and where the
7
+ * body begins), and getting them wrong on a Windows checkout is what re-freezes
8
+ * the scan.
9
+ */
10
+ /** The leading frontmatter split apart, with the offsets the writer needs. */
11
+ export type FrontmatterSplit = {
12
+ /** The block between the fences, line endings normalised to `\n`. */
13
+ readonly frontmatter: string;
14
+ /** Offset in the ORIGINAL text at which the markdown body starts. */
15
+ readonly bodyStart: number;
16
+ /** True when the file's fences are `---\r\n` (a Windows checkout). */
17
+ readonly crlf: boolean;
18
+ };
19
+ /**
20
+ * Split the leading `---` block.
21
+ *
22
+ * CRLF-TOLERANT ON PURPOSE. `core.autocrlf=true` is the default on Windows, so a
23
+ * checkout can hand this module a file whose fences are `---\r\n`. A pattern
24
+ * anchored on `\n` alone finds no frontmatter there and the refresh refuses —
25
+ * reviving the exact freeze the refresh exists to end, on the platform most of
26
+ * its users run. The block is returned with `\n` endings so the yaml AST offsets
27
+ * and the span arithmetic agree; `crlf` records what the file actually uses, so
28
+ * the writer can put it back.
29
+ */
30
+ export declare function splitFrontmatter(content: string): FrontmatterSplit | null;
31
+ /** The frontmatter block alone, or `null`. */
32
+ export declare function frontmatterOf(content: string): string | null;