mandrel 2.70.0 → 2.72.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 (79) hide show
  1. package/.agents/README.md +8 -9
  2. package/.agents/agents/acceptance-critic.md +1 -0
  3. package/.agents/agents/auditor.md +1 -0
  4. package/.agents/agents/plan-critic.md +1 -0
  5. package/.agents/agents/story-worker.md +63 -64
  6. package/.agents/docs/agentrc-reference.json +2 -1
  7. package/.agents/docs/configuration.md +7 -8
  8. package/.agents/rules/git-conventions-reference.md +2 -2
  9. package/.agents/schemas/agentrc.schema.json +19 -2
  10. package/.agents/schemas/story-deliver-terminal.schema.json +10 -1
  11. package/.agents/scripts/acceptance-eval.js +194 -15
  12. package/.agents/scripts/deliver-run.js +92 -43
  13. package/.agents/scripts/lib/audit-suite/index.js +1 -1
  14. package/.agents/scripts/lib/audit-suite/story-checklist.js +65 -0
  15. package/.agents/scripts/lib/audit-to-stories/audit-label-taxonomy.js +2 -2
  16. package/.agents/scripts/lib/bootstrap/issue-forms-template.js +1 -1
  17. package/.agents/scripts/lib/cli-args.js +22 -0
  18. package/.agents/scripts/lib/close-validation/gates.js +17 -3
  19. package/.agents/scripts/lib/config/agent-models.js +117 -0
  20. package/.agents/scripts/lib/config-settings-schema-delivery.js +13 -1
  21. package/.agents/scripts/lib/config-settings-schema-quality.js +1 -1
  22. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  23. package/.agents/scripts/lib/git/sync-from-base.js +89 -17
  24. package/.agents/scripts/lib/label-taxonomy.js +13 -3
  25. package/.agents/scripts/lib/notifications/notifier.js +11 -15
  26. package/.agents/scripts/lib/observability/close-telemetry.js +19 -3
  27. package/.agents/scripts/lib/observability/source-classifier.js +1 -0
  28. package/.agents/scripts/lib/orchestration/cancelled-run-discount.js +129 -0
  29. package/.agents/scripts/lib/orchestration/code-review.js +2 -2
  30. package/.agents/scripts/lib/orchestration/deliver-recover.js +166 -34
  31. package/.agents/scripts/lib/orchestration/file-assumptions.js +45 -11
  32. package/.agents/scripts/lib/orchestration/plan-context.js +17 -10
  33. package/.agents/scripts/lib/orchestration/plan-persist/changes-repair.js +130 -24
  34. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +19 -16
  35. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +1 -0
  36. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +4 -3
  37. package/.agents/scripts/lib/orchestration/pr-watch.js +14 -3
  38. package/.agents/scripts/lib/orchestration/resolve-stories.js +10 -2
  39. package/.agents/scripts/lib/orchestration/review-providers/native.js +5 -165
  40. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +14 -2
  41. package/.agents/scripts/lib/orchestration/single-story-close/phases/auto-merge.js +45 -0
  42. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +162 -58
  43. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +58 -6
  44. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +296 -0
  45. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +20 -4
  46. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +52 -6
  47. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +2 -2
  48. package/.agents/scripts/lib/orchestration/single-story-close/phases/story-branch-catch-up.js +50 -0
  49. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-reap.js +64 -52
  50. package/.agents/scripts/lib/orchestration/single-story-close/phases/worktree-restore.js +133 -0
  51. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +187 -74
  52. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +46 -6
  53. package/.agents/scripts/lib/orchestration/story-handoff.js +849 -0
  54. package/.agents/scripts/lib/orchestration/story-init-result.js +83 -0
  55. package/.agents/scripts/lib/orchestration/task-body-validator.js +35 -5
  56. package/.agents/scripts/lib/orchestration/ticket-validator-sizing.js +1 -1
  57. package/.agents/scripts/lib/orchestration/ticket-validator.js +20 -2
  58. package/.agents/scripts/lib/single-story/confirm-merge.js +44 -7
  59. package/.agents/scripts/lib/story-body/story-body.js +40 -5
  60. package/.agents/scripts/lib/templates/decomposer-prompts.js +33 -36
  61. package/.agents/scripts/pr-watch-with-update.js +5 -0
  62. package/.agents/scripts/single-story-close.js +8 -0
  63. package/.agents/scripts/single-story-confirm-merge.js +34 -3
  64. package/.agents/scripts/single-story-init.js +17 -32
  65. package/.agents/scripts/story-handoff.js +112 -0
  66. package/.agents/scripts/sync-claude-agents.js +58 -27
  67. package/.agents/workflows/helpers/acceptance-self-eval.md +24 -18
  68. package/.agents/workflows/helpers/code-review.md +3 -3
  69. package/.agents/workflows/helpers/deliver-digest.md +79 -80
  70. package/.agents/workflows/helpers/deliver-light.md +9 -7
  71. package/.agents/workflows/helpers/deliver-reference.md +38 -22
  72. package/.agents/workflows/helpers/deliver-story-reference.md +39 -18
  73. package/.agents/workflows/helpers/deliver-story.md +30 -23
  74. package/.agents/workflows/helpers/plan-reference.md +24 -9
  75. package/.agents/workflows/helpers/worktree-lifecycle.md +5 -5
  76. package/docs/CHANGELOG.md +31 -0
  77. package/lib/cli/registry.js +7 -0
  78. package/package.json +4 -3
  79. package/.agents/scripts/lib/orchestration/review-providers/scoped-lint.js +0 -272
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The `single-story-init.js` result envelope, composed in one place: the
3
+ * fields the caller acts on (`workCwd`, `dependenciesInstalled`,
4
+ * `remoteVerified`, `checklistPath`) plus the full detail the terse-result
5
+ * log keeps.
6
+ */
7
+
8
+ import { pinRunScopedConfig } from './run-scoped-config.js';
9
+
10
+ /** `installStatus.status` → the envelope's `dependenciesInstalled` string. */
11
+ const INSTALL_FLAGS = Object.freeze({ installed: 'true', failed: 'false' });
12
+
13
+ /**
14
+ * @param {object} args
15
+ * @param {number} args.storyId
16
+ * @param {string} args.storyBranch
17
+ * @param {string} args.baseBranch
18
+ * @param {object} args.config
19
+ * @param {{ title?: string }} args.story
20
+ * @param {{ worktreeEnabled: boolean }} args.runtime
21
+ * @param {string} args.workCwd
22
+ * @param {boolean} args.worktreeCreated
23
+ * @param {{ status: string }} args.installStatus
24
+ * @param {object|null} args.worktreeSweep
25
+ * @param {boolean} args.dryRun
26
+ * @param {{ remoteVerified: boolean, remoteUrl?: string, detail?: string }} args.remote
27
+ * @param {string|null} args.checklistPath
28
+ * @returns {{ result: object, summary: object }}
29
+ */
30
+ export function composeStoryInitResult({
31
+ storyId,
32
+ storyBranch,
33
+ baseBranch,
34
+ config,
35
+ story,
36
+ runtime,
37
+ workCwd,
38
+ worktreeCreated,
39
+ installStatus,
40
+ worktreeSweep,
41
+ dryRun,
42
+ remote,
43
+ checklistPath,
44
+ }) {
45
+ const dependenciesInstalled =
46
+ INSTALL_FLAGS[installStatus.status] ?? 'skipped';
47
+ const result = {
48
+ storyId,
49
+ epicId: null,
50
+ standalone: true,
51
+ storyBranch,
52
+ baseBranch,
53
+ // Write half of the run-scoped config pin; `baseBranch` is close's fallback.
54
+ runScopedConfig: pinRunScopedConfig(config),
55
+ storyTitle: story.title,
56
+ worktreeEnabled: runtime.worktreeEnabled,
57
+ workCwd,
58
+ worktreeCreated,
59
+ installStatus,
60
+ dependenciesInstalled,
61
+ installFailed: installStatus.status === 'failed',
62
+ // Closed-Story worktree sweep outcome; a failure degrades here, never
63
+ // into an init failure. `null` under --dry-run.
64
+ worktreeSweep: worktreeSweep ?? null,
65
+ dryRun,
66
+ remoteVerified: remote.remoteVerified,
67
+ remoteProbe: { remoteUrl: remote.remoteUrl, detail: remote.detail },
68
+ // Footprint-matched write-time checklist (null when no lens matches) —
69
+ // the same Story-scoped path a multi-Story dispatch prompt names.
70
+ checklistPath,
71
+ };
72
+ const summary = {
73
+ storyId,
74
+ storyBranch,
75
+ workCwd,
76
+ worktreeCreated,
77
+ dependenciesInstalled,
78
+ remoteVerified: remote.remoteVerified,
79
+ checklistPath,
80
+ dryRun,
81
+ };
82
+ return { result, summary };
83
+ }
@@ -1,8 +1,10 @@
1
1
  /**
2
2
  * Story body schema validator. String bodies (the canonical serialized form)
3
3
  * are parsed before checking. Requires a non-empty `goal`, `acceptance`, and
4
- * `changes` of `{ path, assumption }` objects; `references` is optional, same
5
- * shape. `verify` is not scored. Errors are batched into one throw.
4
+ * `changes` of `{ path, assumption }` objects; `references` is optional and
5
+ * may also hold bare paths (persist derives `exists`, and the file-assumption
6
+ * probe warns when one is absent). `verify` is not scored. Errors are batched
7
+ * into one throw.
6
8
  */
