@aperant/framework 0.6.6 → 0.7.0

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 (150) hide show
  1. package/CHANGELOG.md +215 -0
  2. package/dist/cli/commands/check-version.d.mts.map +1 -1
  3. package/dist/cli/commands/check-version.mjs +76 -1
  4. package/dist/cli/commands/check-version.mjs.map +1 -1
  5. package/dist/cli/commands/ci-watch.d.mts.map +1 -1
  6. package/dist/cli/commands/ci-watch.mjs +73 -5
  7. package/dist/cli/commands/ci-watch.mjs.map +1 -1
  8. package/dist/cli/commands/health-check.mjs +1 -1
  9. package/dist/cli/commands/health-check.mjs.map +1 -1
  10. package/dist/cli/commands/init.d.mts +17 -1
  11. package/dist/cli/commands/init.d.mts.map +1 -1
  12. package/dist/cli/commands/init.mjs +183 -11
  13. package/dist/cli/commands/init.mjs.map +1 -1
  14. package/dist/cli/commands/release-notes.d.mts +11 -0
  15. package/dist/cli/commands/release-notes.d.mts.map +1 -0
  16. package/dist/cli/commands/release-notes.mjs +173 -0
  17. package/dist/cli/commands/release-notes.mjs.map +1 -0
  18. package/dist/cli/commands/route.d.mts.map +1 -1
  19. package/dist/cli/commands/route.mjs +37 -2
  20. package/dist/cli/commands/route.mjs.map +1 -1
  21. package/dist/cli/commands/task.d.mts.map +1 -1
  22. package/dist/cli/commands/task.mjs +48 -0
  23. package/dist/cli/commands/task.mjs.map +1 -1
  24. package/dist/cli/config/load.d.mts +14 -0
  25. package/dist/cli/config/load.d.mts.map +1 -1
  26. package/dist/cli/config/load.mjs +40 -0
  27. package/dist/cli/config/load.mjs.map +1 -1
  28. package/dist/cli/config/upgrade-gitignore.d.mts.map +1 -1
  29. package/dist/cli/config/upgrade-gitignore.mjs +6 -0
  30. package/dist/cli/config/upgrade-gitignore.mjs.map +1 -1
  31. package/dist/cli/consistency/parse-review.d.mts.map +1 -1
  32. package/dist/cli/consistency/parse-review.mjs +4 -1
  33. package/dist/cli/consistency/parse-review.mjs.map +1 -1
  34. package/dist/cli/dispatch.d.mts.map +1 -1
  35. package/dist/cli/dispatch.mjs +2 -0
  36. package/dist/cli/dispatch.mjs.map +1 -1
  37. package/dist/cli/gate/gates/review-clean.d.mts.map +1 -1
  38. package/dist/cli/gate/gates/review-clean.mjs +4 -2
  39. package/dist/cli/gate/gates/review-clean.mjs.map +1 -1
  40. package/dist/cli/help.d.mts.map +1 -1
  41. package/dist/cli/help.mjs +1 -0
  42. package/dist/cli/help.mjs.map +1 -1
  43. package/dist/cli/host/detect.d.mts +122 -9
  44. package/dist/cli/host/detect.d.mts.map +1 -1
  45. package/dist/cli/host/detect.mjs +132 -0
  46. package/dist/cli/host/detect.mjs.map +1 -1
  47. package/dist/cli/install/legacy-paths.d.mts +38 -0
  48. package/dist/cli/install/legacy-paths.d.mts.map +1 -0
  49. package/dist/cli/install/legacy-paths.mjs +69 -0
  50. package/dist/cli/install/legacy-paths.mjs.map +1 -0
  51. package/dist/cli/install/runtime-migrate.d.mts +84 -0
  52. package/dist/cli/install/runtime-migrate.d.mts.map +1 -0
  53. package/dist/cli/install/runtime-migrate.mjs +244 -0
  54. package/dist/cli/install/runtime-migrate.mjs.map +1 -0
  55. package/dist/cli/install/update-chips.d.mts +23 -0
  56. package/dist/cli/install/update-chips.d.mts.map +1 -1
  57. package/dist/cli/install/update-chips.mjs +60 -0
  58. package/dist/cli/install/update-chips.mjs.map +1 -1
  59. package/dist/cli/release-notes/compile.d.mts +38 -0
  60. package/dist/cli/release-notes/compile.d.mts.map +1 -0
  61. package/dist/cli/release-notes/compile.mjs +244 -0
  62. package/dist/cli/release-notes/compile.mjs.map +1 -0
  63. package/dist/cli/release-notes/draft.d.mts +73 -0
  64. package/dist/cli/release-notes/draft.d.mts.map +1 -0
  65. package/dist/cli/release-notes/draft.mjs +120 -0
  66. package/dist/cli/release-notes/draft.mjs.map +1 -0
  67. package/dist/cli/release-notes/output-dir.d.mts +20 -0
  68. package/dist/cli/release-notes/output-dir.d.mts.map +1 -0
  69. package/dist/cli/release-notes/output-dir.mjs +42 -0
  70. package/dist/cli/release-notes/output-dir.mjs.map +1 -0
  71. package/dist/cli/release-notes/persona-filter.d.mts +51 -0
  72. package/dist/cli/release-notes/persona-filter.d.mts.map +1 -0
  73. package/dist/cli/release-notes/persona-filter.mjs +127 -0
  74. package/dist/cli/release-notes/persona-filter.mjs.map +1 -0
  75. package/dist/cli/release-notes/publish.d.mts +23 -0
  76. package/dist/cli/release-notes/publish.d.mts.map +1 -0
  77. package/dist/cli/release-notes/publish.mjs +125 -0
  78. package/dist/cli/release-notes/publish.mjs.map +1 -0
  79. package/dist/cli/release-notes/ship-autodraft.d.mts +37 -0
  80. package/dist/cli/release-notes/ship-autodraft.d.mts.map +1 -0
  81. package/dist/cli/release-notes/ship-autodraft.mjs +97 -0
  82. package/dist/cli/release-notes/ship-autodraft.mjs.map +1 -0
  83. package/dist/cli/route/drift-detect.d.mts +20 -0
  84. package/dist/cli/route/drift-detect.d.mts.map +1 -0
  85. package/dist/cli/route/drift-detect.mjs +107 -0
  86. package/dist/cli/route/drift-detect.mjs.map +1 -0
  87. package/dist/cli/util/aperant-section.d.mts +34 -0
  88. package/dist/cli/util/aperant-section.d.mts.map +1 -0
  89. package/dist/cli/util/aperant-section.mjs +127 -0
  90. package/dist/cli/util/aperant-section.mjs.map +1 -0
  91. package/dist/cli/util/copy.d.mts +28 -1
  92. package/dist/cli/util/copy.d.mts.map +1 -1
  93. package/dist/cli/util/copy.mjs +43 -55
  94. package/dist/cli/util/copy.mjs.map +1 -1
  95. package/dist/cli/util/semver.d.mts +17 -0
  96. package/dist/cli/util/semver.d.mts.map +1 -0
  97. package/dist/cli/util/semver.mjs +29 -0
  98. package/dist/cli/util/semver.mjs.map +1 -0
  99. package/dist/cli/util/skill-installs.d.mts +65 -9
  100. package/dist/cli/util/skill-installs.d.mts.map +1 -1
  101. package/dist/cli/util/skill-installs.mjs +130 -21
  102. package/dist/cli/util/skill-installs.mjs.map +1 -1
  103. package/dist/cli/util/version-preflight.d.mts +44 -0
  104. package/dist/cli/util/version-preflight.d.mts.map +1 -0
  105. package/dist/cli/util/version-preflight.mjs +66 -0
  106. package/dist/cli/util/version-preflight.mjs.map +1 -0
  107. package/dist/types/config.d.ts +11 -7
  108. package/dist/types/config.d.ts.map +1 -1
  109. package/package.json +133 -133
  110. package/skills/apt-close-task/SKILL.md +30 -0
  111. package/skills/apt-diagram/SKILL.md +45 -9
  112. package/skills/apt-release-notes/SKILL.md +193 -0
  113. package/skills/apt-release-notes/appendices/persona-voice.md +59 -0
  114. package/skills/apt-setup/SKILL.md +146 -3
  115. package/skills/apt-ship/SKILL.md +63 -4
  116. package/skills/apt-spar/SKILL.md +36 -11
  117. package/skills/apt-update/SKILL.md +77 -10
  118. package/skills/apt-watch-ci/SKILL.md +6 -3
  119. package/src/cli/commands/check-version.mjs +73 -1
  120. package/src/cli/commands/ci-watch.mjs +74 -5
  121. package/src/cli/commands/health-check.mjs +1 -1
  122. package/src/cli/commands/init.mjs +202 -10
  123. package/src/cli/commands/release-notes.mjs +187 -0
  124. package/src/cli/commands/route.mjs +38 -2
  125. package/src/cli/commands/task.mjs +49 -0
  126. package/src/cli/config/load.mjs +37 -0
  127. package/src/cli/config/upgrade-gitignore.mjs +6 -0
  128. package/src/cli/consistency/parse-review.mjs +3 -1
  129. package/src/cli/dispatch.mjs +2 -0
  130. package/src/cli/gate/gates/review-clean.mjs +4 -2
  131. package/src/cli/help.mjs +1 -0
  132. package/src/cli/host/detect.mjs +135 -0
  133. package/src/cli/install/legacy-paths.mjs +69 -0
  134. package/src/cli/install/runtime-migrate.mjs +252 -0
  135. package/src/cli/install/update-chips.mjs +57 -0
  136. package/src/cli/release-notes/compile.mjs +261 -0
  137. package/src/cli/release-notes/draft.mjs +133 -0
  138. package/src/cli/release-notes/output-dir.mjs +52 -0
  139. package/src/cli/release-notes/persona-filter.mjs +126 -0
  140. package/src/cli/release-notes/publish.mjs +128 -0
  141. package/src/cli/release-notes/ship-autodraft.mjs +106 -0
  142. package/src/cli/route/drift-detect.mjs +107 -0
  143. package/src/cli/util/aperant-section.mjs +136 -0
  144. package/src/cli/util/copy.mjs +43 -56
  145. package/src/cli/util/semver.mjs +28 -0
  146. package/src/cli/util/skill-installs.mjs +134 -21
  147. package/src/cli/util/version-preflight.mjs +65 -0
  148. package/templates/aperant-claude-md-appendix.md +37 -0
  149. package/templates/config.json +28 -3
  150. package/workflows/docs.md +12 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * install/runtime-migrate.mjs — at-install cleanup of legacy install
