peaks-loop 4.1.17 → 4.1.19

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 (205) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +269 -0
  3. package/README-en.md +6 -0
  4. package/README.md +5 -0
  5. package/contracts/test-style-contract.md +14 -5
  6. package/dist/cli/commands/audit-red-lines-runners.js +6 -1
  7. package/dist/cli/commands/best-practice-scan-collision.d.ts +42 -0
  8. package/dist/cli/commands/best-practice-scan-collision.js +115 -0
  9. package/dist/cli/commands/best-practice-scan-command.d.ts +5 -0
  10. package/dist/cli/commands/best-practice-scan-command.js +9 -18
  11. package/dist/cli/commands/best-practice-scan-helpers.d.ts +12 -6
  12. package/dist/cli/commands/best-practice-scan-helpers.js +37 -17
  13. package/dist/cli/commands/code-auto-compact-command.js +71 -40
  14. package/dist/cli/commands/code-auto-compact-deferral.d.ts +34 -0
  15. package/dist/cli/commands/code-auto-compact-deferral.js +59 -0
  16. package/dist/cli/commands/code-gate-command.d.ts +4 -4
  17. package/dist/cli/commands/code-gate-command.js +4 -4
  18. package/dist/cli/commands/core/skill-generated-config-notice.d.ts +5 -0
  19. package/dist/cli/commands/core/skill-generated-config-notice.js +42 -8
  20. package/dist/cli/commands/core/skill-presence-commands.js +42 -74
  21. package/dist/cli/commands/core/skill-presence-set-command.d.ts +11 -0
  22. package/dist/cli/commands/core/skill-presence-set-command.js +175 -0
  23. package/dist/cli/commands/core/skill-registry-commands.js +32 -0
  24. package/dist/cli/commands/core/skill-store-report.d.ts +8 -0
  25. package/dist/cli/commands/core/skill-store-report.js +79 -0
  26. package/dist/cli/commands/core/standards-init-command.js +44 -8
  27. package/dist/cli/commands/core/standards-migrate-command.js +5 -4
  28. package/dist/cli/commands/dispatch-dag-runners.d.ts +1 -0
  29. package/dist/cli/commands/dispatch-dag-runners.js +11 -1
  30. package/dist/cli/commands/dispatch-detached-branch.js +19 -1
  31. package/dist/cli/commands/dispatch-prompt-composition.js +7 -2
  32. package/dist/cli/commands/dispatch-scratch-path-block.d.ts +73 -0
  33. package/dist/cli/commands/dispatch-scratch-path-block.js +131 -0
  34. package/dist/cli/commands/hooks-commands.js +36 -7
  35. package/dist/cli/commands/hooks-uninstall-command.js +5 -5
  36. package/dist/cli/commands/mut-commands-helpers.d.ts +72 -5
  37. package/dist/cli/commands/mut-commands-helpers.js +197 -4
  38. package/dist/cli/commands/mut-commands.d.ts +9 -1
  39. package/dist/cli/commands/mut-commands.js +82 -154
  40. package/dist/cli/commands/preferences-commands.js +27 -2
  41. package/dist/cli/commands/scan-scope-helpers.js +2 -2
  42. package/dist/services/24h-mode/auto-engage.d.ts +11 -3
  43. package/dist/services/24h-mode/auto-engage.js +14 -6
  44. package/dist/services/artifacts/artifact-templates.js +10 -0
  45. package/dist/services/artifacts/backcompat-acceptance.d.ts +8 -1
  46. package/dist/services/artifacts/backcompat-acceptance.js +8 -7
  47. package/dist/services/artifacts/rd-transition-gates.d.ts +32 -5
  48. package/dist/services/artifacts/rd-transition-gates.js +96 -19
  49. package/dist/services/artifacts/request-artifact-service.js +6 -6
  50. package/dist/services/audit/enforcers/lint-output-style.js +14 -2
  51. package/dist/services/audit/enforcers/root-scratch-artifacts.d.ts +46 -0
  52. package/dist/services/audit/enforcers/root-scratch-artifacts.js +97 -0
  53. package/dist/services/audit/static-service.js +4 -4
  54. package/dist/services/code/auto-compact-history.d.ts +6 -1
  55. package/dist/services/code/auto-compact-history.js +6 -1
  56. package/dist/services/code/auto-compact-modes.d.ts +60 -14
  57. package/dist/services/code/auto-compact-modes.js +75 -20
  58. package/dist/services/code/auto-compact-orchestrator.js +7 -5
  59. package/dist/services/code/auto-compact-profile.d.ts +23 -0
  60. package/dist/services/code/auto-compact-profile.js +51 -0
  61. package/dist/services/code/auto-compact-run-types.d.ts +8 -4
  62. package/dist/services/compact-history/compact-history-service.d.ts +6 -1
  63. package/dist/services/compact-history/compact-history-service.js +5 -1
  64. package/dist/services/context/auto-compact-types.d.ts +7 -5
  65. package/dist/services/dispatch/dispatch-ledger-reader.d.ts +13 -0
  66. package/dist/services/dispatch/dispatch-ledger-reader.js +164 -0
  67. package/dist/services/doctor/doctor-service/checks/canonical-store-version.d.ts +57 -0
  68. package/dist/services/doctor/doctor-service/checks/canonical-store-version.js +190 -0
  69. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.d.ts +37 -0
  70. package/dist/services/doctor/doctor-service/checks/l3-runtime-root-census.js +100 -0
  71. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.d.ts +11 -3
  72. package/dist/services/doctor/doctor-service/checks/skill-reference-parity.js +48 -29
  73. package/dist/services/doctor/doctor-service/plugin-registry.js +4 -0
  74. package/dist/services/doctor/doctor-service/types.d.ts +12 -0
  75. package/dist/services/hooks/hook-payload-cwd.d.ts +11 -4
  76. package/dist/services/hooks/hook-payload-cwd.js +11 -4
  77. package/dist/services/hooks/pre-tool-code-gate.d.ts +4 -4
  78. package/dist/services/hooks/pre-tool-code-gate.js +4 -4
  79. package/dist/services/hooks/presence-marker-detector.d.ts +3 -0
  80. package/dist/services/hooks/presence-marker-detector.js +21 -19
  81. package/dist/services/ide/adapters/claude-code-adapter.js +6 -8
  82. package/dist/services/ide/adapters/codex-adapter.js +23 -7
  83. package/dist/services/ide/adapters/cursor-adapter.js +23 -7
  84. package/dist/services/mode/mode-status-service.d.ts +26 -27
  85. package/dist/services/mode/mode-status-service.js +36 -60
  86. package/dist/services/preferences/preferences-types.d.ts +30 -0
  87. package/dist/services/preferences/preferences-types.js +13 -0
  88. package/dist/services/scan/acceptance-coverage-service.d.ts +14 -11
  89. package/dist/services/scan/acceptance-coverage-service.js +157 -52
  90. package/dist/services/scan/rid-change-claims.d.ts +15 -0
  91. package/dist/services/scan/rid-change-claims.js +116 -0
  92. package/dist/services/session/getSessionDir.d.ts +13 -0
  93. package/dist/services/session/getSessionDir.js +7 -1
  94. package/dist/services/skills/hooks-settings-types.d.ts +17 -21
  95. package/dist/services/skills/presence-caller-id.d.ts +51 -0
  96. package/dist/services/skills/presence-caller-id.js +43 -0
  97. package/dist/services/skills/presence-gate.d.ts +65 -0
  98. package/dist/services/skills/presence-gate.js +113 -0
  99. package/dist/services/skills/presence-lease-resolver.d.ts +63 -0
  100. package/dist/services/skills/presence-lease-resolver.js +114 -0
  101. package/dist/services/skills/presence-lease-selection.d.ts +91 -0
  102. package/dist/services/skills/presence-lease-selection.js +135 -0
  103. package/dist/services/skills/presence-lease-service.d.ts +3 -11
  104. package/dist/services/skills/presence-lease-service.js +34 -87
  105. package/dist/services/skills/presence-lease-store.d.ts +33 -0
  106. package/dist/services/skills/presence-lease-store.js +94 -0
  107. package/dist/services/skills/presence-lease-types.d.ts +31 -0
  108. package/dist/services/skills/presence-lease-types.js +27 -0
  109. package/dist/services/skills/presence-role.d.ts +35 -0
  110. package/dist/services/skills/presence-role.js +72 -0
  111. package/dist/services/skills/skill-presence-service.d.ts +39 -9
  112. package/dist/services/skills/skill-presence-service.js +143 -174
  113. package/dist/services/skills/skill-presence-write.d.ts +60 -0
  114. package/dist/services/skills/skill-presence-write.js +74 -0
  115. package/dist/services/skills/skill-statusline-service.js +7 -7
  116. package/dist/services/skills/sync-service-support.d.ts +27 -0
  117. package/dist/services/skills/sync-service.js +1 -0
  118. package/dist/services/standards/ide-aware-standards-service.d.ts +35 -23
  119. package/dist/services/standards/ide-aware-standards-service.js +45 -20
  120. package/dist/services/standards/migrate-claude-rules-service.d.ts +6 -0
  121. package/dist/services/standards/migrate-claude-rules-service.js +18 -0
  122. package/dist/services/standards/migrate-service.d.ts +1 -1
  123. package/dist/services/standards/migrate-service.js +27 -7
  124. package/dist/services/standards/project-scripts.d.ts +25 -0
  125. package/dist/services/standards/project-scripts.js +116 -0
  126. package/dist/services/standards/project-standards-service.d.ts +23 -15
  127. package/dist/services/standards/project-standards-service.js +176 -243
  128. package/dist/services/standards/standards-constitution.d.ts +89 -0
  129. package/dist/services/standards/standards-constitution.js +199 -0
  130. package/dist/services/standards/standards-files.d.ts +37 -0
  131. package/dist/services/standards/standards-files.js +138 -0
  132. package/dist/services/standards/standards-pointer.d.ts +73 -0
  133. package/dist/services/standards/standards-pointer.js +98 -0
  134. package/dist/services/standards/standards-render-agents.d.ts +34 -0
  135. package/dist/services/standards/standards-render-agents.js +149 -0
  136. package/dist/services/standards/standards-render-common.d.ts +38 -1
  137. package/dist/services/standards/standards-render-common.js +44 -7
  138. package/dist/services/standards/standards-render.d.ts +1 -3
  139. package/dist/services/standards/standards-render.js +6 -87
  140. package/dist/services/workflow/workflow-graph-ensure.d.ts +77 -0
  141. package/dist/services/workflow/workflow-graph-ensure.js +97 -0
  142. package/dist/services/workflow/workflow-inflight-probe.d.ts +68 -31
  143. package/dist/services/workflow/workflow-inflight-probe.js +163 -75
  144. package/dist/services/workflow/workflow-presence-lifecycle.js +21 -6
  145. package/dist/services/workspace/generated-artifacts-content.d.ts +46 -0
  146. package/dist/services/workspace/generated-artifacts-content.js +167 -0
  147. package/dist/services/workspace/generated-artifacts-stamp.d.ts +36 -13
  148. package/dist/services/workspace/generated-artifacts-stamp.js +37 -15
  149. package/dist/services/workspace/runtime-layout.d.ts +64 -0
  150. package/dist/services/workspace/runtime-layout.js +62 -0
  151. package/output-styles/peaks-skill-swarm.md +18 -2
  152. package/package.json +10 -9
  153. package/schemas/doctor-report.schema.json +1 -1
  154. package/scripts/canonical-store-fs.mjs +112 -0
  155. package/scripts/canonical-store-link.mjs +13 -22
  156. package/scripts/canonical-store-marker.mjs +241 -0
  157. package/scripts/canonical-store.mjs +119 -141
  158. package/scripts/install-skills-bundles.mjs +56 -13
  159. package/scripts/install-skills-fs.mjs +73 -0
  160. package/scripts/install-skills-output-styles.mjs +8 -2
  161. package/scripts/install-skills-report.mjs +19 -0
  162. package/scripts/install-skills.mjs +9 -0
  163. package/skills/bee/peaks-perf-audit/SKILL.md +3 -1
  164. package/skills/bee/peaks-prd/SKILL.md +5 -3
  165. package/skills/bee/peaks-qa/SKILL.md +4 -2
  166. package/skills/bee/peaks-qa/references/qa-skill-presence.md +1 -1
  167. package/skills/bee/peaks-qa/references/qa-standards-preflight.md +3 -1
  168. package/skills/bee/peaks-qa/references/qa-sub-agent-dispatch.md +2 -2
  169. package/skills/bee/peaks-rd/SKILL.md +4 -2
  170. package/skills/bee/peaks-rd/references/artifact-and-standards-output.md +1 -1
  171. package/skills/bee/peaks-rd/references/rd-runbook.md +11 -2
  172. package/skills/bee/peaks-rd/references/rd-standards-preflight.md +3 -1
  173. package/skills/bee/peaks-rd/references/rd-sub-agent-dispatch.md +24 -5
  174. package/skills/bee/peaks-rd/references/rd-transition-gates.md +49 -5
  175. package/skills/bee/peaks-rd/references/skill-presence-and-title.md +1 -1
  176. package/skills/bee/peaks-reviewer/SKILL.md +3 -1
  177. package/skills/bee/peaks-sc/SKILL.md +4 -2
  178. package/skills/bee/peaks-security-audit/SKILL.md +3 -1
  179. package/skills/bee/peaks-txt/SKILL.md +5 -3
  180. package/skills/bee/peaks-ui/SKILL.md +6 -4
  181. package/skills/peaks-audit/SKILL.md +3 -1
  182. package/skills/peaks-code/SKILL.md +4 -2
  183. package/skills/peaks-code/references/a2a-artifact-mapping.md +3 -3
  184. package/skills/peaks-code/references/completion-handoff.md +1 -1
  185. package/skills/peaks-code/references/local-artifact-workspace.md +10 -11
  186. package/skills/peaks-code/references/micro-cycle.md +2 -2
  187. package/skills/peaks-code/references/mode-selection-with-stale-presence.md +3 -3
  188. package/skills/peaks-code/references/runbook.md +4 -4
  189. package/skills/peaks-code/references/skill-presence-and-title.md +4 -2
  190. package/skills/peaks-code/references/standards-preflight.md +7 -6
  191. package/skills/peaks-code/references/sub-agent-dispatch.md +1 -1
  192. package/skills/peaks-code/references/swarm-dispatch-contract.md +5 -5
  193. package/skills/peaks-code/references/workflow-gates-and-types.md +37 -11
  194. package/skills/peaks-content/SKILL.md +3 -1
  195. package/skills/peaks-doctor/SKILL.md +3 -1
  196. package/skills/peaks-final-review/SKILL.md +3 -1
  197. package/skills/peaks-ide/SKILL.md +3 -1
  198. package/skills/peaks-issue-fix-orchestrator/SKILL.md +5 -3
  199. package/skills/peaks-race-code/SKILL.md +9 -4
  200. package/skills/peaks-resume/SKILL.md +3 -1
  201. package/skills/peaks-slice-decompose/SKILL.md +3 -1
  202. package/skills/peaks-solo/SKILL.md +3 -1
  203. package/skills/peaks-sop/SKILL.md +4 -2
  204. package/skills/peaks-status/SKILL.md +3 -1
  205. package/skills/peaks-test/SKILL.md +3 -1
