peaks-loop 4.1.26 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +160 -0
  3. package/contracts/readonly-argv-whitelist.json +116 -0
  4. package/dist/cli/commands/code-auto-compact-command.js +15 -3
  5. package/dist/cli/commands/core/session-info-command.js +3 -4
  6. package/dist/cli/commands/core/skill-presence-housekeeping-commands.js +7 -1
  7. package/dist/cli/commands/dashboard-long-run.js +2 -1
  8. package/dist/cli/commands/doctor/invoke-from-code.js +6 -1
  9. package/dist/cli/commands/job-state-root.js +4 -2
  10. package/dist/cli/commands/lease-metrics-commands-support.js +2 -1
  11. package/dist/cli/commands/loop-eval-capture-index.js +2 -1
  12. package/dist/cli/commands/loop-eval-eval-command.js +2 -1
  13. package/dist/cli/commands/mut-commands-helpers.d.ts +9 -28
  14. package/dist/cli/commands/mut-commands-helpers.js +53 -80
  15. package/dist/cli/commands/mut-failure-diagnostic.d.ts +48 -0
  16. package/dist/cli/commands/mut-failure-diagnostic.js +147 -0
  17. package/dist/cli/commands/outer-cache-commands.js +3 -2
  18. package/dist/cli/commands/playwright-session-store.js +5 -2
  19. package/dist/cli/commands/project-context-command.js +7 -2
  20. package/dist/cli/commands/qa-archive-screenshots-command.js +2 -1
  21. package/dist/cli/commands/request-transition-preflight.js +2 -2
  22. package/dist/cli/commands/slice-decompose-artifacts.js +10 -2
  23. package/dist/cli/commands/verdict-aggregate-command.js +4 -3
  24. package/dist/cli/commands/workspace/init-actions.js +5 -0
  25. package/dist/cli/commands/workspace/init-context.js +1 -0
  26. package/dist/cli/commands/worktree-lease-effects.d.ts +13 -0
  27. package/dist/cli/commands/worktree-lease-effects.js +23 -0
  28. package/dist/cli/commands/worktree-lease-gc-command.d.ts +3 -4
  29. package/dist/cli/commands/worktree-lease-gc-command.js +59 -58
  30. package/dist/cli/commands/worktree-lease-git.d.ts +13 -18
  31. package/dist/cli/commands/worktree-lease-git.js +21 -44
  32. package/dist/cli/commands/worktree-lease-list-command.js +1 -1
  33. package/dist/cli/commands/worktree-lease-load.d.ts +19 -7
  34. package/dist/cli/commands/worktree-lease-load.js +37 -9
  35. package/dist/cli/commands/worktree-lease-release-command.d.ts +4 -5
  36. package/dist/cli/commands/worktree-lease-release-command.js +60 -47
  37. package/dist/cli/commands/worktree-lease-renew-command.d.ts +5 -4
  38. package/dist/cli/commands/worktree-lease-renew-command.js +36 -32
  39. package/dist/cli/commands/worktree-lease-session.d.ts +7 -5
  40. package/dist/cli/commands/worktree-lease-session.js +9 -6
  41. package/dist/cli/commands/worktree-lease-spawn-command.d.ts +4 -3
  42. package/dist/cli/commands/worktree-lease-spawn-command.js +38 -46
  43. package/dist/cli/commands/worktree-lease-status-command.js +1 -1
  44. package/dist/cli/commands/worktree-lease-store.d.ts +3 -2
  45. package/dist/cli/commands/worktree-lease-store.js +3 -2
  46. package/dist/services/artifacts/prerequisite-path-resolver.js +5 -1
  47. package/dist/services/audit/enforcers/lint-output-style.js +5 -1
  48. package/dist/services/audit/enforcers/lint-rd-handoff-coverage.js +9 -4
  49. package/dist/services/audit-independent/handoff-missing-refusal.js +16 -1
  50. package/dist/services/audit-independent/judged-declaration-check.js +5 -1
  51. package/dist/services/audit-independent/perf-audit-service.d.ts +2 -4
  52. package/dist/services/audit-independent/perf-audit-service.js +4 -5
  53. package/dist/services/audit-independent/security-audit-artifact.js +5 -1
  54. package/dist/services/capability-audit-service/runner.js +4 -1
  55. package/dist/services/capability-baseline/store.js +2 -1
  56. package/dist/services/capability-guard-runner/contracts/J05.js +4 -2
  57. package/dist/services/capability-guard-runner/contracts/J12.js +2 -2
  58. package/dist/services/code/auto-compact-artifacts.js +42 -10
  59. package/dist/services/code/auto-compact-checkpoint-content.d.ts +49 -0
  60. package/dist/services/code/auto-compact-checkpoint-content.js +157 -0
  61. package/dist/services/code/auto-compact-envelopes.d.ts +11 -2
  62. package/dist/services/code/auto-compact-envelopes.js +18 -4
  63. package/dist/services/code/auto-compact-orchestrator.js +1 -1
  64. package/dist/services/code/emit-handoff.js +8 -1
  65. package/dist/services/code/job-shape-decision.js +13 -2
  66. package/dist/services/code/job-shape-provisional.js +9 -1
  67. package/dist/services/code/post-compact-detector.js +9 -1
  68. package/dist/services/code/step-08-session-readers.js +14 -5
  69. package/dist/services/compact/request-transition-hook.js +6 -1
  70. package/dist/services/compact/suggest-service.js +8 -1
  71. package/dist/services/context/post-compact-reinjection.js +15 -14
  72. package/dist/services/context/spillover-store.js +2 -1
  73. package/dist/services/dispatch/contract-store.d.ts +11 -4
  74. package/dist/services/dispatch/contract-store.js +21 -8
  75. package/dist/services/doctor/doctor-service/checks/workspace-layout.js +8 -3
  76. package/dist/services/doctor/doctor-service/index.js +2 -1
  77. package/dist/services/final-review/final-review-evidence-collect.js +5 -1
  78. package/dist/services/fresh-context/fresh-context-block.js +5 -1
  79. package/dist/services/hooks/auto-compact-hook-install.d.ts +13 -3
  80. package/dist/services/hooks/auto-compact-hook-install.js +13 -3
  81. package/dist/services/hooks/worktree-authorization-gate.d.ts +1 -1
  82. package/dist/services/hooks/worktree-authorization-gate.js +14 -11
  83. package/dist/services/loop/evaluator-dispatcher.js +7 -7
  84. package/dist/services/loop/monotonic-runner.js +2 -1
  85. package/dist/services/loop/spec-service.js +10 -9
  86. package/dist/services/mcp/context-tool.d.ts +3 -0
  87. package/dist/services/mcp/context-tool.js +135 -0
  88. package/dist/services/mcp/surface.js +7 -1
  89. package/dist/services/mcp/tools.js +3 -1
  90. package/dist/services/memory/project-context-service.d.ts +10 -1
  91. package/dist/services/memory/project-context-service.js +13 -6
  92. package/dist/services/observability/jsonl-store.js +4 -1
  93. package/dist/services/polyrepo/polyrepo-dispatcher.js +5 -1
  94. package/dist/services/prd/prd-blocks-checker.js +12 -6
  95. package/dist/services/prd/project-scan-body-tables.d.ts +33 -0
  96. package/dist/services/prd/project-scan-body-tables.js +185 -0
  97. package/dist/services/prd/project-scan-bootstrap-service.d.ts +16 -3
  98. package/dist/services/prd/project-scan-bootstrap-service.js +127 -231
  99. package/dist/services/prd/project-scan-content.d.ts +24 -0
  100. package/dist/services/prd/project-scan-content.js +207 -0
  101. package/dist/services/prd/project-scan-existing-state.d.ts +22 -0
  102. package/dist/services/prd/project-scan-existing-state.js +61 -0
  103. package/dist/services/prd/project-scan-field-refresh.d.ts +87 -0
  104. package/dist/services/prd/project-scan-field-refresh.js +217 -0
  105. package/dist/services/prd/project-scan-frontmatter.d.ts +32 -0
  106. package/dist/services/prd/project-scan-frontmatter.js +34 -0
  107. package/dist/services/prd/project-scan-library-versions.d.ts +60 -0
  108. package/dist/services/prd/project-scan-library-versions.js +135 -0
  109. package/dist/services/prd/project-scan-techstack.d.ts +34 -0
  110. package/dist/services/prd/project-scan-techstack.js +167 -0
  111. package/dist/services/reviewer/reviewer-artifacts.js +2 -1
  112. package/dist/services/sc/sc-service.js +8 -8
  113. package/dist/services/scan/api-diff-recorded.d.ts +2 -3
  114. package/dist/services/scan/api-diff-recorded.js +5 -5
  115. package/dist/services/session/binding-status-service.js +2 -1
  116. package/dist/services/session/binding-store.js +6 -7
  117. package/dist/services/session/caller-binding-service.js +5 -2
  118. package/dist/services/session/getSessionDir.d.ts +4 -0
  119. package/dist/services/session/getSessionDir.js +38 -13
  120. package/dist/services/session/session-binding-bridge.d.ts +3 -6
  121. package/dist/services/session/session-binding-bridge.js +13 -13
  122. package/dist/services/session/session-checkpoint-service.js +22 -3
  123. package/dist/services/session/session-manager.js +16 -20
  124. package/dist/services/skills/presence-lease-resolver.js +3 -2
  125. package/dist/services/skills/presence-lease-service.js +7 -15
  126. package/dist/services/skills/presence-lease-store.d.ts +26 -0
  127. package/dist/services/skills/presence-lease-store.js +60 -5
  128. package/dist/services/skills/skill-presence-service.js +13 -20
  129. package/dist/services/skills/skill-statusline-model.js +7 -2
  130. package/dist/services/slice/slice-archive-service.js +4 -1
  131. package/dist/services/standards/missing-standards-detector.js +2 -1
  132. package/dist/services/test-cache/test-cache-service.js +2 -1
  133. package/dist/services/workflow/artifact-paths.js +6 -2
  134. package/dist/services/workflow/pipeline-verify-gate-support.d.ts +1 -1
  135. package/dist/services/workflow/pipeline-verify-gate-support.js +23 -11
  136. package/dist/services/workflow/workflow-graph-store-helpers.js +12 -3
  137. package/dist/services/workflow/workflow-state-store.js +11 -4
  138. package/dist/services/workspace/migrate-1-4-1-service.js +2 -1
  139. package/dist/services/workspace/reconcile-migrate.js +2 -2
  140. package/dist/services/workspace/reconcile-service.d.ts +4 -6
  141. package/dist/services/workspace/reconcile-service.js +11 -11
  142. package/dist/services/workspace/workspace-service.js +5 -5
  143. package/dist/services/worktree/dispatch-provenance.d.ts +1 -1
  144. package/dist/services/worktree/dispatch-provenance.js +9 -2
  145. package/dist/services/worktree/host-worktree-reconciler.d.ts +1 -1
  146. package/dist/services/worktree/host-worktree-reconciler.js +5 -3
  147. package/dist/shared/runtime-root.js +6 -1
  148. package/package.json +6 -5
  149. package/skills/peaks-code/SKILL.md +1 -1
  150. package/skills/peaks-code/references/project-scan-checklist.md +3 -1
  151. package/skills/peaks-mut/SKILL.md +6 -2
  152. package/dist/services/worktree/git-worktree-parser.d.ts +0 -8
  153. package/dist/services/worktree/git-worktree-parser.js +0 -55
  154. package/dist/services/worktree/worktree-lease-types.d.ts +0 -52
  155. package/dist/services/worktree/worktree-lease-types.js +0 -9
  156. package/dist/services/worktree/worktree-lease.d.ts +0 -116
  157. package/dist/services/worktree/worktree-lease.js +0 -252
@@ -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
  }
@@ -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
+ }