3
+ * trees the framework no longer owns (FRAMEWORK-BUG-021).
4
+ *
5
+ * Codex was originally installed into `.agents/skills/` (commit 1a8dd8a8)
6
+ * and later moved to `.codex/`. Projects that upgraded across that move
7
+ * end up with a stale `.agents/skills/` tree that:
8
+ *
9
+ * - keeps `.apt-version` on disk → the legacy fallback in
10
+ * `readSkillInstallState` reports a stale codex install.
11
+ * - shows up in `health-check` as `stale-skills`.
12
+ * - leaves dozens of orphaned SKILL.md files the runtime no longer
13
+ * reads.
14
+ *
15
+ * `runLegacyCleanup` runs once per `apt-tools init` when codex is in the
16
+ * requested runtime set. It is conservative by default:
17
+ *
18
+ * - Only files listed in `LEGACY_INSTALL_PATHS.codex.framework_files`
19
+ * are removed. User-added skill directories (`my-skill/`, …) are
20
+ * preserved. If anything beyond the known framework set remains,
21
+ * `retained[]` lists those paths.
22
+ * - A present-and-current `apt-file-manifest.json` is treated as the
23
+ * authoritative "this is a managed install, leave it alone" signal:
24
+ * the function no-ops with `reason: 'managed'`.
25
+ * - The caller can suppress cleanup entirely via `--keep-legacy` at the
26
+ * init.mjs site; the function itself is dumb about flags.
27
+ */
28
+
29
+ import { existsSync, readdirSync, rmdirSync, unlinkSync } from 'node:fs'
30
+ import { dirname, join } from 'node:path'
31
+ import { LEGACY_INSTALL_PATHS } from './legacy-paths.mjs'
32
+ import { MANIFEST_FILENAME } from './manifest.mjs'
33
+
34
+ /**
35
+ * @typedef {Object} LegacyCodexDetection
36
+ * @property {boolean} present True when `.agents/skills/` exists.
37
+ * @property {string[]} frameworkFiles Subset of `framework_files` that
38
+ * actually exist on disk (relative
39
+ * to install_root).
40
+ * @property {string[]} userFiles Everything else under
41
+ * install_root (relative to
42
+ * install_root). May include both
43
+ * files and directories. Drives the
44
+ * `retained[]` warning.
45
+ * @property {boolean} hasAptVersion Whether the legacy `.apt-version`
46
+ * stamp is present.
47
+ * @property {boolean} hasManifest Whether an
48
+ * `apt-file-manifest.json` is
49
+ * present at install_root (signals
50
+ * a managed install — cleanup
51
+ * should no-op).
52
+ */
53
+
54
+ const LEGACY = LEGACY_INSTALL_PATHS.codex
55
+
56
+ /**
57
+ * Recursively enumerate every file path under `dir`, returning paths
58
+ * relative to `dir`. Used to compute the "user files" set (anything not
59
+ * in the framework_files list).
60
+ *
61
+ * Returns [] when the dir doesn't exist. Swallows per-entry errors so a
62
+ * single unreadable symlink doesn't abort detection.
63
+ *
64
+ * @param {string} dir
65
+ * @returns {string[]}
66
+ */
67
+ function walkRelative(dir) {
68
+ /** @type {string[]} */
69
+ const out = []
70
+ if (!existsSync(dir)) return out
71
+ /** @param {string} current @param {string} rel */
72
+ const visit = (current, rel) => {
73
+ let entries
74
+ try {
75
+ entries = readdirSync(current, { withFileTypes: true })
76
+ } catch {
77
+ return
78
+ }
79
+ for (const entry of entries) {
80
+ const childPath = join(current, entry.name)
81
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name
82
+ if (entry.isDirectory()) {
83
+ visit(childPath, childRel)
84
+ } else if (entry.isFile()) {
85
+ out.push(childRel)
86
+ }
87
+ // Symlinks / other entry types are intentionally ignored — the
88
+ // framework only ever writes regular files.
89
+ }
90
+ }
91
+ visit(dir, '')
92
+ return out
93
+ }
94
+
95
+ /**
96
+ * Probe the codex legacy install tree at `<targetDir>/.agents/skills/`.
97
+ *
98
+ * @param {string} targetDir
99
+ * @returns {LegacyCodexDetection}
100
+ */
101
+ export function detectLegacyCodexTree(targetDir) {
102
+ const installRoot = join(targetDir, LEGACY.install_root)
103
+ if (!existsSync(installRoot)) {
104
+ return {
105
+ present: false,
106
+ frameworkFiles: [],
107
+ userFiles: [],
108
+ hasAptVersion: false,
109
+ hasManifest: false,
110
+ }
111
+ }
112
+
113
+ const onDisk = walkRelative(installRoot)
114
+ const frameworkSet = new Set(LEGACY.framework_files)
115
+ const frameworkFiles = onDisk.filter((p) => frameworkSet.has(p))
116
+ const userFiles = onDisk.filter((p) => !frameworkSet.has(p) && p !== MANIFEST_FILENAME)
117
+
118
+ return {
119
+ present: true,
120
+ frameworkFiles,
121
+ userFiles,
122
+ hasAptVersion: onDisk.includes('.apt-version'),
123
+ hasManifest: onDisk.includes(MANIFEST_FILENAME),
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Try to remove a directory if it is empty. Swallows ENOTEMPTY / ENOENT
129
+ * so the caller can blindly sweep candidate dirs in any order.
130
+ *
131
+ * @param {string} dir
132
+ * @returns {boolean} true iff the dir was actually removed.
133
+ */
134
+ function rmEmptyDir(dir) {
135
+ if (!existsSync(dir)) return false
136
+ try {
137
+ rmdirSync(dir)
138
+ return true
139
+ } catch {
140
+ return false
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Clean up the legacy `.agents/skills/` tree if it looks orphaned.
146
+ *
147
+ * Branches:
148
+ * 1. `present: false` OR `frameworkFiles.length === 0` → no-op,
149
+ * `{ ran: false, reason: 'no-legacy' }`.
150
+ * 2. `hasManifest: true` → managed install, no-op,
151
+ * `{ ran: false, reason: 'managed' }`.
152
+ * 3. Otherwise: per-file `unlinkSync` each framework-owned file;
153
+ * `rmdirSync` any now-empty `apt-*` subdirectory; sweep
154
+ * `.agents/skills/` only if it is empty; sweep `.agents/` only if
155
+ * its `skills/` got removed and `.agents/` is empty.
156
+ *
157
+ * Returns `{ ran: true, removed, retained, rmdirs }` on the cleanup
158
+ * branch:
159
+ * - `removed` — relative paths under `install_root` that were unlinked.
160
+ * - `retained` — relative paths under `install_root` that were NOT
161
+ * removed (user-added skills / files not in the legacy set).
162
+ * - `rmdirs` — absolute paths of directories that were removed
163
+ * (apt-* subdirs, the install_root itself, .agents/), in removal order.
164
+ *
165
+ * Atomicity: per-file unlink is non-atomic. A partial-failure scenario
166
+ * (process killed mid-loop) is tolerable — the next `init` run will
167
+ * re-detect the remaining framework files and finish the sweep.
168
+ *
169
+ * @param {{ targetDir: string, dryRun?: boolean }} args
170
+ * @returns {
171
+ * | { ran: false, reason: 'no-legacy' | 'managed' }
172
+ * | { ran: true, removed: string[], retained: string[], rmdirs: string[] }
173
+ * }
174
+ */
175
+ export function runLegacyCleanup({ targetDir, dryRun = false }) {
176
+ const detection = detectLegacyCodexTree(targetDir)
177
+
178
+ if (!detection.present || detection.frameworkFiles.length === 0) {
179
+ return { ran: false, reason: 'no-legacy' }
180
+ }
181
+ if (detection.hasManifest) {
182
+ return { ran: false, reason: 'managed' }
183
+ }
184
+
185
+ const installRoot = join(targetDir, LEGACY.install_root)
186
+ const removed = []
187
+ const rmdirs = []
188
+
189
+ if (dryRun) {
190
+ // Dry-run: report what WOULD be removed without touching the filesystem.
191
+ // `retained` is the user-file set from the pre-walk (no sweep occurred).
192
+ // `rmdirs` is the set of apt-* subdirs that would become empty after removal.
193
+ const wouldRemove = detection.frameworkFiles
194
+ const retained = detection.userFiles
195
+ const candidateDirs = new Set()
196
+ for (const rel of wouldRemove) {
197
+ let parent = dirname(rel)
198
+ while (parent !== '.' && parent !== '') {
199
+ candidateDirs.add(parent)
200
+ parent = dirname(parent)
201
+ }
202
+ }
203
+ const wouldRmdirs = [...candidateDirs]
204
+ .sort((a, b) => b.length - a.length)
205
+ .map((rel) => join(installRoot, rel))
206
+ return { ran: true, dryRun: true, removed: wouldRemove, retained, rmdirs: wouldRmdirs }
207
+ }
208
+
209
+ for (const rel of detection.frameworkFiles) {
210
+ const abs = join(installRoot, rel)
211
+ try {
212
+ unlinkSync(abs)
213
+ removed.push(rel)
214
+ } catch {
215
+ /* best-effort: leave a partial sweep; next run finishes it */
216
+ }
217
+ }
218
+
219
+ // Sweep any now-empty `apt-*/` subdirs the unlinks left behind.
220
+ // Walk parent dirs of every removed file in reverse-depth order so
221
+ // nested `apt-pr-review/prompts/` empties before `apt-pr-review/`.
222
+ const candidateDirs = new Set()
223
+ for (const rel of removed) {
224
+ let parent = dirname(rel)
225
+ while (parent !== '.' && parent !== '') {
226
+ candidateDirs.add(parent)
227
+ parent = dirname(parent)
228
+ }
229
+ }
230
+ const sortedDirs = [...candidateDirs].sort((a, b) => b.length - a.length)
231
+ for (const rel of sortedDirs) {
232
+ const abs = join(installRoot, rel)
233
+ if (rmEmptyDir(abs)) rmdirs.push(abs)
234
+ }
235
+
236
+ // Sweep `.agents/skills/` only if fully empty after the per-file
237
+ // pass — preserves any user-added skill dirs.
238
+ if (rmEmptyDir(installRoot)) {
239
+ rmdirs.push(installRoot)
240
+ // Sweep `.agents/` only if it became empty too (i.e. no other
241
+ // `.agents/<sibling>` content the user keeps there).
242
+ const agentsRoot = dirname(installRoot)
243
+ if (rmEmptyDir(agentsRoot)) rmdirs.push(agentsRoot)
244
+ }
245
+
246
+ // Use the pre-walk's userFiles as `retained` — the post-walk only existed
247
+ // to defensively re-scan, but pre-walk already captured user files accurately.
248
+ // (PRF-002: avoid redundant detectLegacyCodexTree call.)
249
+ const retained = detection.userFiles
250
+
251
+ return { ran: true, removed, retained, rmdirs }
252
+ }
@@ -60,6 +60,63 @@ export function readUpdateCache() {
60
60
  }
61
61
  }
62
62
 
63
+ /** Semver-shape pattern: MAJOR.MINOR.PATCH with optional pre-release and build metadata. */
64
+ const SEMVER_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
65
+
66
+ /**
67
+ * Read the worker's cache file with TTL and schema validation. Returns
68
+ * `{ fresh: true, cache }` when the cache exists, parses, declares
69
+ * `schema_version === 1`, and was written within `ttlMs` milliseconds.
70
+ * Returns `{ fresh: false }` when missing, stale, or schema mismatch.
71
+ *
72
+ * Security: `latest_version` and `installed_version` inside
73
+ * `cache.framework` are validated as semver strings. Invalid values are
74
+ * dropped (set to null) so they never propagate into shell-interpolated
75
+ * contexts.
76
+ *
77
+ * ENOENT and JSON parse errors stay silent (expected when the cache is
78
+ * missing or being rewritten). Unexpected errors are logged to stderr.
79
+ *
80
+ * @param {number} ttlMs Maximum age in milliseconds before cache is treated as stale.
81
+ * @returns {{ fresh: true, cache: Record<string, unknown> } | { fresh: false }}
82
+ */
83
+ export function readFreshUpdateCache(ttlMs) {
84
+ const path = updateCachePath()
85
+ if (!existsSync(path)) return { fresh: false }
86
+ let data
87
+ try {
88
+ data = JSON.parse(readFileSync(path, 'utf-8'))
89
+ } catch (err) {
90
+ // SyntaxError = malformed JSON (expected); anything else is unexpected.
91
+ if (!(err instanceof SyntaxError)) {
92
+ console.error('[update-cache] read failed:', err.message)
93
+ }
94
+ return { fresh: false }
95
+ }
96
+ try {
97
+ if (!data || typeof data !== 'object') return { fresh: false }
98
+ if (data.schema_version !== 1) return { fresh: false }
99
+ if (typeof data.checked_at !== 'string') return { fresh: false }
100
+ const age = Date.now() - new Date(data.checked_at).getTime()
101
+ if (!Number.isFinite(age) || age < 0 || age >= ttlMs) return { fresh: false }
102
+ // Validate semver fields in framework block — reject non-semver strings.
103
+ const fw = data.framework && typeof data.framework === 'object' ? data.framework : {}
104
+ const sanitized = { ...data, framework: { ...fw } }
105
+ for (const field of ['latest_version', 'installed_version']) {
106
+ if (
107
+ typeof sanitized.framework[field] === 'string' &&
108
+ !SEMVER_RE.test(sanitized.framework[field])
109
+ ) {
110
+ sanitized.framework[field] = null
111
+ }
112
+ }
113
+ return { fresh: true, cache: sanitized }
114
+ } catch (err) {
115
+ console.error('[update-cache] read failed:', err.message)
116
+ return { fresh: false }
117
+ }
118
+ }
119
+
63
120
  /**
64
121
  * Build the chip string array for a given cache. Empty array when there
65
122
  * are no chips to show. Order: stale_files first (most urgent), then
@@ -0,0 +1,261 @@
1
+ /**
2
+ * release-notes/compile.mjs — tag-time narrative compiler.
3
+ *
4
+ * Reads every `<output_dir>/_unreleased/PR-*.md` fragment, classifies each
5
+ * against the project's persona roster + filter mode, and writes
6
+ * `<output_dir>/<tag>.md`. Atomic-rename pattern: the fragments dir is
7
+ * cleared only AFTER the compiled file lands on disk, so a crash mid-write
8
+ * cannot orphan fragments without their compiled output.
9
+ *
10
+ * Non-negotiable invariant (ID-6): unmapped fragments (no persona tag, or
11
+ * a tag the roster doesn't recognize) MUST appear in a `## Needs Triage`
12
+ * section. Never silent-drop. The triage section is the human curator's
13
+ * safety net — its presence is asserted by TD-3.
14
+ */
15
+
16
+ import { existsSync, readdirSync, readFileSync, rmSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+
19
+ import { loadProjectConfig } from '../config/load.mjs'
20
+ import { readPersonas } from '../personas/sidecar.mjs'
21
+ import { atomicWriteText } from '../util/atomic-write.mjs'
22
+ import { resolveOutputDir, validateTag } from './output-dir.mjs'
23
+ import { buildPersonaTierMap, classifyFragment, isNoneSentinel } from './persona-filter.mjs'
24
+
25
+ const VALID_MODES = new Set(['primary', 'primary+secondary', 'all'])
26
+
27
+ /** Pre-compiled at module level to avoid recompilation in the sort comparator (PRF-001). */
28
+ const PR_FILENAME_RE = /^PR-(\d+)\.md$/
29
+
30
+ /**
31
+ * Parse a single fragment file. Tolerant: missing keys default to empty
32
+ * strings; the body after `## Release note` is read verbatim.
33
+ *
34
+ * @param {string} text
35
+ * @returns {{ pr: string, date: string, persona: string, note: string, raw: string }}
36
+ */
37
+ function parseFragment(text) {
38
+ const lines = text.split('\n')
39
+ let pr = ''
40
+ let date = ''
41
+ let persona = ''
42
+ let note = ''
43
+ let noteStart = -1
44
+ for (let i = 0; i < lines.length; i++) {
45
+ const line = lines[i]
46
+ if (line.startsWith('pr: ')) pr = line.slice(4).trim()
47
+ else if (line.startsWith('date: ')) date = line.slice(6).trim()
48
+ else if (line.startsWith('persona: ')) persona = line.slice(9).trim()
49
+ else if (line.startsWith('## Release note')) {
50
+ noteStart = i
51
+ break
52
+ }
53
+ }
54
+ if (noteStart >= 0) {
55
+ note = lines
56
+ .slice(noteStart + 1)
57
+ .join('\n')
58
+ .trim()
59
+ }
60
+ return { pr, date, persona, note, raw: text }
61
+ }
62
+
63
+ /**
64
+ * Resolve the output dir and persona filter mode from config + flag override.
65
+ *
66
+ * @param {string} projectDir
67
+ * @param {string | null} flagOverride
68
+ * @returns {{ outputDir: string, personaFilter: 'primary' | 'primary+secondary' | 'all' }}
69
+ */
70
+ function resolveContext(projectDir, flagOverride) {
71
+ const config = loadProjectConfig(projectDir)
72
+ const outputDir = resolveOutputDir(projectDir, flagOverride)
73
+ const filterRaw = config?.changelog?.release_notes?.persona_filter
74
+ const personaFilter =
75
+ typeof filterRaw === 'string' && VALID_MODES.has(filterRaw)
76
+ ? /** @type {'primary' | 'primary+secondary' | 'all'} */ (filterRaw)
77
+ : 'primary+secondary'
78
+ return { outputDir, personaFilter }
79
+ }
80
+
81
+ /**
82
+ * @typedef {Object} CompileInput
83
+ * @property {string} projectDir
84
+ * @property {string} tag
85
+ * @property {string | null} outputDir
86
+ */
87
+
88
+ /**
89
+ * @typedef {Object} CompileResult
90
+ * @property {boolean} written
91
+ * @property {string} path
92
+ * @property {number} fragmentsTotal
93
+ * @property {number} fragmentsInBody
94
+ * @property {number} fragmentsInTriage
95
+ * @property {number} fragmentsFiltered
96
+ * @property {boolean} clearedUnreleased
97
+ */
98
+
99
+ /**
100
+ * Compile every `_unreleased/PR-*.md` fragment into `<output_dir>/<tag>.md`.
101
+ *
102
+ * @param {CompileInput} input
103
+ * @returns {CompileResult}
104
+ */
105
+ export function compileTag(input) {
106
+ validateTag(input.tag)
107
+ const { outputDir, personaFilter } = resolveContext(input.projectDir, input.outputDir)
108
+ const fragmentsDir = join(outputDir, '_unreleased')
109
+ const targetPath = join(outputDir, `${input.tag}.md`)
110
+
111
+ const rawFiles = existsSync(fragmentsDir)
112
+ ? readdirSync(fragmentsDir).filter((f) => PR_FILENAME_RE.test(f))
113
+ : []
114
+ // Pre-compute PR numbers once to avoid re-running the regex in the comparator (PRF-001).
115
+ const withNumbers = rawFiles.map((f) => ({
116
+ f,
117
+ n: Number.parseInt(PR_FILENAME_RE.exec(f)?.[1] ?? '0', 10),
118
+ }))
119
+ withNumbers.sort((a, b) => a.n - b.n)
120
+ const fragments = withNumbers.map(({ f }) => ({
121
+ filename: f,
122
+ ...parseFragment(readFileSync(join(fragmentsDir, f), 'utf-8')),
123
+ }))
124
+
125
+ const personasEnvelope = readPersonas(input.projectDir)
126
+ const tierMap = buildPersonaTierMap(personasEnvelope)
127
+
128
+ /** @type {Array<{ pr: string, date: string, persona: string, note: string, tier: 'primary' | 'secondary' | 'tertiary' }>} */
129
+ const bodyEntries = []
130
+ /** @type {Array<{ pr: string, date: string, persona: string, note: string, reason: string }>} */
131
+ const triageEntries = []
132
+ let filteredCount = 0
133
+
134
+ for (const frag of fragments) {
135
+ const { bucket, resolvedTier } = classifyFragment(frag.persona, tierMap, personaFilter)
136
+ if (bucket === 'body' && resolvedTier !== null && resolvedTier !== 'unknown') {
137
+ bodyEntries.push({
138
+ pr: frag.pr,
139
+ date: frag.date,
140
+ persona: frag.persona,
141
+ note: frag.note,
142
+ tier: resolvedTier,
143
+ })
144
+ } else if (bucket === 'triage' || resolvedTier === 'unknown') {
145
+ // Use the shared sentinel predicate so this label stays in lockstep
146
+ // with persona-filter.mjs's NONE_SENTINELS set. Without it, the
147
+ // classifier and labeller drift (e.g. literal "null" persona tags
148
+ // land in triage as 'unknown-persona' instead of 'no-persona-tag').
149
+ // 'unknown' tier (malformed tier value in personas.json) is also
150
+ // routed here — never silent-drop (ID-6 / LOG-001).
151
+ const reason = isNoneSentinel(frag.persona)
152
+ ? 'no-persona-tag'
153
+ : resolvedTier === 'unknown'
154
+ ? 'unknown-tier'
155
+ : 'unknown-persona'
156
+ triageEntries.push({
157
+ pr: frag.pr,
158
+ date: frag.date,
159
+ persona: frag.persona,
160
+ note: frag.note,
161
+ reason,
162
+ })
163
+ } else {
164
+ filteredCount++
165
+ }
166
+ }
167
+
168
+ const compiled = renderCompiled({
169
+ tag: input.tag,
170
+ body: bodyEntries,
171
+ triage: triageEntries,
172
+ filter: personaFilter,
173
+ })
174
+
175
+ atomicWriteText(targetPath, compiled)
176
+
177
+ // Clear _unreleased only AFTER the compiled file is durably written.
178
+ let clearedUnreleased = false
179
+ if (existsSync(fragmentsDir) && fragments.length > 0) {
180
+ for (const frag of fragments) {
181
+ rmSync(join(fragmentsDir, frag.filename), { force: true })
182
+ }
183
+ clearedUnreleased = true
184
+ }
185
+
186
+ return {
187
+ written: true,
188
+ path: targetPath,
189
+ fragmentsTotal: fragments.length,
190
+ fragmentsInBody: bodyEntries.length,
191
+ fragmentsInTriage: triageEntries.length,
192
+ fragmentsFiltered: filteredCount,
193
+ clearedUnreleased,
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Render the per-tag compiled body.
199
+ *
200
+ * Layout:
201
+ * # Release <tag>
202
+ *
203
+ * (per-tier sections — primary first, then secondary, then tertiary
204
+ * when filter==='all'. Each section's entries sorted by PR number.)
205
+ *
206
+ * ## Needs Triage (only when triage[] non-empty)
207
+ *
208
+ * @param {{
209
+ * tag: string,
210
+ * body: Array<{ pr: string, date: string, persona: string, note: string, tier: 'primary' | 'secondary' | 'tertiary' }>,
211
+ * triage: Array<{ pr: string, date: string, persona: string, note: string, reason: string }>,
212
+ * filter: 'primary' | 'primary+secondary' | 'all',
213
+ * }} input
214
+ * @returns {string}
215
+ */
216
+ function renderCompiled(input) {
217
+ const lines = []
218
+ lines.push(`# Release ${input.tag}`)
219
+ lines.push('')
220
+ lines.push(`<!-- persona_filter: ${input.filter} -->`)
221
+ lines.push('')
222
+
223
+ const tiersInOrder = /** @type {const} */ (['primary', 'secondary', 'tertiary'])
224
+ for (const tier of tiersInOrder) {
225
+ const rows = input.body.filter((e) => e.tier === tier)
226
+ if (rows.length === 0) continue
227
+ lines.push(`## ${capitalize(tier)} personas`)
228
+ lines.push('')
229
+ for (const row of rows) {
230
+ lines.push(`- **PR #${row.pr}** (${row.persona}): ${row.note}`)
231
+ }
232
+ lines.push('')
233
+ }
234
+
235
+ if (input.triage.length > 0) {
236
+ lines.push('## Needs Triage')
237
+ lines.push('')
238
+ lines.push('_These fragments lack a recognized persona tag. Curate before publishing._')
239
+ lines.push('')
240
+ for (const row of input.triage) {
241
+ const personaLabel = row.persona && row.persona !== '(none)' ? row.persona : '(no tag)'
242
+ lines.push(`- **PR #${row.pr}** (${personaLabel}, ${row.reason}): ${row.note}`)
243
+ }
244
+ lines.push('')
245
+ }
246
+
247
+ if (input.body.length === 0 && input.triage.length === 0) {
248
+ lines.push('_No fragments to compile._')
249
+ lines.push('')
250
+ }
251
+
252
+ return lines.join('\n')
253
+ }
254
+
255
+ /**
256
+ * @param {string} s
257
+ * @returns {string}
258
+ */
259
+ function capitalize(s) {
260
+ return s.length === 0 ? s : s[0].toUpperCase() + s.slice(1)
261
+ }