doctrina-cli 0.13.0 → 0.15.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 (71) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/commands/adapter.js +205 -0
  4. package/src/commands/analyze.js +120 -17
  5. package/src/commands/change.js +100 -42
  6. package/src/commands/clarify.js +8 -1
  7. package/src/commands/close.js +57 -2
  8. package/src/commands/completion.js +6 -0
  9. package/src/commands/constitution.js +8 -1
  10. package/src/commands/context.js +391 -58
  11. package/src/commands/contract.js +76 -43
  12. package/src/commands/coverage.js +126 -12
  13. package/src/commands/decision.js +172 -40
  14. package/src/commands/doctor.js +92 -11
  15. package/src/commands/handoff.js +8 -1
  16. package/src/commands/hooks.js +6 -0
  17. package/src/commands/index-rebuild.js +8 -1
  18. package/src/commands/init.js +139 -6
  19. package/src/commands/intake.js +11 -2
  20. package/src/commands/intent.js +8 -1
  21. package/src/commands/metrics.js +80 -7
  22. package/src/commands/next.js +38 -3
  23. package/src/commands/prime.js +8 -1
  24. package/src/commands/report.js +8 -1
  25. package/src/commands/review.js +8 -1
  26. package/src/commands/search.js +8 -1
  27. package/src/commands/show.js +8 -1
  28. package/src/commands/skill.js +201 -8
  29. package/src/commands/spec.js +13 -6
  30. package/src/commands/status.js +14 -2
  31. package/src/commands/templates.js +193 -59
  32. package/src/commands/trace.js +15 -3
  33. package/src/commands/triage.js +248 -0
  34. package/src/commands/upgrade.js +8 -1
  35. package/src/commands/validate.js +148 -5
  36. package/src/commands/verify.js +126 -5
  37. package/src/commands/watch.js +8 -1
  38. package/src/commands/why.js +10 -24
  39. package/src/commands/work.js +44 -3
  40. package/src/index.js +61 -6
  41. package/src/lib/adapters.js +140 -0
  42. package/src/lib/adr-guard.js +1 -0
  43. package/src/lib/args.js +10 -0
  44. package/src/lib/clarity.js +1 -0
  45. package/src/lib/colors.js +1 -0
  46. package/src/lib/commands.js +252 -27
  47. package/src/lib/criteria.js +1 -0
  48. package/src/lib/dates.js +1 -0
  49. package/src/lib/diff.js +1 -0
  50. package/src/lib/doc-model.js +287 -0
  51. package/src/lib/docs-impact.js +167 -0
  52. package/src/lib/ears.js +1 -0
  53. package/src/lib/exit-codes.js +103 -0
  54. package/src/lib/flag-catalog.js +106 -0
  55. package/src/lib/fs-ops.js +1 -0
  56. package/src/lib/gates.js +123 -0
  57. package/src/lib/git.js +97 -0
  58. package/src/lib/index-json.js +14 -6
  59. package/src/lib/json-out.js +83 -0
  60. package/src/lib/pipeline.js +161 -0
  61. package/src/lib/prompt.js +18 -1
  62. package/src/lib/runtime.js +683 -0
  63. package/src/lib/scan.js +81 -33
  64. package/src/lib/spec-ops.js +94 -9
  65. package/src/lib/suggest.js +1 -0
  66. package/src/lib/templates.js +89 -0
  67. package/src/lib/usage.js +89 -0
  68. package/src/lib/version.js +1 -0
  69. package/templates/AGENTS.md.template +59 -53
  70. package/templates/contract.md.template +74 -3
  71. package/templates/spec.md.template +22 -0
package/src/lib/args.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Tiny argv parser. Returns { positional: string[], flags: Map<string, string|boolean> }.
2
3
  // Supports:
3
4
  // --flag -> flags.set("flag", true)
@@ -82,6 +83,15 @@ export function flagString(flags, name, fallback = undefined) {
82
83
  return String(v);
83
84
  }
84
85
 
