mandrel 1.92.0 → 1.94.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 (144) hide show
  1. package/.agents/agents/acceptance-critic.md +129 -0
  2. package/.agents/agents/retro.md +42 -0
  3. package/.agents/agents/story-worker.md +162 -0
  4. package/.agents/docs/configuration.md +7 -1
  5. package/.agents/docs/execution-reference.md +27 -2
  6. package/.agents/instructions.md +43 -33
  7. package/.agents/personas/engineer.md +26 -112
  8. package/.agents/personas/security-engineer.md +1 -2
  9. package/.agents/rules/git-conventions-reference.md +225 -0
  10. package/.agents/rules/git-conventions.md +25 -200
  11. package/.agents/rules/security-baseline.md +5 -0
  12. package/.agents/rules/testing-standards.md +106 -13
  13. package/.agents/schemas/agentrc.schema.json +31 -1
  14. package/.agents/schemas/lifecycle/slice.end.schema.json +21 -0
  15. package/.agents/schemas/lifecycle/slice.heartbeat.schema.json +20 -0
  16. package/.agents/schemas/lifecycle/slice.start.schema.json +17 -0
  17. package/.agents/scripts/acceptance-eval.js +62 -18
  18. package/.agents/scripts/agents-bootstrap-github.js +1 -1
  19. package/.agents/scripts/bookkeeping-reconcile.js +117 -0
  20. package/.agents/scripts/check-context-budget.js +62 -5
  21. package/.agents/scripts/diagnose-friction.js +0 -6
  22. package/.agents/scripts/epic-deliver-prepare.js +272 -10
  23. package/.agents/scripts/lib/bootstrap/project-bootstrap.js +56 -18
  24. package/.agents/scripts/lib/close-validation/gates.js +159 -21
  25. package/.agents/scripts/lib/config/acceptance-eval.js +52 -5
  26. package/.agents/scripts/lib/config/delivery-routing.js +87 -0
  27. package/.agents/scripts/lib/config/explain.js +2 -0
  28. package/.agents/scripts/lib/config-resolver.js +1 -1
  29. package/.agents/scripts/lib/config-settings-schema-delivery.js +37 -3
  30. package/.agents/scripts/lib/config-settings-schema-quality.js +9 -0
  31. package/.agents/scripts/lib/doc-tiers.js +37 -2
  32. package/.agents/scripts/lib/observability/active-story-env.js +111 -2
  33. package/.agents/scripts/lib/observability/hook-heartbeat.js +219 -0
  34. package/.agents/scripts/lib/observability/tool-trace-hook.js +15 -4
  35. package/.agents/scripts/lib/orchestration/acceptance-clusters.js +111 -0
  36. package/.agents/scripts/lib/orchestration/acceptance-eval-decision.js +32 -4
  37. package/.agents/scripts/lib/orchestration/bookkeeping-outbox.js +270 -0
  38. package/.agents/scripts/lib/orchestration/ceremony-routing.js +141 -0
  39. package/.agents/scripts/lib/orchestration/context-hydration-engine.js +3 -124
  40. package/.agents/scripts/lib/orchestration/deliver-route.js +173 -0
  41. package/.agents/scripts/lib/orchestration/epic-plan-spec/phases/authoring-context.js +1 -1
  42. package/.agents/scripts/lib/orchestration/epic-run-state-store.js +233 -0
  43. package/.agents/scripts/lib/orchestration/file-assumptions.js +68 -7
  44. package/.agents/scripts/lib/orchestration/lifecycle/emit-slice-lifecycle.js +270 -0
  45. package/.agents/scripts/lib/orchestration/lifecycle/listeners/acceptance-reconciler.js +83 -2
  46. package/.agents/scripts/lib/orchestration/lifecycle/listeners/checkpoint-pointer-writer.js +6 -0
  47. package/.agents/scripts/lib/orchestration/plan-context.js +189 -3
  48. package/.agents/scripts/lib/orchestration/plan-critic-conditions.js +3 -2
  49. package/.agents/scripts/lib/orchestration/plan-critics-evaluate.js +99 -0
  50. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +38 -1
  51. package/.agents/scripts/lib/orchestration/plan-persist/summary.js +16 -1
  52. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +1 -0
  53. package/.agents/scripts/lib/orchestration/story-close/pre-merge-validation.js +1 -0
  54. package/.agents/scripts/lib/orchestration/ticket-validator.js +19 -2
  55. package/.agents/scripts/lib/provider-factory.js +1 -1
  56. package/.agents/scripts/lib/templates/decomposer-prompts.js +1 -1
  57. package/.agents/scripts/plan-context.js +28 -10
  58. package/.agents/scripts/post-structured-comment.js +38 -0
  59. package/.agents/scripts/slice-phase.js +361 -0
  60. package/.agents/scripts/sync-claude-agents.js +165 -0
  61. package/.agents/scripts/update-ticket-state.js +31 -0
  62. package/.agents/scripts/wave-tick.js +138 -9
  63. package/.agents/skills/core/api-and-interface-design/SKILL.md +5 -3
  64. package/.agents/skills/core/code-review-and-quality/SKILL.md +63 -7
  65. package/.agents/skills/core/debugging-and-error-recovery/SKILL.md +1 -1
  66. package/.agents/skills/core/epic-plan-consolidate/SKILL.md +5 -5
  67. package/.agents/skills/core/epic-plan-decompose-author/SKILL.md +8 -8
  68. package/.agents/skills/core/epic-plan-premortem/SKILL.md +4 -4
  69. package/.agents/skills/core/epic-plan-spec-author/SKILL.md +26 -56
  70. package/.agents/skills/core/gates-and-baselines/SKILL.md +149 -0
  71. package/.agents/skills/core/idea-refinement/SKILL.md +2 -8
  72. package/.agents/skills/core/qa-coverage-mapping/SKILL.md +7 -7
  73. package/.agents/skills/skills.index.json +11 -381
  74. package/.agents/workflows/deliver.md +47 -4
  75. package/.agents/workflows/helpers/acceptance-self-eval.md +38 -13
  76. package/.agents/workflows/helpers/deliver-epic-reference.md +18 -5
  77. package/.agents/workflows/helpers/deliver-epic-single.md +331 -0
  78. package/.agents/workflows/helpers/deliver-epic.md +51 -8
  79. package/.agents/workflows/helpers/deliver-stories.md +15 -5
  80. package/.agents/workflows/helpers/epic-deliver-story.md +12 -3
  81. package/.agents/workflows/helpers/mandrel-sync-config.md +1 -1
  82. package/.agents/workflows/helpers/plan-epic-reference.md +19 -8
  83. package/.agents/workflows/helpers/plan-epic.md +95 -27
  84. package/.agents/workflows/helpers/scope-triage-gate.md +9 -0
  85. package/.agents/workflows/mandrel-update.md +1 -1
  86. package/.agents/workflows/plan.md +16 -4
  87. package/docs/CHANGELOG.md +23 -0
  88. package/lib/cli/registry.js +95 -0
  89. package/package.json +4 -2
  90. package/.agents/personas/engineer-mobile.md +0 -120
  91. package/.agents/personas/engineer-web.md +0 -111
  92. package/.agents/personas/product.md +0 -94
  93. package/.agents/personas/refactorer.md +0 -113
  94. package/.agents/personas/sre.md +0 -86
  95. package/.agents/personas/ux-designer.md +0 -95
  96. package/.agents/scripts/epic-plan-decompose.js +0 -54
  97. package/.agents/scripts/epic-plan-spec.js +0 -64
  98. package/.agents/scripts/lib/orchestration/skill-capsule-loader.js +0 -109
  99. package/.agents/scripts/plan-critics.js +0 -227
  100. package/.agents/skills/core/baseline-refresh/SKILL.md +0 -181
  101. package/.agents/skills/core/ci-cd-and-automation/SKILL.md +0 -274
  102. package/.agents/skills/core/ci-cd-and-automation/examples.md +0 -211
  103. package/.agents/skills/core/code-simplification/SKILL.md +0 -389
  104. package/.agents/skills/core/context-engineering/SKILL.md +0 -309
  105. package/.agents/skills/core/context-engineering/examples.md +0 -58
  106. package/.agents/skills/core/deprecation-and-migration/SKILL.md +0 -250
  107. package/.agents/skills/core/frontend-ui-engineering/SKILL.md +0 -357
  108. package/.agents/skills/core/hydrate-context/SKILL.md +0 -123
  109. package/.agents/skills/core/idea-refinement/examples.md +0 -437
  110. package/.agents/skills/core/idea-refinement/frameworks.md +0 -135
  111. package/.agents/skills/core/incremental-implementation/SKILL.md +0 -271
  112. package/.agents/skills/core/introducing-a-baseline-gate/SKILL.md +0 -213
  113. package/.agents/skills/core/knowledge-transfer/SKILL.md +0 -180
  114. package/.agents/skills/core/mutation-survivor-remediation/SKILL.md +0 -117
  115. package/.agents/skills/core/performance-optimization/SKILL.md +0 -314
  116. package/.agents/skills/core/planning-and-task-breakdown/SKILL.md +0 -277
  117. package/.agents/skills/core/property-based-testing/SKILL.md +0 -148
  118. package/.agents/skills/core/refactoring-discipline/SKILL.md +0 -111
  119. package/.agents/skills/core/shipping-and-launch/SKILL.md +0 -328
  120. package/.agents/skills/core/spec-driven-development/SKILL.md +0 -252
  121. package/.agents/skills/core/test-driven-development/SKILL.md +0 -475
  122. package/.agents/skills/core/using-agent-skills/SKILL.md +0 -232
  123. package/.agents/skills/stack/architecture/monorepo-path-strategist/SKILL.md +0 -31
  124. package/.agents/skills/stack/architecture/structured-output-zod/SKILL.md +0 -51
  125. package/.agents/skills/stack/architecture/subagent-orchestration/SKILL.md +0 -76
  126. package/.agents/skills/stack/backend/cloudflare-hono-architect/SKILL.md +0 -31
  127. package/.agents/skills/stack/backend/cloudflare-hono-architect/examples/route-template.ts +0 -33
  128. package/.agents/skills/stack/backend/cloudflare-queue-manager/SKILL.md +0 -31
  129. package/.agents/skills/stack/backend/cloudflare-workers/SKILL.md +0 -51
  130. package/.agents/skills/stack/backend/highlevel-crm/SKILL.md +0 -54
  131. package/.agents/skills/stack/backend/sqlite-drizzle-expert/SKILL.md +0 -29
  132. package/.agents/skills/stack/backend/sqlite-drizzle-expert/examples/schema-template.ts +0 -30
  133. package/.agents/skills/stack/backend/stripe-integration/SKILL.md +0 -57
  134. package/.agents/skills/stack/backend/stripe-integration/scripts/listen-stripe.sh +0 -9
  135. package/.agents/skills/stack/backend/turso-sqlite/SKILL.md +0 -48
  136. package/.agents/skills/stack/frontend/astro/SKILL.md +0 -62
  137. package/.agents/skills/stack/frontend/astro-react-island-strategist/SKILL.md +0 -30
  138. package/.agents/skills/stack/frontend/expo-react-native-developer/SKILL.md +0 -29
  139. package/.agents/skills/stack/frontend/google-analytics-v4/SKILL.md +0 -50
  140. package/.agents/skills/stack/frontend/tailwind-v4/SKILL.md +0 -58
  141. package/.agents/skills/stack/frontend/ui-accessibility-engineer/SKILL.md +0 -34
  142. package/.agents/skills/stack/qa/audit-accessibility/SKILL.md +0 -51
  143. package/.agents/skills/stack/qa/lighthouse-baseline/SKILL.md +0 -199
  144. package/.agents/skills/stack/security/backend-security-patterns/SKILL.md +0 -68