7
9
 
8
10
  import { suggestPathEntryFix } from '../story-body/body-format-lints.js';
@@ -157,6 +159,34 @@ function collectChangesErrors(prefix, rawChanges) {
157
159
  return errors;
158
160
  }
159
161
 
162
+ /**
163
+ * A bare `references[]` entry: a path string, or an object with no
164
+ * assumption (the parser's shape for a bare bullet).
165
+ *
166
+ * @param {unknown} entry
167
+ * @returns {string|null} The path, or `null` when the entry is not bare.
168
+ */
169
+ export function bareReferencePath(entry) {
170
+ const raw = typeof entry === 'string' ? entry : bareObjectPath(entry);
171
+ return typeof raw === 'string' && raw.trim() !== '' ? raw.trim() : null;
172
+ }
173
+
174
+ /**
175
+ * @param {unknown} entry
176
+ * @returns {unknown} The `path` of an assumption-less object, else `null`.
177
+ */
178
+ function bareObjectPath(entry) {
179
+ return entry?.assumption == null ? entry?.path : null;
180
+ }
181
+
182
+ /**
183
+ * @param {unknown} entry
184
+ * @returns {boolean} A pinned `{ path, assumption }` object or a bare path.
185
+ */
186
+ function isValidReferenceEntry(entry) {
187
+ return isObjectPathEntry(entry) || bareReferencePath(entry) !== null;
188
+ }
189
+
160
190
  /**
161
191
  * @param {string} prefix
162
192
  * @param {unknown} rawReferences
@@ -166,14 +196,14 @@ function collectReferencesErrors(prefix, rawReferences) {
166
196
  if (rawReferences === undefined || rawReferences === null) return [];
167
197
  if (!Array.isArray(rawReferences)) {
168
198
  return [
169
- `${prefix}: body.references must be an array of { path, assumption } objects when present, got ${typeof rawReferences}.`,
199
+ `${prefix}: body.references must be an array of paths or { path, assumption } objects when present, got ${typeof rawReferences}.`,
170
200
  ];
171
201
  }
172
202
  const errors = [];
173
203
  for (const entry of rawReferences) {
174
- if (!isObjectPathEntry(entry)) {
204
+ if (!isValidReferenceEntry(entry)) {
175
205
  errors.push(
176
- `${prefix}: body.references entry must declare { path: <string>, assumption: one of ${FILE_ASSUMPTION_VALUES.join('|')} }. Got: ${JSON.stringify(entry)}.`,
206
+ `${prefix}: body.references entry must be a bare path or declare { path: <string>, assumption: one of ${FILE_ASSUMPTION_VALUES.join('|')} }. Got: ${JSON.stringify(entry)}.`,
177
207
  );
178
208
  }
179
209
  }
@@ -17,7 +17,7 @@ export const DELIVERABLE_GRANULARITY_GUIDANCE = Object.freeze({
17
17
  /** Binding-vs-advisory authoring altitude and the New-File Contract. */
