mandrel 1.86.0 → 1.87.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 (30) hide show
  1. package/.agents/instructions.md +7 -0
  2. package/.agents/rules/git-conventions.md +13 -1
  3. package/.agents/scripts/boot-sweep.js +36 -4
  4. package/.agents/scripts/git-cleanup.js +8 -0
  5. package/.agents/scripts/lib/checks/subagent-agent-tool-required.js +107 -30
  6. package/.agents/scripts/lib/epic-plan-ideation.js +24 -3
  7. package/.agents/scripts/lib/framework-version.js +210 -0
  8. package/.agents/scripts/lib/orchestration/context-hydration-engine.js +7 -22
  9. package/.agents/scripts/lib/orchestration/epic-cleanup.js +41 -5
  10. package/.agents/scripts/lib/orchestration/epic-spec-reconciler-diff.js +34 -3
  11. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches.js +102 -7
  12. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +85 -1
  13. package/.agents/scripts/lib/orchestration/git-cleanup/phases/phase-drivers.js +34 -3
  14. package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +71 -4
  15. package/.agents/scripts/lib/single-story-sweep.js +60 -5
  16. package/.agents/scripts/lib/story-body/story-body.js +81 -4
  17. package/.agents/scripts/providers/github/tickets.js +18 -1
  18. package/.agents/skills/core/epic-plan-consolidate/SKILL.md +7 -2
  19. package/.agents/skills/core/epic-plan-premortem/SKILL.md +8 -2
  20. package/.agents/skills/skills.index.json +3 -3
  21. package/.agents/skills/stack/architecture/subagent-orchestration/SKILL.md +36 -8
  22. package/.agents/workflows/git-cleanup.md +72 -18
  23. package/.agents/workflows/helpers/acceptance-self-eval.md +23 -1
  24. package/.agents/workflows/helpers/deliver-epic.md +22 -3
  25. package/.agents/workflows/helpers/epic-audit.md +60 -2
  26. package/.agents/workflows/helpers/parallel-tooling.md +9 -2
  27. package/.agents/workflows/helpers/plan-epic.md +32 -14
  28. package/.agents/workflows/loops/nightly-audit.md +9 -1
  29. package/docs/CHANGELOG.md +15 -0
  30. package/package.json +1 -1
@@ -334,6 +334,13 @@ budget grounds.
334
334
  spawns (search, doc regeneration, lint, log triage) and keep
335
335
  **implementation and design** work on the default capability; name no
336
336
  specific model — let the host and operator own the concrete mapping.