86
+ // True when a value-taking flag was written WITHOUT one — `--budget` at the
87
+ // end of the line, or `--budget -100`, where the parser cannot tell a value
88
+ // from the next flag. `flagString` reports both as absent, so without this
89
+ // a mistyped number silently becomes "use the default", which is the one
90
+ // outcome the author definitely did not ask for.
91
+ export function flagGivenWithoutValue(flags, name) {
92
+ return flags.get(name) === true;
93
+ }
94
+
85
95
  export function flagBool(flags, name, fallback = false) {
86
96
  const v = flags.get(name);
87
97
  if (v === undefined) return fallback;
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Deterministic under-specification detector for free-text briefs and
2
3
  // intakes — the clarification gate (review Topic A). It does NOT judge
3
4
  // meaning (that stays the agent's job, ADR 0005); it flags input that is
package/src/lib/colors.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // ANSI colour helpers. Falls back to plain text when:
2
3
  // - stdout is not a TTY, OR
3
4
  // - the NO_COLOR environment variable is set (any value), OR
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Single canonical list of top-level `doctrina` commands.
2
3
  //
3
4
  // This is the one place the command surface is named. `src/index.js` builds
@@ -11,9 +12,9 @@
11
12
  // Keep this sorted by the workflow order used in `--help`, not alphabetically.
12
13
  export const COMMAND_NAMES = [
13
14
  // bootstrap / day-to-day
14
- "init", "intake", "work",
15
+ "init", "intake", "triage", "work",
15
16
  // authoring
16
- "spec", "change", "contract", "decision", "skill", "intent",
17
+ "spec", "change", "contract", "decision", "skill", "intent", "adapter",
17
18
  // read / orient
18
19
  "prime", "context", "show", "search", "status", "next", "why", "handoff", "constitution",
19
20
  // gates
@@ -35,6 +36,7 @@ export const COMMAND_NAMES = [
35
36
  export const OPERATIONS = [
36
37
  ["init", "Scaffold AGENTS.md and .doctrina/ in the current directory"],
37
38
  ["intake", "Store the full project description; print the bootstrap playbook"],
39
+ ["triage", "Classify a request into a lane, and check the runtime surface"],
38
40
  ["work", "Brief prompt -> scaffolded change + guided work playbook"],
39
41
  ["spec new", "Create a new capability spec (--bug for bug-shape)"],
40
42
  ["spec list", "List specs with version, status, and size"],
@@ -54,10 +56,14 @@ export const OPERATIONS = [
54
56
  ["decision land", "Record that an accepted ADR is now implemented (non-mutating)"],
55
57
  ["decision supersede", "Create a new ADR that supersedes an existing one"],
56
58
  ["decision list", "List ADRs with status, date, and title"],
59
+ ["decision scope", "Show and propose the capabilities each ADR governs"],
57
60
  ["skill new", "Scaffold an on-demand procedural memory skill"],
58
61
  ["skill list", "List skills with their descriptions"],
59
62
  ["skill sync", "Mirror skill frontmatter descriptions into index.json"],
60
63
  ["skill suggest", "Surface fix-shaped lessons worth a skill (--write scaffolds)"],
64
+ ["adapter list", "Inventory agent adapters: installed / available / native"],
65
+ ["adapter add", "Install one agent adapter (additive; never touches AGENTS.md)"],
66
+ ["adapter remove", "Delete the files an adapter installed"],
61
67
  ["intent add", "Append a new product intent anchor post-intake (- [SC5] ...)"],
62
68
  ["intent list", "List product.md intent anchors in document order"],
63
69
  ["analyze", "Inspect a change folder before applying"],
@@ -90,6 +96,70 @@ export const OPERATIONS = [
90
96
  ["upgrade", "Bring an existing project up to the installed CLI (--write applies)"],
91
97
  ];
92
98
 
99
+ // ---------------------------------------------------------------------------
100
+ // Per-command PURPOSE and WHEN (audit item M2).
101
+ //
102
+ // The generated surface block was a name index. An agent reading
103
+ // "`doctrina trace --strict`" learns that the command exists and nothing
104
+ // about what triggers it, what it costs, or what it returns — so learning
105
+ // the surface meant running `--help` 35 times, roughly the whole context
106
+ // budget spent on a lookup.
107
+ //
108
+ // Doctrina already solved this for SKILLS: `context` prints a description
109
+ // and a `when:` trigger per skill and tells the agent to load the body only
110
+ // when the trigger fires. Commands get the same treatment.
111
+ //
112
+ // `when` is the moment you reach for it, in the agent's own terms.
113
+ // `purpose` is one line on what it does. Both are required: a command that
114
+ // cannot state its trigger has not earned a place on the surface, and
115
+ // `templates check` fails when either is missing.
116
+ export const COMMAND_META = {
117
+ init: { moment: "Bootstrap", when: "starting a project that has no AGENTS.md yet", purpose: "scaffold AGENTS.md and .doctrina/" },
118
+ intake: { moment: "Bootstrap", when: "you have a full project description and no specs yet", purpose: "store the intent and print the bootstrap playbook" },
119
+ adapter: { moment: "Bootstrap", when: "adding or removing an agent's pointer files", purpose: "install/remove agent adapters (additive)" },
120
+
121
+ prime: { moment: "Orient", when: "at the START of every session", purpose: "gates, standing rules, and open work in one read" },
122
+ status: { moment: "Orient", when: "you need the health of the tree at a glance", purpose: "index, coverage, trace, and artifact counts" },
123
+ next: { moment: "Orient", when: "you finished something and do not know what follows", purpose: "the recommended next workflow action" },
124
+ context: { moment: "Orient", when: "before working on any task, to load the right files", purpose: "the read pack, assembled to fit a token budget" },
125
+ show: { moment: "Orient", when: "you need one requirement, criterion, or ADR, not a file", purpose: "point-read a single artifact by reference" },
126
+ search: { moment: "Orient", when: "you do not know which artifact mentions a term", purpose: "search the artifact tree, grouped by category" },
127
+ why: { moment: "Orient", when: "you need to justify or trace a capability's existence", purpose: "provenance: intent, proof, ADRs, and history" },
128
+ constitution: { moment: "Orient", when: "you need the standing rules before deciding something", purpose: "accepted ADRs and product non-goals" },
129
+ handoff: { moment: "Orient", when: "BEFORE compaction or handing over to another session", purpose: "a resume note: open work, task state, next command" },
130
+
131
+ triage: { moment: "Change", when: "a request arrives — BEFORE scaffolding, especially if it smells like an incident", purpose: "classify the lane (product/runtime/chore) and check the declared runtime surface" },
132
+ work: { moment: "Change", when: "a request arrives that changes behaviour (triage says PRODUCT)", purpose: "scaffold a change and print the playbook to execute" },
133
+ spec: { moment: "Change", when: "a capability needs creating or its headers advancing", purpose: "create, list, and edit capability specs" },
134
+ change: { moment: "Change", when: "driving a change through its lifecycle by hand", purpose: "new / apply / archive / check / tick / diff / abandon" },
135
+ decision: { moment: "Change", when: "the change decides something a later session must not relitigate", purpose: "record, accept, land, scope, and supersede ADRs" },
136
+ contract: { moment: "Change", when: "the change touches ports, env vars, or public endpoints", purpose: "own and verify the integration surface" },
137
+ intent: { moment: "Change", when: "new product intent appears after the intake", purpose: "append and list product intent anchors" },
138
+ skill: { moment: "Change", when: "a lesson is worth not relearning", purpose: "capture on-demand procedural memory" },
139
+
140
+ analyze: { moment: "Gate", when: "before applying a change", purpose: "structural pre-flight on a change folder" },
141
+ clarify: { moment: "Gate", when: "before applying, or before opening a PR", purpose: "smell-test Markdown for ambiguity" },
142
+ validate: { moment: "Gate", when: "after any artifact edit, and before considering work done", purpose: "schema, structure, EARS, and index drift" },
143
+ coverage: { moment: "Gate", when: "before claiming a capability is proven", purpose: "acceptance criteria against cited evidence" },
144
+ trace: { moment: "Gate", when: "checking that product intent still maps to capabilities", purpose: "intent provenance across the tree" },
145
+ review: { moment: "Gate", when: "before handing work back, to self-review it", purpose: "conformance of your changes vs specs/ADRs/contracts" },
146
+ verify: { moment: "Gate", when: "the real build gate must run", purpose: "the project's declared typecheck/test/build checks" },
147
+ close: { moment: "Gate", when: "a change is implemented and ready to finish", purpose: "the whole closing sequence in one attested pass" },
148
+ doctor: { moment: "Gate", when: "something looks wrong and you do not know which gate to ask", purpose: "aggregate diagnostic with per-finding remedies" },
149
+
150
+ templates: { moment: "Maintain", when: "after upgrading the CLI, or to customise a scaffold", purpose: "inspect, check, and refresh the template shape" },
151
+ upgrade: { moment: "Maintain", when: "you just updated the doctrina-cli package", purpose: "bring this project up to the installed CLI" },
152
+ index: { moment: "Maintain", when: "the index drifted from the tree", purpose: "regenerate index.json from the artifacts on disk" },
153
+ hooks: { moment: "Maintain", when: "setting up a repo so drift cannot be committed", purpose: "install the pre-commit gate" },
154
+ watch: { moment: "Maintain", when: "you want the tree re-synced on every save", purpose: "re-run validate --fix and next continuously" },
155
+ metrics: { moment: "Maintain", when: "reporting adoption over a period", purpose: "local git-derived adoption metrics" },
156
+ report: { moment: "Maintain", when: "summarising a period for a human", purpose: "a Markdown digest of changes, gates, and git" },
157
+ completion: { moment: "Maintain", when: "setting up a human's shell", purpose: "print shell completions from the catalog" },
158
+ };
159
+
160
+ // The order moments appear in the generated block.
161
+ export const MOMENTS = ["Bootstrap", "Orient", "Change", "Gate", "Maintain"];
162
+
93
163
  // The Commands block of `doctrina --help`, generated from OPERATIONS so the
94
164
  // printed surface can never omit an operation the catalog knows about.
95
165
  export function surfaceHelp() {
@@ -112,23 +182,13 @@ export const SURFACE_BEGIN =
112
182
  "<!-- doctrina:surface:begin — CLI-owned block, generated from the installed command catalog. Refreshed by `doctrina upgrade --write`; edits inside are overwritten. -->";
113
183
  export const SURFACE_END = "<!-- doctrina:surface:end -->";
114
184
 
115
- // Workflow grouping for the generated block. A test asserts the flattened
116
- // names equal COMMAND_NAMES, so a new command cannot ship ungrouped (and
117
- // therefore cannot ship invisible to AGENTS.md).
118
- export const SURFACE_GROUPS = [
119
- ["Start", ["init", "intake", "work"]],
120
- ["Author", ["spec", "change", "contract", "decision", "skill", "intent"]],
121
- ["Read / orient", ["prime", "context", "show", "search", "status", "next", "why", "handoff", "constitution"]],
122
- ["Gates", ["analyze", "clarify", "validate", "coverage", "trace", "review", "verify", "close", "doctor"]],
123
- ["Maintain", ["templates", "hooks", "index", "watch", "metrics", "report", "completion", "upgrade"]],
124
- ];
125
185
 
126
186
  // Per-command usage hints appended to the generated reference — arguments and
127
187
  // the flags an agent reaches for daily. Cosmetic only; the operation list
128
188
  // itself always comes from OPERATIONS.
129
189
  const SURFACE_HINTS = {
130
190
  work: '"<prompt>" (--capability · --chore · --from-diff · --quiet)',
131
- context: "[<cap>] --concat",
191
+ context: "[<cap>] --for \"<task>\" --concat",
132
192
  validate: "(--fix)",
133
193
  coverage: "--strict",
134
194
  trace: "--strict",
@@ -139,7 +199,25 @@ const SURFACE_HINTS = {
139
199
  handoff: "(before compaction/handover)",
140
200
  };
141
201
 
202
+ // The declared size budget for the generated block. A surface that cannot
203
+ // describe itself in this many lines is too large — the answer is to cut
204
+ // commands (M8), never to raise the number.
205
+ export const SURFACE_LINE_BUDGET = 40;
206
+
207
+ // Moments an agent works IN get a trigger per command. "Maintain" is
208
+ // compressed to one line: those commands are reached for by a human after
209
+ // an upgrade or when wiring a repo, not by an agent mid-loop, and giving
210
+ // each its own line pushed the block past its budget. The budget is the
211
+ // forcing function — a surface that cannot describe itself in 40 lines is
212
+ // too large, and the answer is to cut commands (M8), not to raise it.
213
+ const COMPACT_MOMENTS = new Set(["Maintain"]);
214
+
142
215
  // The full managed section, heading included, between the markers.
216
+ //
217
+ // Organised by MOMENT rather than by category, and each line carries the
218
+ // trigger: an agent scanning it learns WHEN to reach for a command, which
219
+ // a name index never told it. Same shape `context` prints for skills —
220
+ // description plus `when:`, body on demand.
143
221
  export function surfaceMarkdown() {
144
222
  const subsByCmd = new Map();
145
223
  for (const [op] of OPERATIONS) {
@@ -147,26 +225,39 @@ export function surfaceMarkdown() {
147
225
  if (!subsByCmd.has(cmd)) subsByCmd.set(cmd, []);
148
226
  if (sub) subsByCmd.get(cmd).push(sub);
149
227
  }
150
- const renderCmd = (cmd) => {
228
+ const invocation = (cmd) => {
151
229
  const subs = subsByCmd.get(cmd) ?? [];
152
230
  const hint = SURFACE_HINTS[cmd] ? ` ${SURFACE_HINTS[cmd]}` : "";
153
- return subs.length > 0 ? `\`doctrina ${cmd} ${subs.join("|")}\`` : `\`doctrina ${cmd}${hint}\``;
231
+ return subs.length > 0 ? `${cmd} ${subs.join("|")}` : `${cmd}${hint}`;
154
232
  };
233
+
155
234
  const lines = [
156
235
  "## Doctrina command surface (generated — reach for these, don't hand-author)",
157
236
  "",
158
- "Every operation of the installed CLI, grouped by workflow. The CLI",
159
- "scaffolds from canonical templates and keeps `index.json` in sync, so",
160
- "prefer it over writing artifacts by hand. Details: `doctrina --help`.",
161
- "",
237
+ // Two lines, not three. This block is always-loaded context inside a
238
+ // file with a hard 150-line budget, so its own preamble competes with
239
+ // the commands it introduces — and a command an agent never discovers
240
+ // costs more than a sentence of prose ever saves.
241
+ "Every command, with the moment you reach for it. The CLI scaffolds from",
242
+ "canonical templates and syncs `index.json`. Flags: `doctrina <cmd> --help`.",
162
243
  ];
163
- for (const [label, cmds] of SURFACE_GROUPS) {
164
- lines.push(`- **${label}:** ${cmds.map(renderCmd).join(" · ")}`);
244
+ for (const moment of MOMENTS) {
245
+ const cmds = COMMAND_NAMES.filter((n) => COMMAND_META[n]?.moment === moment);
246
+ if (cmds.length === 0) continue;
247
+ if (COMPACT_MOMENTS.has(moment)) {
248
+ // Each name still carries the `doctrina ` prefix: the compact line is
249
+ // read by validate's drift gate too, which only recognises a command
250
+ // reference in that form.
251
+ lines.push(`**${moment}** (triggers: \`doctrina <command> --help\`) — ` +
252
+ cmds.map((n) => `\`doctrina ${invocation(n)}\``).join(" · "));
253
+ continue;
254
+ }
255
+ lines.push(`**${moment}**`);
256
+ for (const cmd of cmds) {
257
+ const meta = COMMAND_META[cmd];
258
+ lines.push(`- \`doctrina ${invocation(cmd)}\` — ${meta.purpose}. *When:* ${meta.when}.`);
259
+ }
165
260
  }
166
- lines.push("");
167
- lines.push("Session bookends: `doctrina prime` to orient at session start;");
168
- lines.push("`doctrina handoff` before compaction or handover. Continuous:");
169
- lines.push("`doctrina watch`. Capture lessons: `doctrina skill suggest`.");
170
261
  return lines.join("\n");
171
262
  }
172
263
 
@@ -175,13 +266,87 @@ export function surfaceBlock() {
175
266
  return `${SURFACE_BEGIN}\n${surfaceMarkdown()}\n${SURFACE_END}`;
176
267
  }
177
268
 
269
+ // The block's CANONICAL POSITION, defined once — by the shipped template,
270
+ // which is the only place the intended layout exists.
271
+ //
272
+ // `templates update` used to APPEND the block, so the same CLI produced two
273
+ // different AGENTS.md layouts: third section on a fresh `init`, dead last
274
+ // after an `upgrade` — behind 117 lines the agent reads first, which is the
275
+ // attention problem design principle #2 exists to prevent, and with no
276
+ // heading of its own before it, so a hierarchical parse read the command
277
+ // surface as content of "## What never goes in this file" (audit item C4).
278
+ //
279
+ // Returns { after, before }: the heading text the block follows in the
280
+ // template, and the heading it precedes. Either may be null.
281
+ export function surfaceAnchors(templateText) {
282
+ const block = findSurfaceBlock(templateText);
283
+ if (!block) return { after: null, before: null };
284
+ const headingsBefore = [...templateText.slice(0, block.start).matchAll(/^##\s+.*$/gm)];
285
+ const headingAfter = templateText.slice(block.end).match(/^##\s+.*$/m);
286
+ return {
287
+ after: headingsBefore.length > 0 ? headingsBefore[headingsBefore.length - 1][0].trim() : null,
288
+ before: headingAfter ? headingAfter[0].trim() : null,
289
+ };
290
+ }
291
+
292
+ // Place `block` into `text` at the canonical position, returning the new
293
+ // text. Used by both `init` (via the template, which already has it there)
294
+ // and `templates update` (on a project that has none), so the two produce
295
+ // the same layout and running it twice is a no-op.
296
+ export function placeSurfaceBlock(text, block, anchors) {
297
+ const existing = findSurfaceBlock(text);
298
+ if (existing) return text.slice(0, existing.start) + block + text.slice(existing.end);
299
+
300
+ const lines = text.split("\n");
301
+ const headingIndex = (heading) =>
302
+ heading ? lines.findIndex((l) => l.trim() === heading) : -1;
303
+
304
+ // A section ends at the next heading OR at the start of another CLI-owned
305
+ // block. The marker comment precedes that block's heading, so scanning for
306
+ // headings alone would place this block BETWEEN a marker and its own
307
+ // heading — nesting the two, after which the next regeneration treats the
308
+ // outer span as stale and deletes everything inside it. That corrupted a
309
+ // real file before this guard existed.
310
+ const isBoundary = (line) => /^##\s+/.test(line) || /^\s*<!--\s*doctrina:\w+:begin/.test(line);
311
+
312
+ // Preferred: immediately after the section the template puts it after.
313
+ const afterIdx = headingIndex(anchors.after);
314
+ if (afterIdx >= 0) {
315
+ let end = afterIdx + 1;
316
+ while (end < lines.length && !isBoundary(lines[end])) end += 1;
317
+ const head = lines.slice(0, end).join("\n").replace(/\s+$/, "");
318
+ const tail = lines.slice(end).join("\n");
319
+ return `${head}\n\n${block}\n\n${tail}`.replace(/\n{3,}/g, "\n\n");
320
+ }
321
+
322
+ // Next: immediately before the section the template puts it before.
323
+ const beforeIdx = headingIndex(anchors.before);
324
+ if (beforeIdx >= 0) {
325
+ const head = lines.slice(0, beforeIdx).join("\n").replace(/\s+$/, "");
326
+ const tail = lines.slice(beforeIdx).join("\n");
327
+ return `${head}\n\n${block}\n\n${tail}`.replace(/\n{3,}/g, "\n\n");
328
+ }
329
+
330
+ // Last resort: append, with a trailing newline so the file stays well-formed.
331
+ return `${text.replace(/\s+$/, "")}\n\n${block}\n`;
332
+ }
333
+
178
334
  // Locate the managed block in an AGENTS.md text. Returns
179
335
  // { start, end, inner } (string offsets; inner excludes the marker lines)
180
336
  // or null when either marker is absent.
181
337
  export function findSurfaceBlock(text) {
182
- const begin = text.match(/<!--\s*doctrina:surface:begin[\s\S]*?-->/);
338
+ return findMarkedBlock(text, "surface");
339
+ }
340
+
341
+ // Shared locator for the CLI-owned marker blocks (surface, changed).
342
+ // Returns { start, end, inner } as string offsets, or null when either
343
+ // marker is missing.
344
+ function findMarkedBlock(text, name) {
345
+ // Note the doubled backslashes: these are TEMPLATE literals, so `\s`
346
+ // would collapse to a bare "s" before the RegExp ever sees it.
347
+ const begin = text.match(new RegExp(`<!--\\s*doctrina:${name}:begin[\\s\\S]*?-->`));
183
348
  if (!begin) return null;
184
- const endRe = /<!--\s*doctrina:surface:end\s*-->/;
349
+ const endRe = new RegExp(`<!--\\s*doctrina:${name}:end\\s*-->`);
185
350
  const end = endRe.exec(text.slice(begin.index + begin[0].length));
186
351
  if (!end) return null;
187
352
  const innerStart = begin.index + begin[0].length;
@@ -214,3 +379,63 @@ export function referencedCommands(markdown) {
214
379
  }
215
380
  return out;
216
381
  }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // The agent-facing changelog (M2, part 3).
385
+ //
386
+ // Reported from real use: when a new command shipped, the LLM driving
387
+ // Doctrina had no idea the capability existed. It only found out by running
388
+ // `doctrina --help` — which it had no reason to run, because nothing told
389
+ // it anything had changed.
390
+ //
391
+ // CHANGELOG.md is 46 KB of human prose and far too large to carry into a
392
+ // context window. This is three to six lines stating only what alters
393
+ // AGENT behaviour: a new capability, a changed trigger, a removed command.
394
+ // `upgrade --write` refreshes it, so an agent reading AGENTS.md after an
395
+ // upgrade learns what is new without being told to look.
396
+
397
+ export const AGENT_CHANGELOG_BEGIN =
398
+ "<!-- doctrina:changed:begin — CLI-owned. Regenerated by `doctrina upgrade --write`. -->";
399
+ export const AGENT_CHANGELOG_END = "<!-- doctrina:changed:end -->";
400
+
401
+ // What changed for an AGENT, per version. Keyed by the version that
402
+ // introduced it. Only entries that alter what an agent should DO belong
403
+ // here — a bug fix nobody's behaviour depends on does not.
404
+ export const AGENT_CHANGELOG = {
405
+ "0.15.0": [
406
+ "`doctrina triage \"<prompt>\"` — classify a request as PRODUCT / RUNTIME / CHORE BEFORE scaffolding. `work` now holds a runtime-shaped prompt with exit 3 and points here; `--force` opens the change anyway.",
407
+ "`contract check` now holds the declared wiring to the implementation: a `vars`/`secrets` variable no workflow exports, a default an empty CI value never triggers, an unvalidated enum, a selector matching zero targets (RT01-RT05).",
408
+ "A `verify` check may declare `expect`, so a run that exits 0 having executed NOTHING fails the gate; an `[orchestration]` acceptance criterion is proven by citing such a guarded check (`verify:<name>`), not by a citation that merely resolves.",
409
+ "A spec may declare an ordered `### Pipeline`; `validate` refuses a step that requires what a later step produces. `validate --runtime` adds the runtime gate.",
410
+ "`skill suggest --from-error <text|file>` drafts a skill from the failure on screen; `context --for` now ranks skills by their trigger.",
411
+ ],
412
+ "0.14.0": [
413
+ "`doctrina adapter add|remove|list` — add an agent without re-scaffolding; `init --force` no longer overwrites authored AGENTS.md/product.md.",
414
+ "`doctrina change apply` now refuses what `analyze` refuses; `change check` previews a close, `change tick` checks boxes in bulk.",
415
+ "Exit codes are a 5-class contract: 1 gate, 2 usage, 3 precondition, 4 environment. Branch on the code, not the prose.",
416
+ "A change that alters a documented surface must carry its docs — `close` refuses otherwise (`--force` records the gap).",
417
+ "Project templates under `.doctrina/templates/` now override the bundled ones, per file.",
418
+ ],
419
+ };
420
+
421
+ // The block written into AGENTS.md for a given version. Empty string when
422
+ // that version has no agent-visible changes.
423
+ export function agentChangelogMarkdown(version) {
424
+ const entries = AGENT_CHANGELOG[version];
425
+ if (!entries || entries.length === 0) return "";
426
+ return [
427
+ `## What changed in ${version}`,
428
+ "",
429
+ ...entries.map((e) => `- ${e}`),
430
+ ].join("\n");
431
+ }
432
+
433
+ export function agentChangelogBlock(version) {
434
+ const md = agentChangelogMarkdown(version);
435
+ if (!md) return "";
436
+ return `${AGENT_CHANGELOG_BEGIN}\n${md}\n${AGENT_CHANGELOG_END}`;
437
+ }
438
+
439
+ export function findAgentChangelogBlock(text) {
440
+ return findMarkedBlock(text, "changed");
441
+ }
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Shared parser for the "## Acceptance criteria" section of a spec.
2
3
  //
3
4
  // A criterion is a numbered item that MAY span several lines (continuation
package/src/lib/dates.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Date helpers. Single source so the CLI emits consistent YYYY-MM-DD strings.
2
3
 
3
4
  export function today(now = new Date()) {
package/src/lib/diff.js CHANGED
@@ -1,3 +1,4 @@
1
+ // @ts-check
1
2
  // Minimal line diff (LCS-based) for `change diff`. Specs are capped at a
2
3
  // few hundred lines, so the O(n*m) table is fine and keeps us at zero deps.
3
4