@@ -0,0 +1,241 @@
1
+ #!/usr/bin/env node
2
+ //
3
+ // The `.peaks-managed` sidecar — its FORMAT, its reader, its writer, and the
4
+ // version comparison the store's staleness decision rests on.
5
+ //
6
+ // WHY IT IS ITS OWN MODULE. `canonical-store.mjs` was one line under the
7
+ // 300-line cap, and the marker grew a second fact (the version that produced
8
+ // the copy) plus a parser that must keep reading the LEGACY shape — the plain
9
+ // single-path line already sitting on every user's machine. The format is a
10
+ // CONTRACT with those machines, so the code that owns it lives in one file
11
+ // with the compatibility rules written down beside it.
12
+ //
13
+ // THE TWO FACTS. A sidecar records (1) the SOURCE PATH the copy was made from
14
+ // and (2) the PACKAGE VERSION that copy came from. The path says WHERE the
15
+ // bytes came from; the version says HOW OLD they are. The version is the fact
16
+ // that makes staleness KNOWABLE: without it a store frozen at 4.1.15 is
17
+ // indistinguishable from a store that is current, which is why a downstream
18
+ // machine sat on a stale skill for an unknown number of releases.
19
+ //
20
+ // THE FORMAT. One line of JSON:
21
+ //
22
+ // {"format":"peaks-managed-v2","path":"<source path>","version":"<version>"}
23
+ //
24
+ // THE LEGACY FORMAT IS STILL READ. A sidecar holding a plain path — the shape
25
+ // every install before this one wrote — parses as `{path, version: null}`:
26
+ // "ours, version unknown". A reader that threw on the old format would break
27
+ // every existing install, so it does not. Only a writer that KNOWS the version
28
+ // writes the new shape; a reader never rewrites a marker it merely read.
29
+ //
30
+ // THE PATH IS NOT AUTHORITY. The recorded path is provenance, not ownership:
31
+ // ownership is decided by the PRESENCE of the sidecar, so a store entry the
32
+ // user authored (no sidecar) is still never overwritten.
33
+
34
+ import { randomUUID } from 'node:crypto';
35
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
36
+ import { dirname } from 'node:path';
37
+
38
+ /** Sidecar suffix, same convention `install-skills.mjs` already writes. */
39
+ export const MANAGED_MARKER_SUFFIX = '.peaks-managed';
40
+
41
+ /** The marker shape this module writes. A reader accepts it and the legacy one. */
42
+ export const MANAGED_MARKER_FORMAT = 'peaks-managed-v2';
43
+
44
+ /** Scratch prefix for the atomic write; never a valid asset name. */
45
+ const TEMP_PREFIX = '.peaks-tmp-';
46
+
47
+ /** How many segments a release string is compared by: MAJOR.MINOR.PATCH. */
48
+ const RELEASE_SEGMENTS = 3;
49
+
50
+ function getPathStats(path) {
51
+ try {
52
+ return lstatSync(path);
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /** A marker is a plain single-linked file — never a link, never a hardlink. */
59
+ function validateMarkerPath(markerPath) {
60
+ const stats = getPathStats(markerPath);
61
+ if (!stats) return;
62
+ if (stats.isSymbolicLink()) throw new Error('Peaks managed marker path must not be a symlink');
63
+ if (!stats.isFile()) throw new Error('Peaks managed marker path must be a file');
64
+ if (stats.nlink !== 1) throw new Error('Peaks managed marker path must not be hardlinked');
65
+ }
66
+
67
+ /**
68
+ * The v2 marker parsed, or null when the content is not one. A legacy plain
69
+ * path is not JSON; a legacy JSON marker (the pre-canonical-store agent shape)
70
+ * is JSON but does not carry this format tag, so it is not ours either.
71
+ */
72
+ function parseVersionedMarker(content) {
73
+ const trimmed = content.trim();
74
+ if (!trimmed.startsWith('{')) return null;
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(trimmed);
78
+ } catch {
79
+ return null;
80
+ }
81
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
82
+ if (parsed.format !== MANAGED_MARKER_FORMAT) return null;
83
+ return {
84
+ path: typeof parsed.path === 'string' && parsed.path.length > 0 ? parsed.path : null,
85
+ version: typeof parsed.version === 'string' && parsed.version.length > 0 ? parsed.version : null
86
+ };
87
+ }
88
+
89
+ /**
90
+ * The sidecar's two facts, or null when there is no sidecar. A LEGACY sidecar
91
+ * (a plain path, or the pre-canonical-store JSON shape) reads as a path with
92
+ * `version: null` — "ours, version unknown".
93
+ *
94
+ * @param {string} targetPath
95
+ * @returns {{ path: string | null, version: string | null } | null}
96
+ */
97
+ export function readManagedMarker(targetPath) {
98
+ const markerPath = `${targetPath}${MANAGED_MARKER_SUFFIX}`;
99
+ validateMarkerPath(markerPath);
100
+ if (!existsSync(markerPath)) return null;
101
+ const content = readFileSync(markerPath, 'utf8');
102
+ const versioned = parseVersionedMarker(content);
103
+ if (versioned !== null) return versioned;
104
+ const legacy = content.trim();
105
+ return { path: legacy.length > 0 ? legacy : null, version: null };
106
+ }
107
+
108
+ /**
109
+ * The recorded path, for the callers that only need that. A v2 marker answers
110
+ * its path; every other shape answers its content unchanged, which is what the
111
+ * pre-canonical-store readers already expected to find.
112
+ *
113
+ * @param {string} targetPath
114
+ * @returns {string | null}
115
+ */
116
+ export function readManagedTarget(targetPath) {
117
+ const marker = readManagedMarker(targetPath);
118
+ if (marker === null) return null;
119
+ return marker.path;
120
+ }
121
+
122
+ /**
123
+ * Is there a sidecar beside this path at all? Ownership is decided by
124
+ * PRESENCE, not by the content: a sidecar we cannot parse is still a sidecar,
125
+ * and an empty one still marks the entry as ours.
126
+ *
127
+ * @param {string} targetPath
128
+ */
129
+ export function markerExists(targetPath) {
130
+ const markerPath = `${targetPath}${MANAGED_MARKER_SUFFIX}`;
131
+ validateMarkerPath(markerPath);
132
+ return existsSync(markerPath);
133
+ }
134
+
135
+ /**
136
+ * Write the sidecar through a sibling temp file, so no reader sees it
137
+ * half-written. With a `version`, the v2 shape is written; without one, the
138
+ * legacy single-path line is written — the shape every caller that does not
139
+ * know a version has always written.
140
+ *
141
+ * @param {string} targetPath
142
+ * @param {string} provenance
143
+ * @param {string} [version]
144
+ */
145
+ export function writeManagedMarker(targetPath, provenance, version) {
146
+ const markerPath = `${targetPath}${MANAGED_MARKER_SUFFIX}`;
147
+ validateMarkerPath(markerPath);
148
+ mkdirSync(dirname(markerPath), { recursive: true });
149
+ const tempPath = `${markerPath}${TEMP_PREFIX}${randomUUID()}`;
150
+ const body =
151
+ typeof version === 'string' && version.length > 0
152
+ ? `${JSON.stringify({ format: MANAGED_MARKER_FORMAT, path: provenance, version })}\n`
153
+ : `${provenance}\n`;
154
+ writeFileSync(tempPath, body, 'utf8');
155
+ renameSync(tempPath, markerPath);
156
+ }
157
+
158
+ /**
159
+ * The `kind` each family wrote into its pre-canonical-store JSON sidecar.
160
+ */
161
+ export const LEGACY_MARKER_KIND = Object.freeze({
162
+ agents: 'agent',
163
+ 'output-styles': 'output-style'
164
+ });
165
+
166
+ /**
167
+ * The sidecar shape written before the canonical store existed: JSON naming the
168
+ * package path the file was copied from, plus a content hash. Parsed, never
169
+ * trusted — and it is a MARKER FORMAT, so it is read here, beside the format
170
+ * this module writes.
171
+ *
172
+ * @param {string} recorded
173
+ * @returns {{ kind: string, assetName: string, sourcePath: string } | null}
174
+ */
175
+ export function parseLegacyMarker(recorded) {
176
+ if (typeof recorded !== 'string' || !recorded.startsWith('{')) return null;
177
+ let marker;
178
+ try {
179
+ marker = JSON.parse(recorded);
180
+ } catch {
181
+ return null;
182
+ }
183
+ const assetName = marker?.agentName ?? marker?.outputStyleName;
184
+ if (marker?.version !== 1 || typeof marker.kind !== 'string') return null;
185
+ if (typeof assetName !== 'string' || typeof marker.sourcePath !== 'string') return null;
186
+ return { kind: marker.kind, assetName, sourcePath: marker.sourcePath };
187
+ }
188
+
189
+ /**
190
+ * A release string's `MAJOR.MINOR.PATCH`, as three numbers. Only the leading
191
+ * triple is read: a prerelease suffix compares as its release triple, and a
192
+ * segment that is missing or not a number reads as 0 — which is also what
193
+ * makes an UNREADABLE version the oldest one, and therefore stale.
194
+ */
195
+ function releaseTriple(version) {
196
+ const segments = String(version).replace(/^v/i, '').split('-')[0].split('.');
197
+ const triple = [];
198
+ for (let index = 0; index < RELEASE_SEGMENTS; index += 1) {
199
+ const parsed = Number.parseInt(segments[index] ?? '', 10);
200
+ triple.push(Number.isNaN(parsed) ? 0 : parsed);
201
+ }
202
+ return triple;
203
+ }
204
+
205
+ /**
206
+ * Negative when `a` predates `b`, positive when it follows, 0 when their
207
+ * release triples are equal.
208
+ *
209
+ * @param {string} a
210
+ * @param {string} b
211
+ */
212
+ export function compareVersions(a, b) {
213
+ const left = releaseTriple(a);
214
+ const right = releaseTriple(b);
215
+ for (let index = 0; index < RELEASE_SEGMENTS; index += 1) {
216
+ const difference = (left[index] ?? 0) - (right[index] ?? 0);
217
+ if (difference !== 0) return difference < 0 ? -1 : 1;
218
+ }
219
+ return 0;
220
+ }
221
+
222
+ /**
223
+ * Is the recorded version BEHIND the source version?
224
+ *
225
+ * Three answers, and the middle one is the whole point of this module:
226
+ * - no source version known → false. Nothing to compare against, so the
227
+ * decision falls back to the bytes.
228
+ * - no recorded version → TRUE. "Version unknown" is stale: the source
229
+ * package is authoritative, and a copy that cannot say how old it is
230
+ * cannot be shown to be current.
231
+ * - both known → true only when the recorded one is OLDER. A
232
+ * copy recorded by a NEWER version is not behind, and is left alone.
233
+ *
234
+ * @param {string | null} recorded
235
+ * @param {string | null} source
236
+ */
237
+ export function isVersionBehind(recorded, source) {
238
+ if (typeof source !== 'string' || source.length === 0) return false;
239
+ if (typeof recorded !== 'string' || recorded.length === 0) return true;
240
+ return compareVersions(recorded, source) < 0;
241
+ }
@@ -8,10 +8,13 @@
8
8
  // peaks-loop@latest`: the links bound to a VERSION, not to a PATH peaks-loop owns.
9
9
  //
10
10
  // WIRED FOR SKILLS (slice 2) and PRUNED (slice 3); agents / output-styles are later.
11
- // `scripts/install-skills.mjs` is the only caller today. Idempotence is by CONTENT —
12
- // an asset whose bytes already match is not rewritten — and OWNERSHIP is by MARKER:
13
- // see `isManagedEntry`, which gates the replace path here and the delete path in
14
- // `scripts/canonical-store-prune.mjs`.
11
+ // `scripts/install-skills.mjs` is the only caller today. Idempotence is by CONTENT
12
+ // AND BY VERSION — an asset whose bytes already match is not rewritten, and an
13
+ // asset made by an OLDER release is refreshed even when its bytes happen to
14
+ // match — and OWNERSHIP is by MARKER: see `isManagedEntry`, which gates the
15
+ // replace path here and the delete path in `scripts/canonical-store-prune.mjs`.
16
+ // The marker itself, its format and the version it records, live in
17
+ // `scripts/canonical-store-marker.mjs`.
15
18
 
16
19
  import { randomUUID } from 'node:crypto';
17
20
  import {
@@ -19,18 +22,39 @@ import {
19
22
  existsSync,
20
23
  lstatSync,
21
24
  mkdirSync,
22
- readdirSync,
23
- readFileSync,
24
- realpathSync,
25
25
  renameSync,
26
26
  rmSync,
27
27
  symlinkSync,
28
- unlinkSync,
29
- writeFileSync
28
+ unlinkSync
30
29
  } from 'node:fs';
31
30
  import { homedir } from 'node:os';
32
31
  import { dirname, join, resolve } from 'node:path';
33
32
 
33
+ import { contentMatches, getPathStats, linkResolvesTo } from './canonical-store-fs.mjs';
34
+ import {
35
+ LEGACY_MARKER_KIND,
36
+ MANAGED_MARKER_SUFFIX,
37
+ isVersionBehind,
38
+ markerExists,
39
+ parseLegacyMarker,
40
+ readManagedMarker,
41
+ readManagedTarget,
42
+ writeManagedMarker
43
+ } from './canonical-store-marker.mjs';
44
+
45
+ // The marker API is re-exported from here so every existing importer — the
46
+ // link module, the prune module, the type declarations — keeps its one
47
+ // import site, while the format itself lives in the module that owns it.
48
+ export {
49
+ LEGACY_MARKER_KIND,
50
+ MANAGED_MARKER_SUFFIX,
51
+ parseLegacyMarker,
52
+ readManagedMarker,
53
+ readManagedTarget,
54
+ writeManagedMarker
55
+ };
56
+ export { linkResolvesTo };
57
+
34
58
  /** The three asset families, parallel under the canonical root. */
35
59
  export const CANONICAL_ASSET_KINDS = Object.freeze(['skills', 'agents', 'output-styles']);
36
60
 
@@ -38,64 +62,24 @@ export const CANONICAL_ASSET_KINDS = Object.freeze(['skills', 'agents', 'output-
38
62
  * `~/.peaks` (`src/services/sop/sop-paths.ts`). */
39
63
  export const CANONICAL_ROOT_ENV = 'PEAKS_HOME';
40
64
 
41
- /** Sidecar suffix, same convention `install-skills.mjs` already writes. */
42
- export const MANAGED_MARKER_SUFFIX = '.peaks-managed';
43
-
44
65
  /** Scratch prefix for the atomic write; never a valid name (assets do not start with a dot). */
45
66
  const TEMP_PREFIX = '.peaks-tmp-';
46
67
 
47
- function getPathStats(path) {
48
- try {
49
- return lstatSync(path);
50
- } catch {
51
- return null;
52
- }
53
- }
54
-
55
- /** `\\?\C:\x` and `\\?\UNC\srv\share` are spellings of a path, not other paths. */
56
- function stripLongPathPrefix(value) {
57
- const uncPrefix = '\\\\?\\UNC\\';
58
- if (value.startsWith(uncPrefix)) return `\\\\${value.slice(uncPrefix.length)}`;
59
- const prefix = '\\\\?\\';
60
- return value.startsWith(prefix) ? value.slice(prefix.length) : value;
61
- }
62
-
63
- /**
64
- * The real, resolved, case-folded identity of a path, or null when it does not
65
- * resolve (a dangling junction included).
66
- */
67
- function resolveIdentity(path) {
68
- let resolved;
69
- try {
70
- resolved = realpathSync(path);
71
- } catch {
72
- return null;
73
- }
74
- const normalized = stripLongPathPrefix(resolved);
75
- return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
76
- }
77
-
78
- /**
79
- * Whether `linkPath` resolves to the same directory as `expectedPath`. Both sides
80
- * go through `realpath`, so a `\\?\` prefix, a `.` segment or a case difference
81
- * cannot make one directory look like two.
82
- */
83
- export function linkResolvesTo(linkPath, expectedPath) {
84
- const actual = resolveIdentity(linkPath);
85
- const expected = resolveIdentity(expectedPath);
86
- return actual !== null && expected !== null && actual === expected;
87
- }
88
-
89
68
  /**
90
69
  * Does peaks-loop own `targetPath`? Our `.peaks-managed` marker beside it is the
91
70
  * only proof: a path the user authored carries none and must never be replaced or
92
71
  * removed (a DANGLING link counts as ours).
72
+ *
73
+ * The marker's PRESENCE is the proof, not its content — the content is
74
+ * provenance, and a sidecar this build cannot parse is still a sidecar. Reading
75
+ * the content here would make an unreadable marker indistinguishable from a
76
+ * missing one, and the missing one is the user's.
93
77
  */
94
78
  export function isManagedEntry(targetPath) {
95
79
  const stats = getPathStats(targetPath);
96
80
  if (!stats) return false;
97
81
  if (stats.isSymbolicLink()) return isOurLink(targetPath, stats);
98
- return readManagedTarget(targetPath) !== null;
82
+ return markerExists(targetPath);
99
83
  }
100
84
 
101
85
  /** Reject anything that is not one plain path segment; names reach the filesystem. */
@@ -138,99 +122,77 @@ export function resolveKindRoot(kind, options = {}) {
138
122
  return join(resolveCanonicalRoot(options), kind);
139
123
  }
140
124
 
141
- /** A marker is a plain single-linked file — never a link, never a hardlink. */
142
- function validateMarkerPath(markerPath) {
143
- const stats = getPathStats(markerPath);
144
- if (!stats) return;
145
- if (stats.isSymbolicLink()) throw new Error('Peaks managed marker path must not be a symlink');
146
- if (!stats.isFile()) throw new Error('Peaks managed marker path must be a file');
147
- if (stats.nlink !== 1) throw new Error('Peaks managed marker path must not be hardlinked');
148
- }
149
-
150
- /** The `.peaks-managed` sidecar beside `targetPath`, trimmed, or null — the same
151
- * convention `install-skills.mjs` writes (one line holding the producing path). */
152
- export function readManagedTarget(targetPath) {
153
- const markerPath = `${targetPath}${MANAGED_MARKER_SUFFIX}`;
154
- validateMarkerPath(markerPath);
155
- if (!existsSync(markerPath)) return null;
156
- return readFileSync(markerPath, 'utf8').trim();
157
- }
158
-
159
- /** Write the sidecar through a sibling temp file, so no reader sees it half-written. */
160
- export function writeManagedMarker(targetPath, provenance) {
161
- const markerPath = `${targetPath}${MANAGED_MARKER_SUFFIX}`;
162
- validateMarkerPath(markerPath);
163
- mkdirSync(dirname(markerPath), { recursive: true });
164
- const tempPath = `${markerPath}${TEMP_PREFIX}${randomUUID()}`;
165
- writeFileSync(tempPath, `${provenance}\n`, 'utf8');
166
- renameSync(tempPath, markerPath);
167
- }
168
-
169
- /** Every file and directory under `rootPath`, as sorted `/`-joined relative paths. */
170
- function listTreeEntries(rootPath) {
171
- const entries = [];
172
- const walk = (dir, prefix) => {
173
- for (const name of readdirSync(dir).sort()) {
174
- const relativePath = prefix === '' ? name : `${prefix}/${name}`;
175
- const stats = lstatSync(join(dir, name));
176
- if (stats.isDirectory()) {
177
- entries.push(`${relativePath}/`);
178
- walk(join(dir, name), relativePath);
179
- } else if (stats.isFile()) {
180
- entries.push(relativePath);
181
- } else {
182
- throw new Error(
183
- `Peaks canonical store cannot read ${join(dir, name)}: not a file or directory`
184
- );
185
- }
186
- }
187
- };
188
- walk(rootPath, '');
189
- return entries;
190
- }
191
-
192
- /** True when `targetPath` already holds exactly the bytes `sourcePath` holds. */
193
- function contentMatches(sourcePath, targetPath) {
194
- const targetStats = getPathStats(targetPath);
195
- if (!targetStats || targetStats.isSymbolicLink()) return false;
196
- if (!targetStats.isDirectory()) {
197
- return targetStats.isFile() && readFileSync(sourcePath).equals(readFileSync(targetPath));
198
- }
199
- const sourceEntries = listTreeEntries(sourcePath);
200
- const targetEntries = listTreeEntries(targetPath);
201
- if (sourceEntries.length !== targetEntries.length) return false;
202
- for (let index = 0; index < sourceEntries.length; index += 1) {
203
- if (sourceEntries[index] !== targetEntries[index]) return false;
204
- if (sourceEntries[index].endsWith('/')) continue;
205
- const from = join(sourcePath, sourceEntries[index]);
206
- const to = join(targetPath, targetEntries[index]);
207
- if (!readFileSync(from).equals(readFileSync(to))) return false;
208
- }
209
- return true;
210
- }
211
-
212
125
  /**
213
126
  * Materialise `sourcePath` as a REAL COPY at `<kindRoot>/<name>`: idempotent by
214
- * content, and REFUSING when the landing path is not ours — an existing entry with
215
- * no marker beside it gets `action: 'unmanaged'` instead of the `rmSync` that used
216
- * to run unconditionally (the `~/.peaks/agents/ecc` shape).
127
+ * content AND by version, and REFUSING when the landing path is not ours — an
128
+ * existing entry with no marker beside it gets `action: 'unmanaged'` instead of
129
+ * the `rmSync` that used to run unconditionally (the `~/.peaks/agents/ecc`
130
+ * shape).
131
+ *
132
+ * THE DECISION, in order:
133
+ *
134
+ * 1. the entry exists and carries NO marker → `unmanaged`. Never overwritten.
135
+ * This is the user's own copy, and it is the protection the whole chain
136
+ * rests on.
137
+ * 2. the entry's RECORDED VERSION is behind the source package's version →
138
+ * refreshed, whatever the bytes say and whatever path the marker names.
139
+ * A copy that cannot name its version (the legacy sidecar) is "version
140
+ * unknown", and unknown is stale: the source package is authoritative.
141
+ * 3. the bytes differ → refreshed.
142
+ * 4. otherwise the copy is current. A marker whose recorded PATH no longer
143
+ * matches is still a stale fact about a current copy, so it is corrected
144
+ * — the bytes are left alone.
145
+ * 5. an entry the store does not hold is `absent`: there is nothing to
146
+ * compare, so it is neither current nor stale.
147
+ *
148
+ * `options.version` is the version of the package that owns `skills/<name>`
149
+ * (`package.json#version` of the install root). Without it there is nothing to
150
+ * compare against and the decision falls back to the bytes alone.
217
151
  *
218
- * @param {{ sourcePath: string, name: string, kind: string, root?: string }} options
152
+ * @param {{ sourcePath: string, name: string, kind: string, root?: string, version?: string, dryRun?: boolean }} options
219
153
  */
220
154
  export function ensureCanonicalCopy(options) {
221
155
  const { sourcePath, name, kind } = options;
156
+ const version =
157
+ typeof options.version === 'string' && options.version.length > 0 ? options.version : null;
158
+ const dryRun = options.dryRun === true;
222
159
  assertAssetName(name, kind);
223
160
  const kindRoot = resolveKindRoot(kind, options);
224
161
  const canonicalPath = join(kindRoot, name);
225
162
 
226
- if (getPathStats(canonicalPath) && !isManagedEntry(canonicalPath)) {
227
- return { canonicalPath, action: 'unmanaged' };
163
+ const exists = getPathStats(canonicalPath) !== null;
164
+ if (exists && !isManagedEntry(canonicalPath)) {
165
+ return { canonicalPath, action: 'unmanaged', state: 'unmanaged', version: null };
228
166
  }
229
- if (contentMatches(sourcePath, canonicalPath)) {
230
- if (readManagedTarget(canonicalPath) !== sourcePath) {
231
- writeManagedMarker(canonicalPath, sourcePath);
167
+
168
+ const marker = readManagedMarker(canonicalPath);
169
+ const recordedVersion = marker?.version ?? null;
170
+ const versionStale = exists && isVersionBehind(recordedVersion, version);
171
+ const bytesMatch = contentMatches(sourcePath, canonicalPath);
172
+
173
+ if (exists && !versionStale && bytesMatch) {
174
+ if (marker?.path !== sourcePath && !dryRun) {
175
+ // The version the copy was made from is kept when the source's version is
176
+ // unknown: a rewrite must not turn a known fact into an unknown one.
177
+ writeManagedMarker(canonicalPath, sourcePath, version ?? recordedVersion);
232
178
  }
233
- return { canonicalPath, action: 'unchanged' };
179
+ return { canonicalPath, action: 'unchanged', state: 'current', version: recordedVersion };
180
+ }
181
+
182
+ // An entry the store does not hold is not stale — it is ABSENT. It is not
183
+ // current either: "current" says the store holds a copy that is not behind,
184
+ // and there is no copy to compare. An entry it holds is stale when its version
185
+ // is behind or its bytes differ.
186
+ const state = exists ? 'stale' : 'absent';
187
+ const reason = versionStale ? 'version' : 'content';
188
+ if (dryRun) {
189
+ return {
190
+ canonicalPath,
191
+ action: 'planned',
192
+ state,
193
+ version: recordedVersion,
194
+ reason: exists ? reason : null
195
+ };
234
196
  }
235
197
 
236
198
  mkdirSync(kindRoot, { recursive: true });
@@ -243,8 +205,14 @@ export function ensureCanonicalCopy(options) {
243
205
  rmSync(tempPath, { recursive: true, force: true });
244
206
  throw error;
245
207
  }
246
- writeManagedMarker(canonicalPath, sourcePath);
247
- return { canonicalPath, action: 'installed' };
208
+ writeManagedMarker(canonicalPath, sourcePath, version);
209
+ return {
210
+ canonicalPath,
211
+ action: 'installed',
212
+ state,
213
+ version,
214
+ reason: exists ? reason : null
215
+ };
248
216
  }
249
217
 
250
218
  /**
@@ -263,7 +231,11 @@ function isOurLink(linkPath, stats) {
263
231
  * link peaks-loop owns is ever replaced; a real directory the user authored is left
264
232
  * alone and reported `skipped`. An `unmanaged` copy is never linked TO either.
265
233
  *
266
- * @param {{ sourcePath: string, name: string, kind: string, linkPath?: string, root?: string }} options
234
+ * With `dryRun`, nothing is written: the copy is planned and the link is
235
+ * reported `planned`, so a caller can show what a repair WOULD do before it
236
+ * does it.
237
+ *
238
+ * @param {{ sourcePath: string, name: string, kind: string, linkPath?: string, root?: string, version?: string, dryRun?: boolean }} options
267
239
  */
268
240
  export function reconcileCanonicalEntry(options) {
269
241
  const { linkPath } = options;
@@ -276,10 +248,16 @@ export function reconcileCanonicalEntry(options) {
276
248
  return { ...copied, linkAction: 'unchanged' };
277
249
  }
278
250
 
279
- let linkAction = 'linked';
280
251
  const current = getPathStats(linkPath);
252
+ if (current && !isOurLink(linkPath, current)) {
253
+ return { ...copied, linkAction: 'skipped' };
254
+ }
255
+ if (options.dryRun === true) {
256
+ return { ...copied, linkAction: 'planned' };
257
+ }
258
+
259
+ let linkAction = 'linked';
281
260
  if (current) {
282
- if (!isOurLink(linkPath, current)) return { ...copied, linkAction: 'skipped' };
283
261
  unlinkSync(linkPath);
284
262
  const markerPath = `${linkPath}${MANAGED_MARKER_SUFFIX}`;
285
263
  if (existsSync(markerPath)) unlinkSync(markerPath);