18
18
  export const AUTHORING_ALTITUDE_GUIDANCE = Object.freeze({
19
19
  altitude:
20
- '**Binding contract vs advisory sketch.** `acceptance[]` and `verify[]` are the Story\'s **binding contract** — the executor MUST satisfy them exactly, and they are the only definition of "done." `changes[]` and `references[]` are an **advisory implementation sketch**: your best prediction of the file footprint, which the executor MAY revise when the real codebase diverges from the sketch. Author `acceptance[]` / `verify[]` to assert the **outcome** independent of any one file layout — never pin an incidental implementation detail (an internal helper name, a private file path) into an acceptance item that the advisory `changes[]` is free to reshape; assert the observable behaviour instead.',
20
+ '**Binding contract vs advisory sketch.** `acceptance[]` and `verify[]` are the Story\'s **binding contract** — the executor MUST satisfy them exactly, and they are the only definition of "done." `changes[]`, `references[]` (the files to read before editing — author them) and `## Context` are an **advisory implementation sketch**: your best prediction of the footprint, which the executor MAY revise when the real codebase diverges from it. Author `acceptance[]` / `verify[]` to assert the **outcome** independent of any one file layout — never pin an incidental implementation detail (an internal helper name, a private file path) into an acceptance item that the advisory `changes[]` is free to reshape; assert the observable behaviour instead.',
21
21
  advisoryCaveat:
22
22
  "**Advisory does not mean unchecked.** `changes[]` paths are still probed against the base branch: a `creates` on an existing path or a `refactors-existing` on an absent one is reported as a dry-run warning, and a `deletes` naming a path absent at base is refused. The executor's latitude to revise the approach never licenses skipping `acceptance[]` / `verify[]` or relaxing any `rules/security-baseline.md` MUST.",
23
23
  newFileContract:
@@ -31,8 +31,25 @@ function collectPathsFromText(text, paths) {
31
31
  }
32
32
  }
33
33
 
34
+ /**
35
+ * A backticked token that reads as a repo-relative path: at least one `/`,
36
+ * no whitespace, glob, scheme or `:line` suffix, and not absolute.
37
+ */
38
+ const BACKTICKED_TOKEN_RE = /`([^`\s]+)`/g;
39
+ const REPO_RELATIVE_PATH_RE = /^(?!\/)[\w.@-]+(?:\/[\w.@-]+)+$/;
40
+
41
+ function collectBacktickedPaths(text, paths) {
42
+ if (!text || typeof text !== 'string') return;
43
+ for (const [, token] of text.matchAll(BACKTICKED_TOKEN_RE)) {
44
+ if (REPO_RELATIVE_PATH_RE.test(token)) paths.add(token);
45
+ }
46
+ }
47
+
34
48
  function collectTaskPathReferences(task) {
35
49
  const paths = new Set();
50
+ // `## Context` names read-first files by any extension, so every
51
+ // backticked path in it is probed, not only the code-asset roots.
52
+ collectBacktickedPaths(resolveChangesSource(task)?.context, paths);
36
53
  const body = task.body;