@@ -0,0 +1,270 @@
1
+ /**
2
+ * emit-slice-lifecycle.js — Epic #4475 (M4-A).
3
+ *
4
+ * Programmatic emitters for the three single-delivery slice lifecycle events
5
+ * (`slice.start`, `slice.end`, `slice.heartbeat`) — the single-delivery
6
+ * analogues of the per-Story `story.dispatch.start` / `story.dispatch.end` /
7
+ * `story.heartbeat` events. They append one schema-validated NDJSON record to
8
+ * `temp/epic-<id>/lifecycle.ndjson`, mirroring `emit-story-heartbeat.js`.
9
+ *
10
+ * A single-delivery run collapses the whole Epic into one long guarded
11
+ * session walking the `## Delivery Slicing` table on `epic/<id>`. Without a
12
+ * per-Story heartbeat the `/deliver` idle watchdog cannot tell a live session
13
+ * from a dead one, so these events give the long session an inspectable
14
+ * forward-progress signal (`slice.heartbeat`) plus per-slice boundaries
15
+ * (`slice.start` / `slice.end`) the resume path reads back.
16
+ *
17
+ * Introduced INERT in M4-A: the executor that emits these lands in M4-B
18
+ * (`deliver-epic-single.md`). Shipping the emitters + schemas now keeps that
19
+ * PR the flip-only change.
20
+ *
21
+ * The emit is best-effort at the call site (a failure to append MUST NOT
22
+ * block the slice transition itself); callers catch and log via the script's
23
+ * Logger, exactly as the story-heartbeat callers do. These functions still
24
+ * throw on a programming error (bad argument / schema mismatch) so the bug
25
+ * surfaces in tests.
26
+ */
27
+
28
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
29
+ import path from 'node:path';
30
+ import { fileURLToPath } from 'node:url';
31
+
32
+ import Ajv2020 from 'ajv/dist/2020.js';
33
+ import addFormats from 'ajv-formats';
34
+
35
+ import { epicLedgerPath } from '../../config/temp-paths.js';
36
+
37
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
38
+ const SCHEMA_DIR = path.resolve(
39
+ __dirname,
40
+ '..',
41
+ '..',
42
+ '..',
43
+ '..',
44
+ 'schemas',
45
+ 'lifecycle',
46
+ );
47
+
48
+ const VALID_PHASES = new Set([
49
+ 'init',
50
+ 'implementing',
51
+ 'closing',
52
+ 'blocked',
53
+ 'done',
54
+ ]);
55
+
56
+ const VALID_OUTCOMES = new Set(['done', 'blocked', 'failed', 'skipped']);
57
+
58
+ /** Lazily-compiled AJV validators, one per event schema. */
59
+ const _validators = new Map();
60
+
61
+ function getValidator(event) {
62
+ let validator = _validators.get(event);
63
+ if (!validator) {
64
+ const schema = JSON.parse(
65
+ readFileSync(path.join(SCHEMA_DIR, `${event}.schema.json`), 'utf8'),
66
+ );
67
+ const ajv = new Ajv2020({ allErrors: true, strict: false });
68
+ addFormats(ajv);
69
+ validator = ajv.compile(schema);
70
+ _validators.set(event, validator);
71
+ }
72
+ return validator;
73
+ }
74
+
75
+ function assertEpicId(epicId) {
76
+ if (!Number.isInteger(epicId) || epicId < 1) {
77
+ throw new Error('emit-slice-lifecycle: epicId must be a positive integer');
78
+ }
79
+ }
80
+
81
+ function assertSliceId(sliceId) {
82
+ if (typeof sliceId !== 'string' || sliceId.length === 0) {
83
+ throw new Error('emit-slice-lifecycle: sliceId must be a non-empty string');
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Validate `payload` against `<event>.schema.json`, then append it as a single
89
+ * NDJSON `emitted` record to the Epic ledger. Shared tail of all three
90
+ * emitters.
91
+ *
92
+ * @param {string} event
93
+ * @param {object} payload
94
+ * @param {{ epicId: number, timestamp: string, config?: object, ledgerPath?: string }} ctx
95
+ * @returns {{ ledgerPath: string, record: object }}
96
+ */
97
+ function appendSliceEvent(
98
+ event,
99
+ payload,
100
+ { epicId, timestamp, config, ledgerPath: ledgerPathOverride },
101
+ ) {
102
+ const validator = getValidator(event);
103
+ if (!validator(payload)) {
104
+ const detail = (validator.errors ?? [])
105
+ .map((e) => `${e.instancePath || '/'} ${e.message}`)
106
+ .join('; ');
107
+ throw new Error(
108
+ `emit-slice-lifecycle: ${event} payload failed schema validation: ${detail}`,
109
+ );
110
+ }
111
+
112
+ const ledgerPath = ledgerPathOverride ?? epicLedgerPath(epicId, config);
113
+ mkdirSync(path.dirname(ledgerPath), { recursive: true });
114
+ const record = { kind: 'emitted', ts: timestamp, event, payload };
115
+ appendFileSync(ledgerPath, `${JSON.stringify(record)}\n`, 'utf8');
116
+ return { ledgerPath, record };
117
+ }
118
+
119
+ /**
120
+ * Append one `slice.start` record as the executor begins implementing a slice.
121
+ *
122
+ * @param {object} opts
123
+ * @param {number} opts.epicId
124
+ * @param {string} opts.sliceId Stable slice-map key (e.g. `slice-1`).
125
+ * @param {number} [opts.sliceIndex] Zero-based position in the Delivery
126
+ * Slicing table.
127
+ * @param {string} [opts.title] Human-readable slice label.
128
+ * @param {string} [opts.timestamp] ISO-8601 wall clock. Defaults to now().
129
+ * @param {object} [opts.config]
130
+ * @param {string} [opts.ledgerPath] Override for tests.
131
+ * @returns {{ ledgerPath: string, record: object }}
132
+ */
133
+ export function emitSliceStart(opts) {
134
+ const {
135
+ epicId,
136
+ sliceId,
137
+ sliceIndex,
138
+ title,
139
+ timestamp = new Date().toISOString(),
140
+ config,
141
+ ledgerPath,
142
+ } = opts ?? {};
143
+ assertEpicId(epicId);
144
+ assertSliceId(sliceId);
145
+
146
+ const payload = {
147
+ event: 'slice.start',
148
+ epicId,
149
+ sliceId,
150
+ ...(Number.isInteger(sliceIndex) ? { sliceIndex } : {}),
151
+ ...(typeof title === 'string' ? { title } : {}),
152
+ timestamp,
153
+ };
154
+ return appendSliceEvent('slice.start', payload, {
155
+ epicId,
156
+ timestamp,
157
+ config,
158
+ ledgerPath,
159
+ });
160
+ }
161
+
162
+ /**
163
+ * Append one `slice.end` record when a slice finishes. A `done` outcome is
164
+ * what the slice-map checkpoint flips `slices[id].status` to before the walk
165
+ * advances.
166
+ *
167
+ * @param {object} opts
168
+ * @param {number} opts.epicId
169
+ * @param {string} opts.sliceId
170
+ * @param {'done'|'blocked'|'failed'|'skipped'} opts.outcome
171
+ * @param {number} [opts.sliceIndex]
172
+ * @param {number} [opts.durationMs]
173
+ * @param {string} [opts.timestamp]
174
+ * @param {object} [opts.config]
175
+ * @param {string} [opts.ledgerPath]
176
+ * @returns {{ ledgerPath: string, record: object }}
177
+ */
178
+ export function emitSliceEnd(opts) {
179
+ const {
180
+ epicId,
181
+ sliceId,
182
+ outcome,
183
+ sliceIndex,
184
+ durationMs,
185
+ timestamp = new Date().toISOString(),
186
+ config,
187
+ ledgerPath,
188
+ } = opts ?? {};
189
+ assertEpicId(epicId);
190
+ assertSliceId(sliceId);
191
+ if (!VALID_OUTCOMES.has(outcome)) {
192
+ throw new Error(
193
+ `emit-slice-lifecycle: slice.end outcome "${outcome}" must be one of: ${[...VALID_OUTCOMES].join(', ')}`,
194
+ );
195
+ }
196
+
197
+ const payload = {
198
+ event: 'slice.end',
199
+ epicId,
200
+ sliceId,
201
+ ...(Number.isInteger(sliceIndex) ? { sliceIndex } : {}),
202
+ outcome,
203
+ ...(Number.isInteger(durationMs) ? { durationMs } : {}),
204
+ timestamp,
205
+ };
206
+ return appendSliceEvent('slice.end', payload, {
207
+ epicId,
208
+ timestamp,
209
+ config,
210
+ ledgerPath,
211
+ });
212
+ }
213
+
214
+ /**
215
+ * Append one `slice.heartbeat` record from inside a slice's implementation
216
+ * loop — the forward-progress signal the idle watchdog reads for the single
217
+ * long session.
218
+ *
219
+ * @param {object} opts
220
+ * @param {number} opts.epicId
221
+ * @param {string} opts.sliceId
222
+ * @param {string} [opts.phase='implementing'] init|implementing|closing|blocked|done.
223
+ * @param {string} [opts.timestamp]
224
+ * @param {string} [opts.operator] Optional lease-owner handle; included only
225
+ * when a non-empty string is supplied.
226
+ * @param {object} [opts.config]
227
+ * @param {string} [opts.ledgerPath]
228
+ * @returns {{ ledgerPath: string, record: object }}
229
+ */
230
+ export function emitSliceHeartbeat(opts) {
231
+ const {
232
+ epicId,
233
+ sliceId,
234
+ phase = 'implementing',
235
+ timestamp = new Date().toISOString(),
236
+ operator,
237
+ config,
238
+ ledgerPath,
239
+ } = opts ?? {};
240
+ assertEpicId(epicId);
241
+ assertSliceId(sliceId);
242
+ if (!VALID_PHASES.has(phase)) {
243
+ throw new Error(
244
+ `emit-slice-lifecycle: slice.heartbeat phase "${phase}" must be one of: ${[...VALID_PHASES].join(', ')}`,
245
+ );
246
+ }
247
+ if (
248
+ operator !== undefined &&
249
+ (typeof operator !== 'string' || operator.length === 0)
250
+ ) {
251
+ throw new Error(
252
+ 'emit-slice-lifecycle: operator, when supplied, must be a non-empty string',
253
+ );
254
+ }
255
+
256
+ const payload = {
257
+ event: 'slice.heartbeat',
258
+ epicId,
259
+ sliceId,
260
+ phase,
261
+ timestamp,
262
+ ...(operator !== undefined ? { operator } : {}),
263
+ };
264
+ return appendSliceEvent('slice.heartbeat', payload, {
265
+ epicId,
266
+ timestamp,
267
+ config,
268
+ ledgerPath,
269
+ });
270
+ }
@@ -34,6 +34,47 @@
34
34
  */
35
35
 
36
36
  import { reconcileAcceptanceSpec as defaultReconcileAcceptanceSpec } from '../../../../acceptance-spec-reconciler.js';
37
+ import { DELIVERY_SINGLE_LABEL } from '../../deliver-route.js';
38
+ import { read as readEpicRunState } from '../../epic-run-state-store.js';
39
+
40
+ /**
41
+ * Default single-delivery resolver (Epic #4475, M4-B, design §2c). Decides
42
+ * whether the Epic under reconciliation is the single-delivery shape — the
43
+ * signal that flips a `waived` reconcile into a hard failure (the back gate
44
+ * of the non-waivable epic-level acceptance contract). Two sources, primary
45
+ * first:
46
+ *
47
+ * 1. `epic-run-state.deliveryShape === 'single'` — the durable checkpoint
48
+ * the single-delivery prepare writes.
49
+ * 2. The `delivery::single` label on the Epic ticket — the plan-time marker.
50
+ *
51
+ * Best-effort + fail-open-to-fan-out: any probe failure (null provider in a
52
+ * unit fixture, a GitHub read error) degrades to `false` (treat as fan-out),
53
+ * so the defence-in-depth back gate never *invents* a block — the front gate
54
+ * (prepare refusing `acceptance::n-a`) is the primary guard. Tests inject
55
+ * `resolveSingleFn` directly to bypass the probes.
56
+ *
57
+ * @param {{ provider?: object|null, epicId: number, config?: object|null }} args
58
+ * @returns {Promise<boolean>}
59
+ */
60
+ export async function defaultResolveSingle({ provider, epicId }) {
61
+ if (!provider) return false;
62
+ try {
63
+ const checkpoint = await readEpicRunState({ provider, epicId });
64
+ if (checkpoint?.deliveryShape === 'single') return true;
65
+ } catch {
66
+ // Fall through to the label probe.
67
+ }
68
+ try {
69
+ const epic = await provider.getTicket(epicId);
70
+ const labels = Array.isArray(epic?.labels) ? epic.labels : [];
71
+ return labels.some(
72
+ (l) => (typeof l === 'string' ? l : l?.name) === DELIVERY_SINGLE_LABEL,
73
+ );
74
+ } catch {
75
+ return false;
76
+ }
77
+ }
37
78
 
38
79
  /**
39
80
  * Classify a `reconcileAcceptanceSpec` result envelope into the typed
@@ -49,6 +90,16 @@ import { reconcileAcceptanceSpec as defaultReconcileAcceptanceSpec } from '../..
49
90
  * `.waived` and route waived Epics through to PR
50
91
  * creation, while empty-spec Epics still
51
92
  * terminate without a PR via `.skipped`.
93
+ * **Non-waivable under single delivery (Epic #4475,
94
+ * M4-B, design §2c):** when `opts.single` is true the
95
+ * epic-level reconcile is the ONLY acceptance gate
96
+ * left, so a `waived` status is treated as a hard
97
+ * `failed` (reason `single-delivery-non-waivable`)
98
+ * instead of passing through — the back gate that
99
+ * forecloses the cohort's dilution (waived reconcile
100
+ * as the sole gate). The front gate (prepare refusing
101
+ * `acceptance::n-a`) already blocks this at seed time;
102
+ * this is defence in depth.
52
103
  * - `'empty-spec'` → the linked spec exists but declares zero AC IDs.
53
104
  * Treated as "no work to do"; emit `.skipped` with
54
105
  * reason `'empty-spec'` so operators see the
@@ -61,14 +112,23 @@ import { reconcileAcceptanceSpec as defaultReconcileAcceptanceSpec } from '../..
61
112
  * the Epic ticket.
62
113
  *
63
114
  * @param {object|undefined|null} result reconciler envelope.
115
+ * @param {{ single?: boolean }} [opts] `single: true` flips a `waived` status
116
+ * into a hard `failed` (the non-waivable epic reconcile back gate).
64
117
  * @returns {{ outcome: 'ok'|'waived'|'skipped'|'failed', reason?: string }}
65
118
  */
66
- export function classifyReconcileResult(result) {
119
+ export function classifyReconcileResult(result, opts = {}) {
120
+ const single = opts?.single === true;
67
121
  if (!result || typeof result !== 'object') {
68
122
  return { outcome: 'failed', reason: 'reconciler-no-result' };
69
123
  }
70
124
  const status = result.status;
71
125
  if (status === 'waived') {
126
+ if (single) {
127
+ return {
128
+ outcome: 'failed',
129
+ reason: 'single-delivery-non-waivable',
130
+ };
131
+ }
72
132
  return { outcome: 'waived', reason: 'waiver' };
73
133
  }
74
134
  if (status === 'empty-spec') {
@@ -112,6 +172,9 @@ export class AcceptanceReconciler {
112
172
  * injected for the same reason.
113
173
  * @param {Function} [opts.reconcileAcceptanceSpecFn] Override of the
114
174
  * helper for tests; defaults to the production export.
175
+ * @param {Function} [opts.resolveSingleFn] Override of the single-delivery
176
+ * resolver for tests (Epic #4475, M4-B); defaults to `defaultResolveSingle`
177
+ * (checkpoint `deliveryShape` → `delivery::single` label).
115
178
  * @param {{ info?: Function, warn?: Function, debug?: Function }} [opts.logger]
116
179
  */
117
180
  constructor(opts = {}) {
@@ -134,6 +197,7 @@ export class AcceptanceReconciler {
134
197
  this.config = opts.config ?? null;
135
198
  this.reconcileAcceptanceSpecFn =
136
199
  opts.reconcileAcceptanceSpecFn ?? defaultReconcileAcceptanceSpec;
200
+ this.resolveSingleFn = opts.resolveSingleFn ?? defaultResolveSingle;
137
201
  this.logger = opts.logger ?? console;
138
202
  /** @type {Set<string>} `${event}:${seqId}` keys we've handled. */
139
203
  this._seen = new Set();
@@ -256,7 +320,24 @@ export class AcceptanceReconciler {
256
320
  return;
257
321
  }
258
322
 
259
- const classification = classifyReconcileResult(result);
323
+ // Resolve the delivery shape before classifying: under single delivery a
324
+ // `waived` reconcile is non-waivable (design §2c). Best-effort — a probe
325
+ // failure degrades to `false` (fan-out pass-through), never inventing a
326
+ // block.
327
+ let single = false;
328
+ try {
329
+ single = await this.resolveSingleFn({
330
+ provider: this.provider,
331
+ epicId,
332
+ config: this.config,
333
+ });
334
+ } catch (err) {
335
+ this.logger.warn?.(
336
+ `[AcceptanceReconciler] single-delivery probe failed (treating as fan-out): ${err?.message ?? err}`,
337
+ );
338
+ }
339
+
340
+ const classification = classifyReconcileResult(result, { single });
260
341
  if (classification.outcome === 'ok') {
261
342
  await this._emitOk({ event, seqId, baseRead });
262
343
  return;
@@ -81,6 +81,12 @@ export const SUBSCRIBED_END_EVENTS = Object.freeze([
81
81
  'epic.snapshot.end',
82
82
  'epic.watch.end',
83
83
  'retro.end',
84
+ // Epic #4475 (M4-A) — single-delivery slice boundary. A completed slice is
85
+ // a resume checkpoint for the one long guarded session (the analogue of
86
+ // story.dispatch.end for fan-out). Subscribed now so the pointer updates
87
+ // once the M4-B executor emits slice.end through the bus; inert until then
88
+ // (nothing emits it in M4-A).
89
+ 'slice.end',
84
90
  'story.dispatch.end',
85
91
  ]);
86
92
 
@@ -11,7 +11,7 @@
11
11
  * file instead of shim-scripting library imports (the bench measured
12
12
  * ~12–15 turns of shim-writing for the dup search alone).
13
13
  *
14
- * Two modes (the design's mode matrix):
14
+ * Three modes (the design's mode matrix + the #4496 seed entry):
15
15
  * - `epic` — the Epic exists. Carries `epic`, `clarity` (the Epic
16
16
  * Clarity Gate rubric — free, same body fetch), `replan`
17
17
  * (already-planned signals) and `planState`.
@@ -19,6 +19,14 @@
19
19
  * to the persist half). Carries `onePager` and
20
20
  * `duplicates[]` (cross-Epic dup search). Clarity is not
21
21
  * scored — the ideation path is definitionally clear.
22
+ * - `seed` — headless ideation entry (#4496 fix 1): the one-pager
23
+ * does not exist yet either. The dup search runs off the
24
+ * raw seed text, and the envelope additively carries
25
+ * `seed`, `scopeTriage` (the scope-triage rubric applied
26
+ * CLI-side — no skill Reads on the headless path) and
27
+ * `onePagerSpec` (the canonical one-pager sections, so
28
+ * the authoring pass writes the one-pager in the SAME
29
+ * batched write as the spec artifacts).
22
30
  *
23
31
  * All fields are JSON-serialisable; the module performs no GitHub writes.
24
32
  * The only I/O surfaces are the injected `provider` (reads) and the
@@ -79,6 +87,131 @@ export const TICKET_SCHEMA_DESCRIPTOR = Object.freeze({
79
87
  'validateAndNormalizeTickets (lib/orchestration/ticket-validator.js) at persist time',
80
88
  });
81
89
 
90
+ /**
91
+ * Canonical one-pager authoring descriptor for the `seed` envelope
92
+ * (#4496 fix 1). The section names are the ones `plan-epic.md`'s ideation
93
+ * entry has always named, chosen so the authored headings parse against
94
+ * the `SECTION_RE` map in `lib/epic-plan-ideation.js` (which renders the
95
+ * Epic body from the one-pager at persist time via
96
+ * `.agents/templates/epic-from-idea.md`).
97
+ */
98
+ export const ONE_PAGER_AUTHORING_SPEC = Object.freeze({
99
+ sections: Object.freeze([
100
+ 'Problem Statement',
101
+ 'Recommended Direction',
102
+ 'Key Assumptions',
103
+ 'MVP Scope',
104
+ 'Not Doing',
105
+ ]),
106
+ instruction:
107
+ 'Author the one-pager markdown (the canonical sections above, as `## ` ' +
108
+ 'headings) in the SAME batched write as the other planning artifacts — ' +
109
+ 'no separate ideation pass and no idea-refinement skill activation on ' +
110
+ 'this path. Every unresolved unknown lands in Key Assumptions instead ' +
111
+ 'of a question.',
112
+ consumedBy:
113
+ 'plan-persist.js --one-pager (ideation Epic creation via ' +
114
+ '.agents/templates/epic-from-idea.md)',
115
+ });
116
+
117
+ /**
118
+ * Count top-level enumerated items (`- `, `* `, `1. `) anywhere in a
119
+ * free-form seed text. Unlike {@link countScopeItems} this does not require
120
+ * a scope-shaped heading — a raw `--idea` seed rarely has one.
121
+ *
122
+ * @param {string} text
123
+ * @returns {number}
124
+ */
125
+ function countEnumeratedItems(text) {
126
+ if (typeof text !== 'string' || text.length === 0) return 0;
127
+ return text
128
+ .split(/\r?\n/)
129
+ .filter((line) => /^\s*(?:[-*]|\d+\.)\s+\S/.test(line)).length;
130
+ }
131
+
132
+ /**
133
+ * Delta-shaped change-request verbs — the `core/scope-triage` skill's
134
+ * change-request rubric routes these to `story` by default when the
135
+ * footprint stays inside Story width.
136
+ */
137
+ const DELTA_VERB_RE =
138
+ /\b(fix(?:es)?|tweak(?:s)?|extend(?:s)?|update(?:s)?|adjust(?:s)?|rename(?:s)?|correct(?:s)?|patch(?:es)?|bug|regression|flaky)\b/i;
139
+
140
+ /**
141
+ * Deterministic, CLI-applied scope-triage verdict over a raw `--idea` seed
142
+ * (#4496 fix 6). Embedding the verdict in the `--seed` envelope removes the
143
+ * two skill Reads (`core/scope-triage` + the gate fragment's rubric pass)
144
+ * from the headless path; the attended path keeps the skill-based judgment.
145
+ *
146
+ * The heuristics anchor to the same sizing SSOT the skill anchors to —
147
+ * `DELIVERABLE_GRANULARITY_GUIDANCE` / `DEFAULT_TASK_SIZING` in
148
+ * `ticket-validator-sizing.js` (one Story = one coherent capability slice;
149
+ * multiple independent capabilities = an Epic) — and to the skill's
150
+ * change-request delta rubric. Like the skill, the verdict is **advisory**:
151
+ * being wrong in the `epic` direction is cheap (the consolidation critic and
152
+ * the sizing validator catch an over-planned Story later), and `borderline`
153
+ * is a first-class output, not a forced call.
154
+ *
155
+ * @param {{ seedText?: string }} args
156
+ * @returns {{ verdict: 'epic'|'story'|'borderline', reasons: string[], advisory: true, appliedBy: 'cli' }}
157
+ */
158
+ export function buildScopeTriageSignal({ seedText = '' } = {}) {
159
+ const advisory = /** @type {const} */ (true);
160
+ const appliedBy = /** @type {const} */ ('cli');
161
+ const text = typeof seedText === 'string' ? seedText : '';
162
+ const listItems = countEnumeratedItems(text);
163
+ const wordCount = text.split(/\s+/).filter(Boolean).length;
164
+
165
+ if (listItems >= 3) {
166
+ return {
167
+ verdict: 'epic',
168
+ reasons: [
169
+ `seed enumerates ${listItems} candidate capabilities — a genuine fan-out surface`,
170
+ ],
171
+ advisory,
172
+ appliedBy,
173
+ };
174
+ }
175
+ if (listItems >= 1) {
176
+ return {
177
+ verdict: 'story',
178
+ reasons: [
179
+ `seed enumerates ${listItems} capability item(s) — one coherent change with one reason to exist`,
180
+ ],
181
+ advisory,
182
+ appliedBy,
183
+ };
184
+ }
185
+ if (DELTA_VERB_RE.test(text) && wordCount <= 120) {
186
+ return {
187
+ verdict: 'story',
188
+ reasons: [
189
+ 'delta-shaped seed (change-request verb, no capability enumeration) within Story width',
190
+ ],
191
+ advisory,
192
+ appliedBy,
193
+ };
194
+ }
195
+ if (wordCount >= 250) {
196
+ return {
197
+ verdict: 'epic',
198
+ reasons: [
199
+ `broad prose seed (~${wordCount} words) with no enumeration — plausibly multiple independent capabilities`,
200
+ ],
201
+ advisory,
202
+ appliedBy,
203
+ };
204
+ }
205
+ return {
206
+ verdict: 'borderline',
207
+ reasons: [
208
+ 'no capability enumeration and no clear delta signal — could be one ambitious Story or a small Epic; the operator (or the --yes Recommended branch) decides',
209
+ ],
210
+ advisory,
211
+ appliedBy,
212
+ };
213
+ }
214
+
82
215
  /**
83
216
  * Resolve the planning risk heuristics list from the canonical config
84
217
  * block (same resolution the decompose context uses).
@@ -449,14 +582,56 @@ async function buildOnePagerModeEnvelope({
449
582
  };
450
583
  }
451
584
 
585
+ /**
586
+ * Build the seed-mode (headless ideation) envelope — #4496 fix 1. The
587
+ * one-pager does not exist yet: the dup search and the authoring-context
588
+ * fold both run off the raw seed text (the same builders the one-pager mode
589
+ * uses), and the envelope additively carries `seed`, the CLI-applied
590
+ * `scopeTriage` verdict (fix 6 — no skill Reads on the headless path), and
591
+ * `onePagerSpec` so the one-pager sections are authored in the same batched
592
+ * write as the spec artifacts.
593
+ */
594
+ async function buildSeedModeEnvelope({
595
+ seedText,
596
+ provider,
597
+ config,
598
+ settings,
599
+ fullContext,
600
+ cwd,
601
+ }) {
602
+ if (typeof seedText !== 'string' || seedText.trim().length === 0) {
603
+ throw new Error(
604
+ '[plan-context] --seed requires non-empty seed text — nothing to plan from.',
605
+ );
606
+ }
607
+ const base = await buildOnePagerModeEnvelope({
608
+ onePagerPath: undefined,
609
+ onePagerContent: seedText,
610
+ provider,
611
+ config,
612
+ settings,
613
+ fullContext,
614
+ cwd,
615
+ });
616
+ const { onePager: _onePager, ...rest } = base;
617
+ return {
618
+ ...rest,
619
+ mode: 'seed',
620
+ seed: { text: seedText },
621
+ scopeTriage: buildScopeTriageSignal({ seedText }),
622
+ onePagerSpec: ONE_PAGER_AUTHORING_SPEC,
623
+ };
624
+ }
625
+
452
626
  /**
453
627
  * Build the single planner-context envelope.
454
628
  *
455
629
  * @param {{
456
- * mode: 'epic'|'one-pager',
630
+ * mode: 'epic'|'one-pager'|'seed',
457
631
  * epicId?: number,
458
632
  * onePagerPath?: string,
459
633
  * onePagerContent?: string,
634
+ * seedText?: string,
460
635
  * provider: object,
461
636
  * config: object,
462
637
  * settings: object,
@@ -469,6 +644,7 @@ export async function buildPlanContext({
469
644
  epicId,
470
645
  onePagerPath,
471
646
  onePagerContent,
647
+ seedText,
472
648
  provider,
473
649
  config = {},
474
650
  settings = {},
@@ -504,7 +680,17 @@ export async function buildPlanContext({
504
680
  cwd,
505
681
  });
506
682
  }
683
+ if (mode === 'seed') {
684
+ return buildSeedModeEnvelope({
685
+ seedText,
686
+ provider,
687
+ config,
688
+ settings,
689
+ fullContext,
690
+ cwd,
691
+ });
692
+ }
507
693
  throw new Error(
508
- `[plan-context] unknown mode "${mode}" — expected "epic" or "one-pager".`,
694
+ `[plan-context] unknown mode "${mode}" — expected "epic", "one-pager" or "seed".`,
509
695
  );
510
696
  }
@@ -28,8 +28,9 @@
28
28
  * skip decision this module produces is logged to the plan-metrics ledger
29
29
  * (`appendCriticSkip`) by the callers so under-firing is auditable.
30
30
  *
31
- * Pure, synchronous, no I/O — the `plan-critics.js` CLI owns reading the
32
- * authored artifacts and the resolved config.
31
+ * Pure, synchronous, no I/O — the folded pre-write phase inside
32
+ * `plan-persist.js` owns reading the authored artifacts and the resolved
33
+ * config.
33
34
  */
34
35
 
35
36
  import { evaluateConsolidationPrecondition } from './consolidation-precondition.js';