337
+ **Depth compounds the cost.** Sub-agents now carry the `Agent` tool and
338
+ can nest further (verified depth 2, announced max depth 5; see
339
+ [#2870](https://github.com/dsj1984/mandrel/issues/2870)), so this
340
+ spend-per-spawn caution is not one-level — **every** nesting level
341
+ re-pays the full always-loaded context. Weigh the whole subtree's cost,
342
+ not just the immediate spawn, before opening a deeper orchestration
343
+ level, and stay within the supported depth envelope.
337
344
  - **Anti-Laziness:** NEVER use placeholder comments like
338
345
  `// ... existing code ...`, `/* rest of file */`, or
339
346
  `// implementation here`. You MUST output the ENTIRE file or the ENTIRE
@@ -142,7 +142,19 @@ operator intervention:
142
142
  candidate with unpushed work, a dirty worktree, or a still-open parent
143
143
  ticket. A branch a flow leaves behind (e.g. a `/git-deliver` feature branch
144
144
  whose PR merges out of band) is therefore reaped automatically at the next
145
- workflow boot, not left for the operator to sweep by hand.
145
+ workflow boot, not left for the operator to sweep by hand. `boot-sweep.js`
146
+ defaults its `--include` glob to `story-*` — a bare invocation only sweeps
147
+ Story branches; `/plan` and `/git-deliver` widen the scope to their own
148
+ branch namespaces (`epic/*`, `feat/*`, `fix/*`, `chore/*`, `docs/*`,
149
+ `refactor/*`) by passing `--include` explicitly at their boot call site.
150
+ A branch the planner detects only via the weaker content-equivalence
151
+ signal (`detectedBy: 'content-merged'`, Story #4395's
152
+ `git merge-tree --write-tree` probe — content already landed in the base
153
+ branch by another route, such as a squash-merged Epic PR, with no merged
154
+ PR or git ancestry of its own) is **never** reaped by the boot sweep: it
155
+ is report-only, surfaced under `contentMerged` in the result envelope and
156
+ a routing hint in the summary line (Story #4396), so the operator can
157
+ send it to `/git-cleanup` for a confirmed, eyeballed reap.
146
158
  - **`/git-cleanup` is recovery, not routine.** Run it by hand only to recover
147
159
  an unusual state the automated hygiene does not cover — triaging stashes,
148
160
  reaping across non-standard branch namespaces, or `--remote` pruning after a
@@ -17,6 +17,17 @@
17
17
  * is swallowed and reported in the result envelope, never thrown, so a
18
18
  * caller can wire it into a boot path without risking the host run.
19
19
  *
20
+ * **Content-merged branches are report-only (Story #4396).** The planner
21
+ * also surfaces branches whose content already landed in the base branch
22
+ * by another route (a squash-merged Epic PR, a renamed head, a manual
23
+ * squash merge) via `detectedBy: 'content-merged'` (Story #4395's
24
+ * `git merge-tree --write-tree` probe) — a weaker signal than a merged PR
25
+ * or git ancestry, since no CI/GitHub merge check ever validated that
26
+ * branch's exact diff. This sweep never reaps on that signal alone; it
27
+ * surfaces the branches under `contentMerged` in the result envelope (and
28
+ * a routing hint in the human summary) so the operator can send them to
29
+ * `/git-cleanup` for a confirmed, eyeballed reap.
30
+ *
20
31
  * Usage:
21
32
  * node .agents/scripts/boot-sweep.js [--include <glob>...] \
22
33
  * [--exclude <glob>...] [--current <branch>] [--base <branch>] \
@@ -42,6 +53,10 @@ Runs the protected merged-branch boot sweep non-interactively: reaps every
42
53
  local branch whose PR is MERGED and whose HEAD matches the merged headRefOid,
43
54
  skipping any candidate the protection partition flags (unpushed work, dirty
44
55
  worktree, still-open parent Story), then fast-forwards the base branch.
56
+ Branches detected only via the weaker content-equivalence signal
57
+ (detectedBy: 'content-merged') are never reaped here — they are reported
58
+ under "contentMerged" (and a routing hint in the summary line) for the
59
+ operator to send to /git-cleanup.
45
60
 
46
61
  Options:
47
62
  --include <glob> Branch glob to sweep (repeatable). Default: story-*
@@ -136,11 +151,31 @@ export async function runBootSweep({
136
151
  localDeleted: 0,
137
152
  remoteDeleted: 0,
138
153
  protected: [],
154
+ contentMerged: [],
139
155
  failures: [],
140
156
  };
141
157
  }
142
158
  }
143
159
 
160
+ /**
161
+ * Build the human-readable one-line summary for a sweep result envelope.
162
+ * Exported for unit tests (Story #4396). A zero `contentMerged` count keeps
163
+ * the pre-Story #4396 line byte-identical (silent no-op summary); a nonzero
164
+ * count appends a routing hint pointing the operator at `/git-cleanup`.
165
+ *
166
+ * @param {{ localDeleted: number, remoteDeleted: number, protected?: Array, contentMerged?: Array }} result
167
+ * @returns {string}
168
+ */
169
+ export function buildSummaryLine(result) {
170
+ const protectedCount = result.protected?.length ?? 0;
171
+ const contentMergedCount = result.contentMerged?.length ?? 0;
172
+ const contentMergedSuffix =
173
+ contentMergedCount > 0
174
+ ? `; ${contentMergedCount} content-merged branch(es) left for /git-cleanup`
175
+ : '';
176
+ return `[boot-sweep] reaped ${result.localDeleted} local + ${result.remoteDeleted} remote; protected ${protectedCount}${contentMergedSuffix}.`;
177
+ }
178
+
144
179
  async function main() {
145
180
  const { values } = parseArgs({
146
181
  options: {
@@ -173,10 +208,7 @@ async function main() {
173
208
  if (values.json) {
174
209
  Logger.info(JSON.stringify(result, null, 2));
175
210
  } else {
176
- const protectedCount = result.protected?.length ?? 0;
177
- Logger.info(
178
- `[boot-sweep] reaped ${result.localDeleted} local + ${result.remoteDeleted} remote; protected ${protectedCount}.`,
179
- );
211
+ Logger.info(buildSummaryLine(result));
180
212
  }
181
213
  }
182
214
 
@@ -55,11 +55,14 @@ import {
55
55
  computeProtectedSet,
56
56
  } from './lib/orchestration/git-cleanup/phases/filters.js';
57
57
  import {
58
+ branchLastCommitAt,
58
59
  branchTipSha,
59
60
  classifyLatestPr,
60
61
  probeAllPrs,
62
+ probeContentEquivalent,
61
63
  probeLatestPr,
62
64
  probeMergedPr,
65
+ refExists,
63
66
  } from './lib/orchestration/git-cleanup/phases/git-probes.js';
64
67
  import { parseCleanupArgs } from './lib/orchestration/git-cleanup/phases/parse-args.js';
65
68
  import {
@@ -74,6 +77,7 @@ import {
74
77
  renderExecutionLine,
75
78
  renderExecutionSummary,
76
79
  renderLatestPrSkipLine,
80
+ renderNotMergedSkipLine,
77
81
  renderPruneLine,
78
82
  } from './lib/orchestration/git-cleanup/phases/render.js';
79
83
  import {
@@ -86,6 +90,7 @@ import {
86
90
 
87
91
  // Public surface preserved for tests + `single-story-sweep.js`.
88
92
  export {
93
+ branchLastCommitAt,
89
94
  branchTipSha,
90
95
  buildAllowlistDecider,
91
96
  buildGlobFilter,
@@ -105,13 +110,16 @@ export {
105
110
  planFastForward,
106
111
  planStashes,
107
112
  probeAllPrs,
113
+ probeContentEquivalent,
108
114
  probeLatestPr,
109
115
  probeMergedPr,
116
+ refExists,
110
117
  renderDeferredLine,
111
118
  renderDryRun,
112
119
  renderExecutionLine,
113
120
  renderExecutionSummary,
114
121
  renderLatestPrSkipLine,
122
+ renderNotMergedSkipLine,
115
123
  renderPruneLine,
116
124
  stashRefIndex,
117
125
  };
@@ -1,30 +1,44 @@
1
1
  /**
2
- * subagent-agent-tool-required — refuse-and-print check.
2
+ * subagent-agent-tool-required — supported-depth guard (refuse-and-print).
3
3
  *
4
- * Detects sub-agent workflow definitions that declare access to the
5
- * `Agent` tool (or otherwise document nested Agent dispatch). Nested
6
- * Agent dispatch is not supported in this Claude Code, so any
7
- * wave-runner-as-sub-agent or cascading fan-out design that declares
8
- * `Agent` in its tool list will silently fail at runtime. The remediation
9
- * is to flatten the fan-out back to the host agent and run sub-agents at
10
- * one level only.
4
+ * Nested `Agent` dispatch from a sub-agent is **supported** on this Claude
5
+ * Code build (verified depth 2, announced max depth 5 — Claude Code
6
+ * 2.1.202, re-spiked 2026-07-08; see Epic #4385 / watch #2870). A level-1
7
+ * sub-agent carries `Agent` in its primary toolset and can spawn a working
8
+ * level-2 sub-agent. Declaring `Agent` in a sub-agent workflow is therefore
9
+ * a legitimate design choice, **not** an automatic runtime failure.
10
+ *
11
+ * What this check guards is the one case that still fails: a fan-out whose
12
+ * declared nesting depth exceeds the announced/supported ceiling. A dispatch
13
+ * chain deeper than the harness supports will silently fail at runtime, so a
14
+ * workflow that declares `Agent` together with a `nesting-depth` beyond the
15
+ * ceiling is flagged as a blocker. A sub-agent that declares `Agent` at a
16
+ * supported depth (the common case — an undeclared depth is treated as the
17
+ * shallow level-1 fan-out) produces no finding.
18
+ *
19
+ * This inverts the historical guard (Story #4387): the check used to refuse
20
+ * `Agent` in *any* sub-agent workflow on the now-false rationale that
21
+ * sub-agents cannot dispatch. It no longer strips a real capability; it only
22
+ * catches an over-deep fan-out. The self-healing surface is preserved — it is
23
+ * re-scoped, not removed.
11
24
  *
12
25
  * Scope: 'epic-deliver', 'retro'. Surfaces as a blocker at preflight for
13
26
  * `epic-deliver` (the fan-out site) and as audit signal at retro.
14
27
  *
15
- * The check is `refuse-and-print` — auto-rewriting a workflow's tool
16
- * list would silently change runtime behavior in ways the operator may
17
- * not have intended (the workflow's logic may depend on the missing
18
- * tool). The fixCommand cites the flatten-fan-out remediation pattern.
28
+ * The check is `refuse-and-print` — auto-rewriting a workflow's declared
29
+ * depth or tool list would silently change runtime behavior in ways the
30
+ * operator may not have intended. The fixCommand explains how to bring the
31
+ * fan-out back under the ceiling (reduce the declared depth or split the
32
+ * deepest level out), and is explicit that stripping `Agent` is NOT the fix.
19
33
  *
20
- * Implementation note: we scan `.agents/workflows/*.md` for workflow
21
- * files whose frontmatter or body identifies them as a sub-agent role
22
- * AND whose `tools:` declaration includes `Agent`. The marker for
23
- * "sub-agent" is the phrase `sub-agent` appearing in the description /
24
- * overview region. This keeps the check stable while the workflow
25
- * surface evolves the project doesn't yet have a structured
26
- * `role: sub-agent` frontmatter field, and the textual marker is what
27
- * the human contributors actually grep for.
34
+ * Implementation note: we scan `.agents/workflows/*.md` for workflow files
35
+ * whose frontmatter or body identifies them as a sub-agent role AND whose
36
+ * `tools:` declaration includes `Agent`, then read the workflow's declared
37
+ * `nesting-depth`. The marker for "sub-agent" is the phrase `sub-agent`
38
+ * appearing in the description / overview region. The depth is read from a
39
+ * `nesting-depth:` (or `agent-depth:`) frontmatter field, or a
40
+ * `<!-- nesting-depth: N -->` body marker; an absent declaration is treated
41
+ * as depth 1 (a single, shallow fan-out level).
28
42
  */
29
43
 
30
44
  import { readdirSync, readFileSync } from 'node:fs';
@@ -32,6 +46,17 @@ import path from 'node:path';
32
46
 
33
47
  const WORKFLOWS_DIR_DEFAULT = path.join('.agents', 'workflows');
34
48
 
49
+ /**
50
+ * Announced maximum nesting depth the Claude Code harness supports for
51
+ * sub-agent fan-out. Depth 2 is independently verified; depths 3–5 are
52
+ * announced but not yet re-spiked (Epic #4385 / watch #2870). A workflow
53
+ * declaring a fan-out deeper than this ceiling is flagged. Operators can pin
54
+ * a stricter (or, once verified, looser) ceiling via `state.supportedDepth`.
55
+ *
56
+ * @type {number}
57
+ */
58
+ export const ANNOUNCED_MAX_DEPTH = 5;
59
+
35
60
  /**
36
61
  * Walk a workflow directory and return absolute `.md` file paths
37
62
  * (non-recursive — the workflows surface is one level deep; helpers/
@@ -127,17 +152,57 @@ function findAgentToolDeclaration(parts) {
127
152
  return null;
128
153
  }
129
154
 
155
+ /**
156
+ * Parse the workflow's declared nesting depth. A sub-agent that declares
157
+ * `Agent` may also declare how deep its fan-out reaches via a
158
+ * `nesting-depth:` (or `agent-depth:`) frontmatter field, or a
159
+ * `<!-- nesting-depth: N -->` marker in the body. Returns the integer
160
+ * depth, or `null` when no depth is declared (the caller treats an absent
161
+ * declaration as the shallow level-1 fan-out).
162
+ *
163
+ * @param {{ frontmatter: string, body: string }} parts
164
+ * @returns {number | null}
165
+ */
166
+ function parseDeclaredDepth(parts) {
167
+ const { frontmatter, body } = parts;
168
+ const fmMatch = frontmatter.match(
169
+ /^[ \t]*(?:nesting-depth|agent-depth)\s*:\s*(\d+)\s*$/m,
170
+ );
171
+ if (fmMatch) return Number.parseInt(fmMatch[1], 10);
172
+ const bodyMatch = body.match(
173
+ /<!--\s*(?:nesting-depth|agent-depth)\s*:\s*(\d+)\s*-->/,
174
+ );
175
+ if (bodyMatch) return Number.parseInt(bodyMatch[1], 10);
176
+ return null;
177
+ }
178
+
179
+ /**
180
+ * Resolve the supported depth ceiling for a detect run. Operators may pin a
181
+ * stricter (or, once verified, looser) ceiling via `state.supportedDepth`;
182
+ * an unset or non-positive-integer override falls back to the announced max.
183
+ *
184
+ * @param {{ supportedDepth?: unknown } | null | undefined} state
185
+ * @returns {number}
186
+ */
187
+ function resolveCeiling(state) {
188
+ const override = state?.supportedDepth;
189
+ if (Number.isInteger(override) && override > 0) return override;
190
+ return ANNOUNCED_MAX_DEPTH;
191
+ }
192
+
130
193
  const FIX_COMMAND = [
131
- '# Flatten fan-out to the host. Sub-agents cannot dispatch other agents.',
132
- "# Remove the `Agent` entry from this workflow's `tools:` declaration,",
133
- '# move any fan-out logic up to the parent / host invocation, and have',
134
- '# the parent dispatch the leaf sub-agents directly.',
194
+ '# Nested Agent dispatch IS supported (verified depth 2, announced max 5 —',
195
+ '# Claude Code 2.1.202). This workflow declares a fan-out deeper than the',
196
+ '# supported ceiling, so the deepest dispatch chain will fail at runtime.',
135
197
  '#',
136
- '# Pattern (host workflow):',
137
- '# for each child: Agent(prompt=<child workflow>, args=<id>)',
198
+ '# Bring the fan-out back under the ceiling — either:',
199
+ '# 1. Lower the declared `nesting-depth` to <= the supported ceiling, or',
200
+ '# 2. Split the deepest level out to a shallower sibling fan-out so no',
201
+ '# single dispatch chain exceeds the supported depth.',
138
202
  '#',
139
- '# Pattern (sub-agent workflow):',
140
- '# tools: [Bash, Read, Edit, Grep, Glob, Write] # NO Agent',
203
+ '# Do NOT strip `Agent` from the tool list to silence this. Sub-agents CAN',
204
+ '# dispatch nested agents at a supported depth; removing the tool would',
205
+ '# disable a legitimate capability, not fix the depth overflow.',
141
206
  ].join('\n');
142
207
 
143
208
  export default {
@@ -149,6 +214,7 @@ export default {
149
214
  detect(state) {
150
215
  const cwd = state?.cwd ?? process.cwd();
151
216
  const root = state?.scanRoot ?? path.join(cwd, WORKFLOWS_DIR_DEFAULT);
217
+ const ceiling = resolveCeiling(state);
152
218
  const files = listWorkflowFiles(root);
153
219
  const offences = [];
154
220
  for (const file of files) {
@@ -162,18 +228,29 @@ export default {
162
228
  const parts = splitFrontmatter(src);
163
229
  const where = findAgentToolDeclaration(parts);
164
230
  if (!where) continue;
231
+ // Declaring `Agent` is legitimate. Only a fan-out deeper than the
232
+ // supported ceiling is a runtime hazard; an undeclared depth is the
233
+ // shallow level-1 fan-out and always within the ceiling.
234
+ const depth = parseDeclaredDepth(parts) ?? 1;
235
+ if (depth <= ceiling) continue;
165
236
  offences.push({
166
237
  file: path.relative(root, file).replace(/\\/g, '/'),
167
238
  where,
239
+ depth,
168
240
  });
169
241
  }
170
242
  if (offences.length === 0) return null;
171
- const detail = offences.map((o) => `${o.file} — ${o.where}`).join('\n');
243
+ const detail = offences
244
+ .map(
245
+ (o) =>
246
+ `${o.file} — declares Agent at nesting-depth ${o.depth} (exceeds supported ceiling ${ceiling}); ${o.where}`,
247
+ )
248
+ .join('\n');
172
249
  return {
173
250
  id: 'subagent-agent-tool-required',
174
251
  severity: 'blocker',
175
252
  scope: state?.scope ?? 'epic-deliver',
176
- summary: `${offences.length} sub-agent workflow(s) declare Agent in their tool list nested Agent dispatch is unsupported`,
253
+ summary: `${offences.length} sub-agent workflow(s) declare an Agent fan-out deeper than the supported nesting ceiling (${ceiling})`,
177
254
  detail,
178
255
  fixCommand: FIX_COMMAND,
179
256
  autoCorrectable: false,
@@ -13,6 +13,10 @@
13
13
  * mock the provider call without touching the GitHub HTTP client.
14
14
  */
15
15
 
16
+ import {
17
+ extractFrameworkStamp,
18
+ stampFrameworkVersion,
19
+ } from './framework-version.js';
16
20
  import { TYPE_LABELS } from './label-constants.js';
17
21
 
18
22
  // Canonical section keys match the rendered template at
@@ -113,24 +117,33 @@ export function parseOnePager(onePager) {
113
117
  * sections are rendered as `_(not specified)_` so the operator can spot
114
118
  * gaps during the HITL review (Phase 3).
115
119
  *
120
+ * Story #4382 — the rendered body is stamped with the Mandrel framework
121
+ * version + authoring date (hidden `mandrel_version` / `authored_at` meta
122
+ * field + a visible `> 🏷️ Authored with Mandrel …` marker) via
123
+ * {@link stampFrameworkVersion}. Pass `stamp` to preserve a
124
+ * previously-authored version on re-render (the Epic edit path does this);
125
+ * omit it to stamp the running version and today's date.
126
+ *
116
127
  * @param {{
117
128
  * onePager: string,
118
129
  * template: string,
130
+ * stamp?: { version?: string, authoredAt?: string },
119
131
  * }} args
120
132
  * @returns {{ title: string, body: string }}
121
133
  */
122
- export function renderEpicBody({ onePager, template }) {
134
+ export function renderEpicBody({ onePager, template, stamp }) {
123
135
  if (!template || typeof template !== 'string') {
124
136
  throw new Error('renderEpicBody: template must be a non-empty string');
125
137
  }
126
138
  const parsed = parseOnePager(onePager);
127
139
 
128
- const body = template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
140
+ const rendered = template.replace(/\{\{(\w+)\}\}/g, (_, key) => {
129
141
  if (key === 'title') return parsed.title;
130
142
  const value = parsed[key];
131
143
  return value && value.length > 0 ? value : '_(not specified)_';
132
144
  });
133
145
 
146
+ const body = stampFrameworkVersion(rendered, stamp ?? {});
134
147
  return { title: parsed.title, body };
135
148
  }
136
149
 
@@ -226,7 +239,15 @@ export async function updateEpicFromOnePager({
226
239
  );
227
240
  }
228
241
 
229
- const { title, body } = renderEpicBody({ onePager, template });
242
+ // Story #4382 preserve the originally-authored version stamp on edit
243
+ // rather than bumping it to whatever version is running now. When the
244
+ // current body carries no stamp (legacy Epic), a fresh stamp is applied.
245
+ const priorStamp = extractFrameworkStamp(currentBody ?? '');
246
+ const stamp = priorStamp
247
+ ? { version: priorStamp.version, authoredAt: priorStamp.authoredAt }
248
+ : undefined;
249
+
250
+ const { title, body } = renderEpicBody({ onePager, template, stamp });
230
251
 
231
252
  if (typeof currentBody === 'string' && currentBody === body) {
232
253
  return { epicId, title, body, changed: false };
@@ -0,0 +1,210 @@
1
+ // .agents/scripts/lib/framework-version.js
2
+ /**
3
+ * framework-version.js — single source of truth for the running Mandrel
4
+ * framework version and the ticket-body authoring stamp.
5
+ *
6
+ * Two concerns live here:
7
+ *
8
+ * 1. **Version resolution.** Under npm distribution the root `package.json`
9
+ * is the canonical version marker. {@link resolveFrameworkVersion} reads it
10
+ * and degrades to `'unknown'` (never throws) so a missing/unreadable
11
+ * manifest can never crash an authoring or hydration path. The private
12
+ * `getVersion()` in `lib/orchestration/context-hydration-engine.js`
13
+ * delegates here (DRY — one manifest reader).
14
+ *
15
+ * 2. **Ticket-body stamp.** Epics and Stories are stamped **once at authoring
16
+ * time** with the running version and the authoring date, via a hybrid
17
+ * surface:
18
+ * - a hidden machine-readable field in the trailing
19
+ * `<!-- meta: {"mandrel_version":"…","authored_at":"…"} -->` block
20
+ * (the source of truth, queryable by tooling), and
21
+ * - a single visible footer line
22
+ * `> 🏷️ Authored with Mandrel v<version> · <YYYY-MM-DD>` so a human
23
+ * reading the raw GitHub issue sees the provenance without any tooling.
24
+ *
25
+ * The stamp is **immutable**: {@link stampFrameworkVersion} is a no-op when
26
+ * the body already carries a `mandrel_version`, so a later re-render or
27
+ * Epic-body edit preserves the originally-authored version verbatim rather
28
+ * than bumping it to whatever version happens to be running.
29
+ *
30
+ * This module imports only Node builtins so it can be pulled in from the
31
+ * story-body serializer, the ticket provider, and the Epic ideation renderer
32
+ * without risking an import cycle.
33
+ */
34
+
35
+ import fs from 'node:fs';
36
+ import path from 'node:path';
37
+ import { fileURLToPath } from 'node:url';
38
+
39
+ /** Returned when the package manifest is absent or unreadable. */
40
+ export const FALLBACK_VERSION = 'unknown';
41
+
42
+ /**
43
+ * Trailing machine-metadata comment block: `<!-- meta: {...} -->`. Mirrors the
44
+ * regex the Story-body parser uses so both surfaces recognise the same block.
45
+ */
46
+ const META_BLOCK_RE = /<!--\s*meta:\s*(\{[\s\S]*?\})\s*-->/;
47
+
48
+ /**
49
+ * The visible authoring marker line. A blockquote so GitHub renders it as a
50
+ * callout. Used both to detect an already-emitted marker (for the strip step)
51
+ * and, in the Story-body parser, to skip the line during section parsing so it
52
+ * never pollutes the last structured section.
53
+ */
54
+ export const AUTHORED_MARKER_LINE_RE = /^\s*>\s*🏷️\s+Authored with Mandrel\b/;
55
+
56
+ /**
57
+ * Compute the default path to the root `package.json`. This module ships inside
58
+ * the `mandrel` package at `<pkgRoot>/.agents/scripts/lib/framework-version.js`,
59
+ * so the manifest sits three directories up — the same layout in the dev repo
60
+ * and the published tarball.
61
+ *
62
+ * @returns {string}
63
+ */
64
+ function defaultPkgPath() {
65
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
66
+ return path.resolve(moduleDir, '../../..', 'package.json');
67
+ }
68
+
69
+ /**
70
+ * Resolve the running framework version from the root `package.json`. Degrades
71
+ * to {@link FALLBACK_VERSION} (never throws) on any read or parse failure so a
72
+ * missing/unreadable manifest can never crash an authoring or hydration path.
73
+ *
74
+ * @param {{ pkgPath?: string }} [opts] - `pkgPath` override (test seam).
75
+ * @returns {string}
76
+ */
77
+ export function resolveFrameworkVersion({ pkgPath } = {}) {
78
+ try {
79
+ const resolved = typeof pkgPath === 'string' ? pkgPath : defaultPkgPath();
80
+ const parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
81
+ return typeof parsed.version === 'string' && parsed.version.trim()
82
+ ? parsed.version.trim()
83
+ : FALLBACK_VERSION;
84
+ } catch {
85
+ return FALLBACK_VERSION;
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Format an authoring date as `YYYY-MM-DD` (UTC). Matches the date shape the
91
+ * rest of the authoring path uses (e.g. `qa-session`).
92
+ *
93
+ * @param {Date} [date=new Date()]
94
+ * @returns {string}
95
+ */
96
+ export function formatAuthoredDate(date = new Date()) {
97
+ const d =
98
+ date instanceof Date && !Number.isNaN(date.getTime()) ? date : new Date();
99
+ return d.toISOString().slice(0, 10);
100
+ }
101
+
102
+ /**
103
+ * Build the visible authoring marker line for a given stamp. Centralised so
104
+ * the string is byte-identical across the two producers (the Story-body
105
+ * serializer and {@link stampFrameworkVersion}).
106
+ *
107
+ * @param {{ version: string, authoredAt: string }} stamp
108
+ * @returns {string}
109
+ */
110
+ export function authoredMarkerLine({ version, authoredAt }) {
111
+ return `> 🏷️ Authored with Mandrel v${version} · ${authoredAt}`;
112
+ }
113
+
114
+ /**
115
+ * Read the framework stamp from a body's trailing meta block. Returns
116
+ * `{ version, authoredAt }` when a non-empty `mandrel_version` is present, or
117
+ * `null` when the body carries no stamp (or the meta block is malformed).
118
+ * `authoredAt` is `null` when the version is present but the date is absent.
119
+ *
120
+ * @param {string} markdown
121
+ * @returns {{ version: string, authoredAt: string|null }|null}
122
+ */
123
+ export function extractFrameworkStamp(markdown) {
124
+ if (typeof markdown !== 'string') return null;
125
+ const match = markdown.match(META_BLOCK_RE);
126
+ if (!match) return null;
127
+ let parsed;
128
+ try {
129
+ parsed = JSON.parse(match[1]);
130
+ } catch {
131
+ return null;
132
+ }
133
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
134
+ return null;
135
+ }
136
+ const version =
137
+ typeof parsed.mandrel_version === 'string' && parsed.mandrel_version.trim()
138
+ ? parsed.mandrel_version.trim()
139
+ : null;
140
+ if (version === null) return null;
141
+ const authoredAt =
142
+ typeof parsed.authored_at === 'string' && parsed.authored_at.trim()
143
+ ? parsed.authored_at.trim()
144
+ : null;
145
+ return { version, authoredAt };
146
+ }
147
+
148
+ /**
149
+ * Stamp a ticket body (Epic or Story markdown) with the framework version and
150
+ * authoring date — **once**. When the body already carries a `mandrel_version`
151
+ * the body is returned verbatim (immutability: never re-derive or bump an
152
+ * already-authored stamp). Otherwise the version keys are merged into (or
153
+ * create) the trailing `<!-- meta -->` block — appended **last** so the key
154
+ * order stays stable with the Story-body serializer — and the visible marker
155
+ * line is (re)emitted just above it.
156
+ *
157
+ * The `version` / `authoredAt` overrides let a caller (e.g. the Epic edit path)
158
+ * preserve a previously-authored stamp; both default to the running version and
159
+ * today's date when omitted.
160
+ *
161
+ * @param {string} markdown
162
+ * @param {{ version?: string, authoredAt?: string }} [stamp]
163
+ * @returns {string}
164
+ */
165
+ export function stampFrameworkVersion(markdown, stamp = {}) {
166
+ const body = typeof markdown === 'string' ? markdown : '';
167
+
168
+ // Immutability: a body that already carries a version is preserved verbatim.
169
+ if (extractFrameworkStamp(body) !== null) return body;
170
+
171
+ const version =
172
+ typeof stamp?.version === 'string' && stamp.version.trim()
173
+ ? stamp.version.trim()
174
+ : resolveFrameworkVersion();
175
+ const authoredAt =
176
+ typeof stamp?.authoredAt === 'string' && stamp.authoredAt.trim()
177
+ ? stamp.authoredAt.trim()
178
+ : formatAuthoredDate();
179
+
180
+ // Merge into any existing (version-less) meta block, appending the version
181
+ // keys last for stable key order.
182
+ const metaMatch = body.match(META_BLOCK_RE);
183
+ const meta = {};
184
+ if (metaMatch) {
185
+ try {
186
+ const parsed = JSON.parse(metaMatch[1]);
187
+ if (
188
+ parsed !== null &&
189
+ typeof parsed === 'object' &&
190
+ !Array.isArray(parsed)
191
+ ) {
192
+ Object.assign(meta, parsed);
193
+ }
194
+ } catch {
195
+ // Malformed meta comment — drop it and re-emit a clean block.
196
+ }
197
+ }
198
+ meta.mandrel_version = version;
199
+ meta.authored_at = authoredAt;
200
+
201
+ // Strip any existing meta block / marker so both re-append canonically.
202
+ const head = body
203
+ .replace(META_BLOCK_RE, '')
204
+ .replace(new RegExp(AUTHORED_MARKER_LINE_RE.source, 'm'), '')
205
+ .replace(/\n{3,}/g, '\n\n')
206
+ .trimEnd();
207
+
208
+ const marker = authoredMarkerLine({ version, authoredAt });
209
+ return `${head}\n\n${marker}\n\n<!-- meta: ${JSON.stringify(meta)} -->`;
210
+ }