37
54
  if (typeof body === 'string') {
38
55
  collectPathsFromText(body, paths);
@@ -118,8 +135,9 @@ function makeMemoizedGitRunner(runner) {
118
135
  }
119
136
 
120
137
  /**
121
- * Warn (never refuse) on Story-referenced code paths absent at the base:
122
- * narrative paths are prose, not a contract the validator can enforce.
138
+ * Warn (never refuse) on Story-referenced code paths absent at the base —
139
+ * goal / acceptance / verify code-asset paths and every backticked path in
140
+ * `## Context`: narrative paths are prose, not a contract to enforce.
123
141
  *
124
142
  * @param {object} opts
125
143
  * @param {object[]} opts.tickets
@@ -16,6 +16,14 @@ import {
16
16
  STATE_LABELS,
17
17
  transitionTicketState,
18
18
  } from '../orchestration/ticketing.js';
19
+ import { sleep as defaultSleep } from '../util/poll-loop.js';
20
+
21
+ /**
22
+ * Backoff before each RETRY of the post-merge done flip (so attempts =
23
+ * length + 1). A transient label write is the common failure; the transition
24
+ * is idempotent, so a retry cannot double-apply.
25
+ */
26
+ const DONE_FLIP_RETRY_DELAYS_MS = Object.freeze([500, 2000]);
19
27
 
20
28
  /**
21
29
  * @param {{ cwd: string, prNumber: number, gh?: object }} args
@@ -47,6 +55,8 @@ export async function readPrMergeState({ cwd, prNumber, gh = defaultGh }) {
47
55
  * @param {{ state: string|null, mergedAt: string|null }} [args.prState] The
48
56
  * merge state the caller already read, so a land reads it once; omitted,
49
57
  * it is read here.
58
+ * @param {(ms: number) => Promise<void>} [args.sleepFn] Backoff between
59
+ * done-flip attempts; injectable so tests do not sleep.
50
60
  * @returns {Promise<object>} `done` | `noop` (already-done) | `pending`
51
61
  * (pr-open / pr-not-merged) | `flip-failed`.
52
62
  */
@@ -62,6 +72,7 @@ export async function confirmStoryMerged({
62
72
  injectedNotify,
63
73
  readPrMergeStateFn = readPrMergeState,
64
74
  prState,
75
+ sleepFn = defaultSleep,
65
76
  }) {
66
77
  progress?.('CONFIRM', `Confirming merge for standalone Story #${storyId}...`);
67
78
 
@@ -88,16 +99,17 @@ export async function confirmStoryMerged({
88
99
  }));
89
100
 
90
101
  if (!isPrMerged({ state, mergedAt })) {
91
- const reason = state === 'CLOSED' ? 'pr-not-merged' : 'pr-open';
92
- progress?.(
93
- 'CONFIRM',
94
- `⏳ PR #${prNumber} not yet merged (state=${state ?? 'unknown'}). Story stays at agent::closing.`,
95
- );
96
- return { storyId, action: 'pending', reason, merged: false };
102
+ return pendingResult({ storyId, prNumber, state, progress });
97
103
  }
98
104
 
99
105
  // Best-effort: a flaky API must not crash confirmation; re-runs are idempotent.
100
- const flipped = await flipDone(provider, storyId, story, progress);
106
+ const flipped = await flipDoneWithRetry({
107
+ provider,
108
+ storyId,
109
+ story,
110
+ progress,
111
+ sleepFn,
112
+ });
101
113
  if (flipped) {
102
114
  await fireStoryMergedNotify({
103
115
  notifyFn: injectedNotify ?? defaultNotify,
@@ -115,6 +127,31 @@ export async function confirmStoryMerged({
115
127
  };
116
128
  }
117
129
 
130
+ /** The PR is not merged yet: the Story stays at `agent::closing`. */
131
+ function pendingResult({ storyId, prNumber, state, progress }) {
132
+ const reason = state === 'CLOSED' ? 'pr-not-merged' : 'pr-open';
133
+ progress?.(
134
+ 'CONFIRM',
135
+ `⏳ PR #${prNumber} not yet merged (state=${state ?? 'unknown'}). Story stays at agent::closing.`,
136
+ );
137
+ return { storyId, action: 'pending', reason, merged: false };
138
+ }
139
+
140
+ /** Only a write that fails every bounded attempt reports the flip failed. */
141
+ async function flipDoneWithRetry({
142
+ provider,
143
+ storyId,
144
+ story,
145
+ progress,
146
+ sleepFn,
147
+ }) {
148
+ for (const delayMs of [0, ...DONE_FLIP_RETRY_DELAYS_MS]) {
149
+ if (delayMs > 0) await sleepFn(delayMs);
150
+ if (await flipDone(provider, storyId, story, progress)) return true;
151
+ }
152
+ return false;
153
+ }
154
+
118
155
  async function flipDone(provider, storyId, story, progress) {
119
156
  try {
120
157
  await transitionTicketState(provider, storyId, STATE_LABELS.DONE, {
@@ -33,6 +33,7 @@ import { isFooterSeparator, parseFooterBlockedByRefs } from './footer-block.js';
33
33
  * @property {string} goal
34
34
  * @property {string} slicing - Intra-Story slice plan; '' when absent.
35
35
  * @property {string} spec - Folded Tech Spec; '' when absent.
36
+ * @property {string} context - Planner handoff facts; '' when absent.
36
37
  * @property {PathEntry[]} changes
37
38
  * @property {string[]} acceptance
38
39
  * @property {string[]} verify
@@ -58,6 +59,7 @@ import { isFooterSeparator, parseFooterBlockedByRefs } from './footer-block.js';
58
59
  * @property {boolean} hasNonGoalsSection
59
60
  * @property {boolean} hasSlicingSection
60
61
  * @property {boolean} hasSpecSection
62
+ * @property {boolean} hasContextSection
61
63
  * @property {boolean} isUnstructuredBody - True when no structured sections were found.
62
64
  */
63
65
 
@@ -87,13 +89,17 @@ const HEADING_TO_FIELD = new Map([
87
89
  ['goal', 'goal'],
88
90
  ['slicing', 'slicing'],
89
91
  ['spec', 'spec'],
92
+ ['context', 'context'],
90
93
  ['changes', 'changes'],
91
94
  ['acceptance', 'acceptance'],
92
95
  ['verify', 'verify'],
93
96
  ['references', 'references'],
94
97
  ['non_goals', 'non_goals'],
95
98
  ]);
96
- const TEXT_BLOCK_FIELDS = new Set(['slicing', 'spec']);
99
+ const TEXT_BLOCK_FIELDS = new Set(['slicing', 'spec', 'context']);
100
+ // Recognized only at `##`: a `### Context` sub-heading inside a Spec stays
101
+ // Spec prose. Context is planner-authored, never an Issue Form label.
102
+ const H2_ONLY_FIELDS = new Set(['context']);
97
103
 
98
104
  /**
99
105
  * @param {string} line
@@ -278,9 +284,8 @@ function splitSections(markdown) {
278
284
  // `##` or `###` (GitHub Issue Forms render labels as level 3). The token
279
285
  // is a single `[\w-]+` word so `Non-Goals` matches; multi-word headings
280
286
  // fall through to the terminator branch below.
281
- const fieldHeadingMatch = line.match(/^#{2,3}\s+([\w-]+)\s*$/i);
282
- const fieldName = fieldHeadingMatch?.[1]?.toLowerCase().replace(/-/g, '_');
283
- if (HEADING_TO_FIELD.has(fieldName)) {
287
+ const fieldName = matchFieldHeading(line);
288
+ if (fieldName !== null) {
284
289
  inPreamble = false;
285
290
  currentSection = fieldName;
286
291
  if (!sections.has(currentSection)) sections.set(currentSection, []);
@@ -307,6 +312,21 @@ function splitSections(markdown) {
307
312
  return { sections, footer, preamble };
308
313
  }
309
314
 
315
+ /**
316
+ * The canonical field a `##` / `###` heading opens, or `null`. The token is a
317
+ * single `[\w-]+` word, lower-cased with `-` folded to `_`.
318
+ *
319
+ * @param {string} line
320
+ * @returns {string|null}
321
+ */
322
+ function matchFieldHeading(line) {
323
+ const match = line.match(/^(#{2,3})\s+([\w-]+)\s*$/);
324
+ if (match === null) return null;
325
+ const fieldName = match[2].toLowerCase().replace(/-/g, '_');
326
+ if (!HEADING_TO_FIELD.has(fieldName)) return null;
327
+ return H2_ONLY_FIELDS.has(fieldName) && match[1] !== '##' ? null : fieldName;
328
+ }
329
+
310
330
  /**
311
331
  * A non-canonical heading closes the current section so appended extended
312
332
  * content (e.g. `## Agent Prompts`) never bleeds into `verify[]` /
@@ -354,6 +374,7 @@ function parseUnstructuredBody(input, preamble, footer) {
354
374
  goal: preamble || input.trim(),
355
375
  slicing: '',
356
376
  spec: '',
377
+ context: '',
357
378
  changes: [],
358
379
  acceptance: [],
359
380
  verify: [],
@@ -373,6 +394,7 @@ function parseUnstructuredBody(input, preamble, footer) {
373
394
  hasNonGoalsSection: false,
374
395
  hasSlicingSection: false,
375
396
  hasSpecSection: false,
397
+ hasContextSection: false,
376
398
  isUnstructuredBody: true,
377
399
  },
378
400
  };
@@ -481,6 +503,7 @@ export function parse(input) {
481
503
  const hasNonGoalsSection = sections.has('non_goals');
482
504
  const hasSlicingSection = sections.has('slicing');
483
505
  const hasSpecSection = sections.has('spec');
506
+ const hasContextSection = sections.has('context');
484
507
 
485
508
  const isUnstructuredBody =
486
509
  !hasGoalSection &&
@@ -495,6 +518,7 @@ export function parse(input) {
495
518
  const goal = parseGoalSection(sections.get('goal') ?? []);
496
519
  const slicing = parseTextBlockSection(sections.get('slicing') ?? []);
497
520
  const spec = parseTextBlockSection(sections.get('spec') ?? []);
521
+ const context = parseTextBlockSection(sections.get('context') ?? []);
498
522
  const changes = parsePathEntrySection(
499
523
  sections.get('changes') ?? [],
500
524
  warnings,
@@ -514,6 +538,7 @@ export function parse(input) {
514
538
  goal,
515
539
  slicing,
516
540
  spec,
541
+ context,
517
542
  changes,
518
543
  acceptance,
519
544
  verify,
@@ -534,6 +559,7 @@ export function parse(input) {
534
559
  hasNonGoalsSection,
535
560
  hasSlicingSection,
536
561
  hasSpecSection,
562
+ hasContextSection,
537
563
  isUnstructuredBody: false,
538
564
  },
539
565
  };
@@ -565,6 +591,7 @@ function parseStructuredObject(obj) {
565
591
  hasNonGoalsSection: 'non_goals' in obj,
566
592
  hasSlicingSection: 'slicing' in obj,
567
593
  hasSpecSection: 'spec' in obj,
594
+ hasContextSection: 'context' in obj,
568
595
  isUnstructuredBody: false,
569
596
  },
570
597
  };
@@ -579,6 +606,7 @@ const STRUCTURED_FIELD_SPECS = [
579
606
  { name: 'goal', kind: 'text' },
580
607
  { name: 'slicing', kind: 'text' },
581
608
  { name: 'spec', kind: 'text' },
609
+ { name: 'context', kind: 'text' },
582
610
  { name: 'changes', kind: 'pathEntryList' },
583
611
  { name: 'acceptance', kind: 'stringList' },
584
612
  { name: 'verify', kind: 'stringList' },
@@ -644,6 +672,13 @@ const SERIALIZE_SECTIONS = [
644
672
  ? `## Spec\n${spec.trim()}`
645
673
  : null,
646
674
  },
675
+ {
676
+ field: 'context',
677
+ render: (context) =>
678
+ typeof context === 'string' && context.trim().length > 0
679
+ ? `## Context\n${context.trim()}`
680
+ : null,
681
+ },
647
682
  {
648
683
  field: 'changes',
649
684
  render: (changes) =>
@@ -690,7 +725,7 @@ function serializeFooter(body, opts) {
690
725
  if (!opts.includeFooter) return '';
691
726
  const footerLines = ['---'];
692
727
  if (opts.footer?.parent) footerLines.push(`parent: #${opts.footer.parent}`);
693
- // Never an `Epic: #N` line: pr-base-guard.js refuses a body carrying one.
728
+ // Never an `Epic: #N` line: resolve-stories.js refuses a body carrying one.
694
729
  if (Array.isArray(body.depends_on)) {
695
730
  for (const dep of body.depends_on) {
696
731
  footerLines.push(`blocked by ${dep}`);
@@ -36,7 +36,7 @@ export function renderStoryAuthorCore() {
36
36
  ### HIERARCHY RULES (v2 default-single):
37
37
  1. **Emit exactly one Story by default.** Split into N>1 only when pieces have near-zero overlap or sit across an architectural seam. Coupled work stays one Story — put intra-session checkpoints in \`## Slicing\` and fold the Tech Spec into \`## Spec\`.
38
38
  2. **Stories**: Specific user-facing or architectural capabilities (e.g., "Implement JWT Token Exchange").
39
- - **Story-Level Execution**: Each Story is executed end-to-end on a single branch by a single agent. Acceptance criteria and verification commands live as top-level \`acceptance[]\` / \`verify[]\` arrays on the Story ticket (see STORY BODY SCHEMA below).
39
+ - **Story-Level Execution**: Each Story is executed end-to-end on a single branch by a single agent, against top-level \`acceptance[]\` / \`verify[]\` arrays (see STORY BODY SCHEMA below).
40
40
  - Thematic grouping is prose in the Story's folded \`## Spec\` / \`## Slicing\`, never sibling tickets for coupled work.
41
41
 
42
42
  ### LABEL CONVENTIONS:
@@ -47,65 +47,64 @@ export function renderStoryAuthorCore() {
47
47
  **Slug format**: \`^[a-z0-9][a-z0-9-]*$\` — hyphen-case only. Underscores are rejected by the validator.
48
48
 
49
49
  ### STORY BODY SCHEMA (REQUIRED FOR EVERY STORY):
50
- \`body\` is either the serialized markdown **string** (the section format below) or a **structured object** carrying the same fields (\`goal\`, optional \`slicing\` / \`spec\`, \`changes\`, optional \`non_goals\`) — persist parses either shape and serializes the canonical markdown itself, so you never need to read \`story-body.js\` or hand-assemble the markdown (the \`stories.template.json\` file emitted next to the plan-context envelope is a ready-to-fill structured-object skeleton). The executing sub-agent is non-interactive and self-verifies from the ticket alone, so the ticket carries everything it needs.
50
+ \`body\` is either the serialized markdown **string** (the section format below) or a **structured object** carrying the same fields (\`goal\`, optional \`slicing\` / \`spec\` / \`context\`, \`changes\`, optional \`references\` / \`non_goals\`) — persist parses either shape and serializes the canonical markdown itself, so you never need to read \`story-body.js\` or hand-assemble the markdown (the \`stories.template.json\` file emitted next to the plan-context envelope is a ready-to-fill structured-object skeleton). The deliverer is non-interactive and may be a smaller model than you: the ticket is its whole handoff, so it carries the research and the decisions you already made.
51
51
 
52
- The \`acceptance[]\` and \`verify[]\` arrays live at the **top level** of the Story ticket object — that is the machine contract the validator reads. Author each list **once, at top level**, and **omit** the \`## Acceptance\` / \`## Verify\` sections from the authored \`body\` string: persist syncs the top-level arrays into those sections so the GitHub issue stays a complete executable document. The validator resolves both fields from the top level, so an omitted section is the expected shape, not a violation.
52
+ \`acceptance[]\` and \`verify[]\` live at the **top level** of the ticket — the machine contract the validator reads. Author each **once, there**, and omit \`## Acceptance\` / \`## Verify\` from \`body\`: persist syncs them in, and fails closed on a body section that disagrees with its array. Never invent a second criteria list inside \`## Spec\`, nor a separate Acceptance Spec / PRD artifact.
53
53
 
54
- Never hand-mirror either list into the \`body\` — there is no step that asks you to. Persist fails closed on a body section that disagrees with its top-level array rather than guessing which list is authoritative, so writing one anyway only adds a way to be wrong. Do **not** invent a second criteria list inside \`## Spec\`, and do not author a separate Acceptance Spec / PRD artifact.
55
-
56
- The **persisted** \`body\` renders these markdown sections (in order) — you author every one of them except \`## Acceptance\` / \`## Verify\`, which persist synthesizes from the top-level arrays:
54
+ The **persisted** \`body\` renders these sections in order:
57
55
 
58
56
  ## Goal
59
57
  <one sentence — why this Story exists>
60
58
 
61
59
  ## Slicing
62
- <optional ordered intra-session checkpoints — not a second Spec or AC table>
60
+ <optional ordered checkpoints, each may end — verify: <exact command>>
63
61
 
64
62
  ## Spec
65
- <optional technical approach at contract level — do NOT restate Goal / Acceptance / Verify>
63
+ <optional decided approach at contract level — do NOT restate Goal / Acceptance / Verify>
64
+
65
+ ## Context
66
+ <optional handoff facts — entry points, pattern to mirror, harness, traps, scoped test command>
66
67
 
67
68
  ## Changes
68
69
  - <file path>
69
70
  - {"path": "<file path>", "assumption": "deletes"}
70
- - ...
71
71
 
72
72
  ## Acceptance <-- synthesized by persist from acceptance[]; do not author
73
73
  - [ ] <outcome a PR reviewer can confirm>
74
- - ...
75
74
 
76
75
  ## Verify <-- synthesized by persist from verify[]; do not author
77
76
  - <exact command or test path>
78
- - ...
77
+
78
+ ## References
79
+ - <file the deliverer reads before editing>
79
80
 
80
81
  ## Non-Goals
81
82
  - <a capability or change this Story explicitly does NOT deliver>
82
- - ...
83
83
 
84
84
  #### STORY BODY RULES:
85
85
 
86
- - **goal** (in body string): One sentence stating WHY this Story exists.
87
- - **spec** (optional, in body string as \`## Spec\`): The technical approach at the altitude the SPEC PROSE CONTRACT below fixes — contract and invariants, never implementation narration. Write as much as the work needs and no more; persist keeps Specs inline at any length and never writes them under \`docs/\`.
88
- - **slicing** (optional): Ordered intra-session checkpoints for one Story, one line each. A checkpoint is a **stage of the work** — a commit boundary the deliverer passes through inside one session, stated as the step it performs. An acceptance item is a **state of the codebase** a PR reviewer confirms once the Story has landed. The same Story therefore carries both: the checkpoints say in what order it is built, \`acceptance[]\` says what must then be true. Never a fan-out table, never a second acceptance list, and never sibling tickets — a broad sweep with many stages is still one Story, sliced here.
89
- - **changes** (in body string): Each entry is a **bare path string** — the default form; persist derives its assumption by probing the base branch and reports the derivation. Use the object form \`{ path, assumption }\` (\`assumption\` one of \`creates | refactors-existing | deletes\`) only to pin one yourself, and always for a \`deletes\`, which a bare path can never express. **Name the files the deliverer authors, and omit generated artifacts** — quality baselines, generated test indexes, migration journals, lockfiles and the like are regenerated by the work itself, the refresh is a close-gate concern, and declaring one needlessly reserves a footprint that serializes sibling Stories at dispatch. Acceptable path shapes include explicit files (\`src/components/Foo.tsx\`), glob patterns (\`tests/e2e/*.spec.ts\`, \`**/*.astro\`), and module identifiers that resolve to files. Pin \`refactors-existing\` for an in-place edit, \`creates\` for a net-new file, \`deletes\` for a removal, whenever the probe would get it wrong. Persist probes every path against the base branch and derives the assumption for you, so a \`creates\` on an existing path or a \`refactors-existing\` on an absent one is a dry-run warning; only a \`deletes\` naming an absent path is refused.
90
- - **acceptance** (top-level array on the ticket object): Each item is an **outcome a PR reviewer can confirm from the diff and the verify output** — what is true of the codebase once the Story lands, stated at the altitude of the capability (a command that now exits 0 against a named input, a behavior a named test now asserts, a config that now fails validation on a retired key, a document that now records a decision). State as many outcomes as the capability has and no more — the list has no target, floor or ceiling, and a long one is never a reason to split the Story. Push grep-shaped probes, file-exists checks and exit-code tests down into \`verify[]\`; never pin an internal helper name or a private file path into an acceptance item the advisory \`changes[]\` is free to reshape. UNACCEPTABLE: "verify by reading the diff", "looks good", "matches the spec".
91
- - **verify** (top-level array on the ticket object): The **mechanical checks** — exact commands or test paths the deliverer runs and the acceptance critic consumes as evidence: \`node --test tests/x.test.js\`, \`npm run lint\`, \`npm run validate\`, a scoped grep. Every acceptance item should be confirmable from at least one verify entry's output plus the diff. A Story with no verify entry is warned about, not rejected — but the critic then has nothing to read as evidence, so author the commands.
92
- - **Bodies record decisions, never questions to the operator.** Never persist an open question ("Flag if…", "TBD", "confirm with the operator") into a Story body — the executing sub-agent is non-interactive and cannot answer it, and the dry-run warns on every one it finds. Triage each unknown by who can resolve it: an AFK-shaped unknown (a fact in docs, a third-party API surface, observable repo behavior) MUST be resolved by your own research before authoring — never restated as an assumption; only a HITL-shaped unknown (a genuine product or architecture call the operator owns) may be restated as a declarative Key Assumption the agent can act on, stating the default chosen (a decision-made-by-default).
93
- - **non_goals** (OPTIONAL, in body string as the \`## Non-Goals\` section): A short list of capabilities or changes this Story explicitly does NOT deliver — an advisory negative-scope bound that fences the executing agent away from adjacent work. It is **advisory and NON-GATING**: the validator does not require, count, or reject on it, and an absent or empty section renders nothing. Use the EXACT single-word hyphenated heading spelling \`## Non-Goals\` (a space-separated heading like \`## Out of Scope\` is NOT recognized by the parser and will be dropped). Reach for it when a Story's negative boundary is non-obvious from its \`acceptance[]\` alone; omit it otherwise.
94
-
95
- #### SPEC PROSE CONTRACT — state the contract, not the implementation:
96
-
97
- The Story is executed by a frontier-model deliverer that reads the codebase itself. Author \`## Spec\` (and Goal prose) at contract level:
98
-
99
- - **Spec states the contract and invariants**: interfaces, status codes, security invariants, and load-bearing constraints — each with its why. That is the whole job of the Spec.
100
- - **Implementation choices belong to the deliverer** unless a choice is load-bearing; a load-bearing choice is stated as a constraint (with why it binds), never as a walkthrough of how to code it.
101
- - **No per-file behavior paragraphs.** The \`## Changes\` list already names the footprint; do not narrate what each file will do.
102
- - **No current-state narration.** Do not describe how the codebase works today as scene-setting; the deliverer reads the code. State only the claims a decision depends on.
103
- - **Do not author a \`## References\` section.** Read-only context the deliverer needs is discoverable from the contract and the footprint.
104
- - **Acceptance criteria remain the binding contract** — the Spec constrains and explains; \`acceptance[]\` binds.
86
+ - **goal**: One sentence stating WHY this Story exists.
87
+ - **spec** (optional): The decided approach at the altitude the SPEC PROSE CONTRACT below fixes. As long as the work needs; persist keeps Specs inline at any length and never writes them under \`docs/\`.
88
+ - **slicing** (optional): Ordered intra-session checkpoints, one line each. A checkpoint is a **stage of the work** — a commit boundary the deliverer passes through, stated as the step it performs. An acceptance item is a **state of the codebase** a PR reviewer confirms once the Story has landed. Never a second acceptance list, never sibling tickets. End a checkpoint with \`— verify: <exact command>\` so the deliverer can prove it before moving on — encouraged past two checkpoints.
89
+ - **context** (optional): The facts you verified while planning, so the deliverer does not rediscover them — entry points (file + symbol), the existing pattern to mirror, the test file or harness to extend, known traps, the scoped test command. Terse verified facts, never a walkthrough. Backticked paths are probed at persist; one absent at base is a warning.
90
+ - **changes**: Each entry is a **bare path string** — the default; persist derives its assumption by probing the base branch and reports the derivation. Pin the object form \`{ path, assumption }\` (\`creates | refactors-existing | deletes\`) only when the probe would get it wrong, and always for a \`deletes\`, which a bare path can never express. Globs (\`tests/e2e/*.spec.ts\`) are accepted. **Name the files the deliverer authors, and omit generated artifacts** — quality baselines, generated indexes, lockfiles and the like are regenerated by the work itself, and declaring one needlessly reserves a footprint that serializes sibling Stories at dispatch. A \`creates\` on an existing path or a \`refactors-existing\` on an absent one is a dry-run warning; only a \`deletes\` naming an absent path is refused.
91
+ - **references** (optional): The files the deliverer should read before editing but does not change. A bare path; persist derives \`exists\` and warns when one is absent at base.
92
+ - **acceptance** (top-level array): Each item is an **outcome a PR reviewer can confirm from the diff and the verify output** — what is true of the codebase once the Story lands, at the altitude of the capability (a command that now exits 0 against a named input, a behavior a named test now asserts, a config that now fails validation on a retired key). State as many outcomes as the capability has — the list has no target, floor or ceiling, and a long one is never a reason to split the Story. Push grep-shaped probes, file-exists checks and exit-code tests down into \`verify[]\`. UNACCEPTABLE: "verify by reading the diff", "looks good", "matches the spec".
93
+ - **verify** (top-level array): The **mechanical checks** — exact commands or test paths the deliverer runs and the acceptance critic reads as evidence: \`node --test tests/x.test.js\`, \`npm run lint\`, a scoped grep. Every acceptance item should be confirmable from at least one verify entry's output plus the diff. An empty list is warned about, not rejected — but leaves the critic no evidence.
94
+ - **Bodies record decisions, never questions to the operator.** Never persist an open question ("Flag if…", "TBD", "confirm with the operator") — the deliverer cannot answer it, and the dry-run warns on each. Triage each unknown: an AFK-shaped unknown (a fact in docs, a third-party API surface, observable repo behavior) MUST be resolved by your own research before authoring; only a HITL-shaped unknown (a product or architecture call the operator owns) may be restated as a declarative Key Assumption stating the default chosen (a decision-made-by-default).
95
+ - **non_goals** (optional, heading exactly \`## Non-Goals\`): Capabilities or changes this Story explicitly does NOT deliver — an advisory, non-gating fence away from adjacent work. Reach for it when the negative boundary is non-obvious from \`acceptance[]\`.
96
+
97
+ #### SPEC PROSE CONTRACT — decide the mechanism, state the contract:
98
+
99
+ - **Spec decides.** Choose every load-bearing mechanism and state it with its why; leave a choice to the deliverer only when it is genuinely not load-bearing. A deliverer left to pick a mechanism re-litigates your research.
100
+ - **Spec states the contract and invariants**: interfaces, status codes, security invariants, load-bearing constraints — never a walkthrough of how to code them.
101
+ - **No per-file behavior paragraphs.** \`## Changes\` names the footprint; \`## Context\` names where to start.
102
+ - **Facts go in Context, not Spec.** State in the Spec only the claims a decision depends on; the rest of what you verified goes in \`## Context\`, tersely.
103
+ - **Acceptance criteria remain the binding contract** — Spec, Context, References and checkpoint verify commands are advisory; \`acceptance[]\` / \`verify[]\` bind.
105
104
 
106
105
  #### DETERMINISTIC BODY-FORMAT LINTS — author lint-clean by construction:
107
106
 
108
- Persist enforces the deterministic body-format rules below and **rejects** an authored body that violates any of them. Author every Story to satisfy all of them on the FIRST draft — each rule is stated example-first so there is nothing to discover by trial-and-error. \`changes-path-entry-shape\` is the one rule persist repairs for you: a plain-string bullet whose path can be salvaged is rewritten into the object form by probing the base branch, and the repair is reported in the dry-run output.
107
+ Persist **rejects** an authored body that violates any rule below, so satisfy all of them on the FIRST draft. \`changes-path-entry-shape\` is the one rule persist repairs for you: a salvageable plain-string bullet is rewritten into the object form by probing the base branch, and the repair is reported in the dry-run output.
109
108
 
110
109
  ${bodyFormatLintChecklist}
111
110
 
@@ -121,12 +120,10 @@ ${advisoryCaveat}
121
120
 
122
121
  **Decompose at deliverable granularity, not module/task level.** ${granularityDefinition}
123
122
 
124
- The only sizing question is **cohesion**: *is this one coherent change with one reason to exist?* There is no target, floor or ceiling on a Story's footprint, Spec length or acceptance count, and a long acceptance list is a description of a broad capability, never a reason to split. A broad contract cutover is one Story when every changed site changes for the same reason. Frontier models one-shot capability-sized work in a single pass; do not fragment a coherent capability into dependent slices to stay "small", and do not pad a Story with adjacent work to look "complete".
123
+ The only sizing question is **cohesion**: *is this one coherent change with one reason to exist?* There is no target, floor or ceiling on a Story's footprint, Spec length or acceptance count. A broad contract cutover is one Story when every changed site changes for the same reason; do not fragment a coherent capability into dependent slices to stay "small", nor pad a Story with adjacent work.
125
124
 
126
125
  ${envelopeFloor}
127
126
 
128
- - **One Story = one coherent change with one reason to exist.**
129
- - **A remediation sweep over one subsystem is one Story.** A batch of findings in the same subsystem shares one reason to exist — the subsystem is wrong — so it arrives as one Story whose \`## Slicing\` checkpoints carry the stages, not as one Story per finding.
130
127
  - ${singleConsumerRule}
131
128
 
132
129
  #### UI AND COPY WORK — where the contract is written down:
@@ -180,7 +177,7 @@ You are planning from one or more existing tickets. Read them for **what the wor
180
177
  2. **A mechanical check is a \`verify[]\` command, not an acceptance item.** "Baselines refreshed", "lint exits 0", "the generated index is regenerated", "the quality gate passes" are commands the deliverer runs and the critic reads as evidence. Carrying them as acceptance items inflates the binding contract with work every close already gates.
181
178
  3. **Read the source's \`verify[]\` for the commands it names, not for its shape.** Take the test paths and scripts; drop any trailing tier suffix (\`(unit)\`, \`(contract)\`, \`(e2e)\`, \`(validate)\`) and any \`manual:<reason>\` escape — a verify entry is a bare command.
182
179
  4. **Re-derive the footprint against the tree as it is now.** The source ticket's \`## Changes\` predicted a repository that has since moved; probe the paths you cite and omit the generated artifacts it listed.
183
- 5. **Do not carry the source's prose wholesale.** Its current-state narration and per-file walkthroughs are exactly what the SPEC PROSE CONTRACT above forbids. Restate the contract and the invariants; the deliverer reads the code for the rest.`;
180
+ 5. **Do not carry the source's prose wholesale.** Its per-file walkthroughs are exactly what the SPEC PROSE CONTRACT above forbids. Restate the decided contract and invariants in \`## Spec\`, and carry only the facts you re-verified against the tree into \`## Context\`.`;
184
181
  }
185
182
 
186
183
  /**
@@ -376,6 +376,7 @@ function buildWatchArgs({
376
376
  ghPrChecksFn,
377
377
  ghPrViewFn,
378
378
  ghPrUpdateBranchFn,
379
+ ghApiFn,
379
380
  sleepFn,
380
381
  logger,
381
382
  }) {
@@ -390,6 +391,7 @@ function buildWatchArgs({
390
391
  ...(ghPrChecksFn ? { ghPrChecksFn } : {}),
391
392
  ...(ghPrViewFn ? { ghPrViewFn } : {}),
392
393
  ...(ghPrUpdateBranchFn ? { ghPrUpdateBranchFn } : {}),
394
+ ghApiFn,
393
395
  ...(sleepFn ? { sleepFn } : {}),
394
396
  logger,
395
397
  };
@@ -605,6 +607,7 @@ async function settleRedWatch({
605
607
  * @param {Function} [opts.ghPrChecksFn]
606
608
  * @param {Function} [opts.ghPrViewFn]
607
609
  * @param {Function} [opts.ghPrUpdateBranchFn]
610
+ * @param {Function} [opts.ghApiFn]
608
611
  * @param {Function} [opts.sleepFn]
609
612
  * @param {Function} [opts.writeDigestFn]
610
613
  * @param {Function} [opts.readDigestFn]
@@ -630,6 +633,7 @@ export async function runPrWatch({
630
633
  ghPrChecksFn,
631
634
  ghPrViewFn,
632
635
  ghPrUpdateBranchFn,
636
+ ghApiFn,
633
637
  sleepFn,
634
638
  writeDigestFn = writeCiDigest,
635
639
  readDigestFn = readCiDigest,
@@ -676,6 +680,7 @@ export async function runPrWatch({
676
680
  ghPrChecksFn,
677
681
  ghPrViewFn,
678
682
  ghPrUpdateBranchFn,
683
+ ghApiFn,
679
684
  sleepFn,
680
685
  logger,
681
686
  }),