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
@@ -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;
@@ -0,0 +1,34 @@
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
+ /**
11
+ * Split the leading `---` block.
12
+ *
13
+ * CRLF-TOLERANT ON PURPOSE. `core.autocrlf=true` is the default on Windows, so a
14
+ * checkout can hand this module a file whose fences are `---\r\n`. A pattern
15
+ * anchored on `\n` alone finds no frontmatter there and the refresh refuses —
16
+ * reviving the exact freeze the refresh exists to end, on the platform most of
17
+ * its users run. The block is returned with `\n` endings so the yaml AST offsets
18
+ * and the span arithmetic agree; `crlf` records what the file actually uses, so
19
+ * the writer can put it back.
20
+ */
21
+ export function splitFrontmatter(content) {
22
+ const match = /^---(\r?\n)([\s\S]*?)\r?\n---/.exec(content);
23
+ if (match === null)
24
+ return null;
25
+ return {
26
+ frontmatter: (match[2] ?? '').replace(/\r\n/g, '\n'),
27
+ bodyStart: match[0].length,
28
+ crlf: match[1] === '\r\n'
29
+ };
30
+ }
31
+ /** The frontmatter block alone, or `null`. */
32
+ export function frontmatterOf(content) {
33
+ return splitFrontmatter(content)?.frontmatter ?? null;
34
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The `libraryVersions` map a project scan records, derived from `scanLibraries`.
3
+ *
4
+ * WHY THE ROOT MANIFEST DECIDES. In a monorepo the scan concatenates every
5
+ * workspace `package.json`, so one name appears once per declaring package with
6
+ * that package's own spec — `typescript` arrives as BOTH the root's `^5.7.2` and
7
+ * a workspace package's `^5.4.0`, and a package used only by a workspace
8
+ * (`ecc-universal`) appears with no root declaration at all. Taking the first row
9
+ * records whichever specifier sorts first, which is the workspace's, not the
10
+ * project's. peaks-rd cross-checks this map against the breaking-changes table,
11
+ * and a floor is exactly the wrong version to file a project under.
12
+ *
13
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
14
+ * 300-line cap.
15
+ */
16
+ /**
17
+ * The root manifest's own dependency map: name → specifier, across every scope.
18
+ *
19
+ * THE ROOT MANIFEST IS THE SOURCE OF THE SPECIFIER, not the scan's row order.
20
+ * This used to be built by taking the first row `scanLibraries` emitted for each
21
+ * name, on the assumption the root sorts first. That assumption is false for any
22
+ * workspace glob outside `packages/*` — `apps/*` and `libs/*` sort a workspace
23
+ * package ahead of the root — so a project pinning `typescript ^5.7.2` recorded
24
+ * the workspace's `^5.4.0` instead. Measured 2026-11-16. Reading the manifest
25
+ * directly removes the ordering dependency entirely: whichever rows exist, the
26
+ * recorded specifier is the one the project itself declares.
27
+ *
28
+ * `null` means "cannot tell" — the manifest is absent, is not a JSON object, or
29
+ * could not be read — and the caller then falls back to the raw scan instead of
30
+ * emptying the map. A malformed manifest therefore degrades the same way a
31
+ * missing one does; it does not throw out of a refresh nobody explicitly asked
32
+ * for.
33
+ */
34
+ export declare function rootDeclaredVersions(projectRoot: string): Map<string, string> | null;
35
+ /**
36
+ * The names the project's OWN `package.json` declares, across every scope.
37
+ * See `rootDeclaredVersions` for what `null` means.
38
+ */
39
+ export declare function rootDeclaredNames(projectRoot: string): Set<string> | null;
40
+ /**
41
+ * Keep one row per name, and only for names the root manifest declares — a name
42
+ * only a workspace package declares is dropped, because the file describes the
43
+ * project and listing a dependency it does not have is a fact peaks-rd would then
44
+ * check against the wrong thing.
45
+ */
46
+ export declare function toLibraryVersions(entries: ReadonlyArray<{
47
+ readonly name: string;
48
+ readonly version: string;
49
+ }>, rootDeclared: ReadonlySet<string>): Record<string, string>;
50
+ /**
51
+ * The map for a project.
52
+ *
53
+ * The ROOT MANIFEST supplies the specifier for every name it declares; the scan
54
+ * supplies only the row set. When the manifest cannot be read, the scan's own
55
+ * rows are used unchanged (never silently empties the map).
56
+ */
57
+ export declare function libraryVersionsFor(projectRoot: string, entries: ReadonlyArray<{
58
+ readonly name: string;
59
+ readonly version: string;
60
+ }>): Record<string, string>;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The `libraryVersions` map a project scan records, derived from `scanLibraries`.
3
+ *
4
+ * WHY THE ROOT MANIFEST DECIDES. In a monorepo the scan concatenates every
5
+ * workspace `package.json`, so one name appears once per declaring package with
6
+ * that package's own spec — `typescript` arrives as BOTH the root's `^5.7.2` and
7
+ * a workspace package's `^5.4.0`, and a package used only by a workspace
8
+ * (`ecc-universal`) appears with no root declaration at all. Taking the first row
9
+ * records whichever specifier sorts first, which is the workspace's, not the
10
+ * project's. peaks-rd cross-checks this map against the breaking-changes table,
11
+ * and a floor is exactly the wrong version to file a project under.
12
+ *
13
+ * Split out of `project-scan-field-refresh.ts` to stay under the `src/**`
14
+ * 300-line cap.
15
+ */
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ /** The `package.json` scopes a dependency can be declared in. */
19
+ const DEPENDENCY_SCOPES = [
20
+ 'dependencies',
21
+ 'devDependencies',
22
+ 'peerDependencies',
23
+ 'optionalDependencies'
24
+ ];
25
+ /** A parsed `package.json` that carries dependency maps, or `null`. */
26
+ function isDependencyRecord(value) {
27
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ }
29
+ /**
30
+ * Parse the root manifest. Returns `undefined` when it cannot be used — absent,
31
+ * unreadable, or not a JSON object.
32
+ *
33
+ * The catch does not RETURN the failure value: it records the failure in a
34
+ * variable and falls off the end, so the "cannot tell" answer is written once,
35
+ * at the call site, rather than disguised as a successful `return null`.
36
+ */
37
+ function parseManifest(projectRoot) {
38
+ const manifestPath = join(projectRoot, 'package.json');
39
+ if (!existsSync(manifestPath))
40
+ return undefined;
41
+ let raw;
42
+ try {
43
+ raw = readFileSync(manifestPath, 'utf8');
44
+ }
45
+ catch {
46
+ raw = undefined;
47
+ }
48
+ if (raw === undefined)
49
+ return undefined;
50
+ let parsed;
51
+ try {
52
+ parsed = JSON.parse(raw);
53
+ }
54
+ catch {
55
+ parsed = undefined;
56
+ }
57
+ return isDependencyRecord(parsed) ? parsed : undefined;
58
+ }
59
+ /**
60
+ * The root manifest's own dependency map: name → specifier, across every scope.
61
+ *
62
+ * THE ROOT MANIFEST IS THE SOURCE OF THE SPECIFIER, not the scan's row order.
63
+ * This used to be built by taking the first row `scanLibraries` emitted for each
64
+ * name, on the assumption the root sorts first. That assumption is false for any
65
+ * workspace glob outside `packages/*` — `apps/*` and `libs/*` sort a workspace
66
+ * package ahead of the root — so a project pinning `typescript ^5.7.2` recorded
67
+ * the workspace's `^5.4.0` instead. Measured 2026-11-16. Reading the manifest
68
+ * directly removes the ordering dependency entirely: whichever rows exist, the
69
+ * recorded specifier is the one the project itself declares.
70
+ *
71
+ * `null` means "cannot tell" — the manifest is absent, is not a JSON object, or
72
+ * could not be read — and the caller then falls back to the raw scan instead of
73
+ * emptying the map. A malformed manifest therefore degrades the same way a
74
+ * missing one does; it does not throw out of a refresh nobody explicitly asked
75
+ * for.
76
+ */
77
+ export function rootDeclaredVersions(projectRoot) {
78
+ const parsed = parseManifest(projectRoot);
79
+ if (parsed === undefined)
80
+ return null;
81
+ const versions = new Map();
82
+ for (const scope of DEPENDENCY_SCOPES) {
83
+ const deps = parsed[scope];
84
+ if (!isDependencyRecord(deps))
85
+ continue;
86
+ for (const [name, spec] of Object.entries(deps)) {
87
+ // A scope earlier in DEPENDENCY_SCOPES wins, matching package.json's own
88
+ // precedence (a real `dependency` is what the project installs).
89
+ if (!versions.has(name) && typeof spec === 'string')
90
+ versions.set(name, spec);
91
+ }
92
+ }
93
+ return versions;
94
+ }
95
+ /**
96
+ * The names the project's OWN `package.json` declares, across every scope.
97
+ * See `rootDeclaredVersions` for what `null` means.
98
+ */
99
+ export function rootDeclaredNames(projectRoot) {
100
+ const versions = rootDeclaredVersions(projectRoot);
101
+ return versions === null ? null : new Set(versions.keys());
102
+ }
103
+ /**
104
+ * Keep one row per name, and only for names the root manifest declares — a name
105
+ * only a workspace package declares is dropped, because the file describes the
106
+ * project and listing a dependency it does not have is a fact peaks-rd would then
107
+ * check against the wrong thing.
108
+ */
109
+ export function toLibraryVersions(entries, rootDeclared) {
110
+ const versions = {};
111
+ for (const entry of entries) {
112
+ if (!rootDeclared.has(entry.name))
113
+ continue;
114
+ if (versions[entry.name] === undefined)
115
+ versions[entry.name] = entry.version;
116
+ }
117
+ return versions;
118
+ }
119
+ /**
120
+ * The map for a project.
121
+ *
122
+ * The ROOT MANIFEST supplies the specifier for every name it declares; the scan
123
+ * supplies only the row set. When the manifest cannot be read, the scan's own
124
+ * rows are used unchanged (never silently empties the map).
125
+ */
126
+ export function libraryVersionsFor(projectRoot, entries) {
127
+ const declared = rootDeclaredVersions(projectRoot);
128
+ if (declared === null) {
129
+ return toLibraryVersions(entries, new Set(entries.map((e) => e.name)));
130
+ }
131
+ const versions = {};
132
+ for (const [name, spec] of declared)
133
+ versions[name] = spec;
134
+ return versions;
135
+ }