@apralabs/apra-fleet 0.2.2 → 0.3.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 (87) hide show
  1. package/README.md +29 -8
  2. package/dist/agents/ci-watcher.md +46 -0
  3. package/dist/agents/deployer.md +75 -0
  4. package/dist/agents/doer.md +70 -0
  5. package/dist/agents/harvester.md +79 -0
  6. package/dist/agents/integ-test-runner.md +96 -0
  7. package/dist/agents/plan-reviewer.md +64 -0
  8. package/dist/agents/planner.md +94 -0
  9. package/dist/agents/reviewer.md +82 -0
  10. package/dist/cli/agent-transform.d.ts +11 -0
  11. package/dist/cli/agent-transform.d.ts.map +1 -0
  12. package/dist/cli/agent-transform.js +63 -0
  13. package/dist/cli/agent-transform.js.map +1 -0
  14. package/dist/cli/config.d.ts +1 -0
  15. package/dist/cli/config.d.ts.map +1 -1
  16. package/dist/cli/config.js +15 -0
  17. package/dist/cli/config.js.map +1 -1
  18. package/dist/cli/install.d.ts +5 -0
  19. package/dist/cli/install.d.ts.map +1 -1
  20. package/dist/cli/install.js +200 -23
  21. package/dist/cli/install.js.map +1 -1
  22. package/dist/cli/uninstall.js +1 -1
  23. package/dist/providers/index.d.ts +1 -0
  24. package/dist/providers/index.d.ts.map +1 -1
  25. package/dist/providers/index.js +3 -0
  26. package/dist/providers/index.js.map +1 -1
  27. package/dist/providers/opencode.d.ts +40 -0
  28. package/dist/providers/opencode.d.ts.map +1 -0
  29. package/dist/providers/opencode.js +178 -0
  30. package/dist/providers/opencode.js.map +1 -0
  31. package/dist/services/cloud/task-wrapper.js +1 -1
  32. package/dist/services/cloud/task-wrapper.js.map +1 -1
  33. package/dist/skills/pm/SKILL.md +343 -0
  34. package/dist/skills/pm/beads.md +137 -0
  35. package/dist/skills/pm/cost.md +152 -0
  36. package/dist/skills/pm/doer-reviewer-loop.md +297 -0
  37. package/dist/skills/pm/fleet-addendum.md +115 -0
  38. package/dist/skills/pm/simple-sprint.md +64 -0
  39. package/dist/skills/pm/sprint.md +311 -0
  40. package/dist/skills/pm/tpl-progress.json +35 -0
  41. package/dist/skills/pm/worktrees.md +92 -0
  42. package/dist/tools/cloud-control.d.ts +2 -2
  43. package/dist/tools/credential-store-set.d.ts +2 -2
  44. package/dist/tools/credential-store-update.d.ts +2 -2
  45. package/dist/tools/execute-prompt.d.ts +3 -0
  46. package/dist/tools/execute-prompt.d.ts.map +1 -1
  47. package/dist/tools/execute-prompt.js +17 -3
  48. package/dist/tools/execute-prompt.js.map +1 -1
  49. package/dist/tools/register-member.d.ts +29 -6
  50. package/dist/tools/register-member.d.ts.map +1 -1
  51. package/dist/tools/register-member.js +43 -3
  52. package/dist/tools/register-member.js.map +1 -1
  53. package/dist/tools/update-member.d.ts +29 -6
  54. package/dist/tools/update-member.d.ts.map +1 -1
  55. package/dist/tools/update-member.js +43 -3
  56. package/dist/tools/update-member.js.map +1 -1
  57. package/dist/types.d.ts +6 -1
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/utils/opencode-model-validation.d.ts +15 -0
  60. package/dist/utils/opencode-model-validation.d.ts.map +1 -0
  61. package/dist/utils/opencode-model-validation.js +40 -0
  62. package/dist/utils/opencode-model-validation.js.map +1 -0
  63. package/dist/workflows/auto-sprint.js +1676 -0
  64. package/package.json +2 -2
  65. package/version.json +1 -1
  66. package/skills/pm/SKILL.md +0 -110
  67. package/skills/pm/backlog-item.md +0 -65
  68. package/skills/pm/beads.md +0 -192
  69. package/skills/pm/cleanup.md +0 -15
  70. package/skills/pm/context-file.md +0 -40
  71. package/skills/pm/doer-reviewer.md +0 -123
  72. package/skills/pm/init.md +0 -25
  73. package/skills/pm/multi-pair-sprint.md +0 -64
  74. package/skills/pm/plan-prompt.md +0 -94
  75. package/skills/pm/simple-sprint.md +0 -42
  76. package/skills/pm/single-pair-sprint.md +0 -178
  77. package/skills/pm/tpl-deploy.md +0 -24
  78. package/skills/pm/tpl-design.md +0 -29
  79. package/skills/pm/tpl-doer.md +0 -43
  80. package/skills/pm/tpl-plan.md +0 -72
  81. package/skills/pm/tpl-pm.md +0 -2
  82. package/skills/pm/tpl-progress.json +0 -28
  83. package/skills/pm/tpl-projects.md +0 -4
  84. package/skills/pm/tpl-requirements.md +0 -21
  85. package/skills/pm/tpl-reviewer-plan.md +0 -53
  86. package/skills/pm/tpl-reviewer.md +0 -72
  87. package/skills/pm/tpl-status.md +0 -29
@@ -0,0 +1,1676 @@
1
+ export const meta = {
2
+ name: 'auto-sprint',
3
+ description: `Multi-cycle sprint workflow: plan -> develop -> test -> harvest.
4
+
5
+ args must be a JSON object (not a string) with these fields:
6
+ issues REQUIRED. Array of beads issue IDs (sprint roots), e.g. ["BD-1","BD-2"].
7
+ branch REQUIRED. Sprint branch name, e.g. "feat/auth". Created if it does not exist.
8
+ goal Optional. Exit when no open issues at or above this priority. "P1" | "P1/P2" | "P1/P2/P3". Default: "P1/P2".
9
+ max_cycles Optional. Hard cycle ceiling. Default: 5.
10
+ base_branch Optional. PR target branch. Default: "main".
11
+ requirementsFile Optional. Path to an additional context file for the planner.
12
+
13
+ Minimal invocation example: { "issues": ["BD-7"], "branch": "feat/my-feature" }`,
14
+ phases: [
15
+ { title: 'Plan' },
16
+ { title: 'Develop' },
17
+ { title: 'Test' },
18
+ { title: 'Harvest' },
19
+ ],
20
+ };
21
+
22
+ // Multi-cycle sprint workflow. Drives 8 agents against a beads backlog until a
23
+ // priority-based quality goal is met or the cycle ceiling is reached.
24
+ //
25
+ // Agent roster:
26
+ // planner -- reads open beads sprint goals/features/bugs, creates feature+task DAG
27
+ // plan-reviewer -- validates DAG: coverage, task size, acceptance criteria
28
+ // doer -- works bd-ready tasks (impl and test-dev), VERIFY checkpoint
29
+ // reviewer -- reviews doer output, can reopen tasks
30
+ // deployer -- follows deploy.md + integ-test-playbook.md (setup/reset/teardown)
31
+ // integ-test-runner -- executes tests, closes features, files bugs/enhancements
32
+ // ci-watcher -- polls CI; creates beads task if not configured
33
+ // harvester -- docs, CHANGELOG, token summary, PR
34
+ //
35
+ // Beads owns all work items and is the exit signal.
36
+ // JS workflow owns all routing. No LLM ever decides whether to continue.
37
+ //
38
+ // args (JSON object serialised to string by the Workflow runtime):
39
+ // branch -- sprint branch (required); asserted/created at startup
40
+ // issues -- beads issue IDs to implement (sprint roots), e.g. ["BD-1","BD-2"] (required)
41
+ // goal -- exit criterion: "P1" | "P1/P2" | "P1/P2/P3" (default: "P1/P2")
42
+ // max_cycles -- hard ceiling on sprint cycles (default: 5)
43
+ // requirementsFile -- optional context file for the planner (default: none)
44
+ // base_branch -- PR target (default: "main")
45
+
46
+ // NOTE: the arg-parsing block below is intentionally duplicated from lib/parse-sprint-args.mjs,
47
+ // which exists only for unit testing (workflow scripts cannot import arbitrary files).
48
+ // Keep both in sync when modifying parsing logic.
49
+ //
50
+ // Accepted forms:
51
+ // "BD-1" bare issue ID
52
+ // "BD-1 BD-2" space/comma-separated issue IDs
53
+ // ["BD-1","BD-2"] JSON array of issue IDs
54
+ // {"issues":["BD-1"],"goal":"P1"} JSON object (full control)
55
+ //
56
+ // branch always defaults to the current git branch when omitted.
57
+ let opts = {};
58
+ if (args) {
59
+ let parsed = null;
60
+ try { parsed = JSON.parse(args); } catch {}
61
+
62
+ if (Array.isArray(parsed)) {
63
+ opts = { issues: parsed };
64
+ } else if (parsed && typeof parsed === 'object') {
65
+ opts = parsed;
66
+ } else {
67
+ // bare string: treat as space/comma-separated issue IDs
68
+ const ids = String(args).split(/[\s,]+/).map(s => s.trim()).filter(Boolean);
69
+ opts = { issues: ids };
70
+ }
71
+ }
72
+
73
+ let branch = opts.branch || ''; // empty = auto-detect in setup; reassigned after setup resolves
74
+ const rawIssues = opts.issues || [];
75
+ const rootIds = Array.isArray(rawIssues) ? rawIssues : [rawIssues];
76
+ const goal = opts.goal || 'P1/P2';
77
+ const maxCycles = Number(opts.max_cycles) || 5;
78
+ const requirementsFile = opts.requirementsFile || '';
79
+ const base_branch = opts.base_branch || 'main';
80
+
81
+ if (rootIds.length === 0) {
82
+ log('ERROR: at least one beads issue ID is required (pass as arg: /auto-sprint BD-1)');
83
+ return { error: 'missing issues' };
84
+ }
85
+
86
+ // Goal -> numeric priority threshold.
87
+ // Exit when open issues in sprint-goal subtree at priority <= threshold reaches zero.
88
+ const GOAL_THRESHOLD = { 'P1': 1, 'P1/P2': 2, 'P1/P2/P3': 3 };
89
+ const threshold = GOAL_THRESHOLD[goal] || 2;
90
+
91
+ // PURE_FUNCTIONS_BEGIN -- extracted by test/sprint-cost.test.mjs via vm; keep this block self-contained
92
+
93
+ // Provider-agnostic tier names. These are the only strings that appear in
94
+ // calibration.json and in dispatch calls. Provider-specific model IDs live
95
+ // exclusively in TIER_TO_MODEL below -- the single place to update when models change.
96
+ const TIER_CHEAP = 'cheap';
97
+ const TIER_STANDARD = 'standard';
98
+ const TIER_PREMIUM = 'premium';
99
+
100
+ // Claude model IDs -- change here only, nowhere else in this file.
101
+ const TIER_TO_MODEL = {
102
+ [TIER_CHEAP]: 'claude-haiku-4-5',
103
+ [TIER_STANDARD]: 'claude-sonnet-4-6',
104
+ [TIER_PREMIUM]: 'claude-opus-4-8',
105
+ };
106
+
107
+ // Legacy aliases kept so existing dispatch call-sites (model: MODEL_OPUS etc.) are unchanged.
108
+ const MODEL_OPUS = TIER_PREMIUM;
109
+ const MODEL_SONNET = TIER_STANDARD;
110
+ const MODEL_HAIKU = TIER_CHEAP;
111
+
112
+ // ------------------------------------------------------------------ schemas
113
+
114
+ const REVIEW_SCHEMA = {
115
+ type: 'object', required: ['verdict', 'notes'],
116
+ properties: {
117
+ verdict: { type: 'string', enum: ['APPROVED', 'CHANGES NEEDED'] },
118
+ notes: { type: 'string' },
119
+ },
120
+ };
121
+
122
+ const PLAN_REVIEW_SCHEMA = {
123
+ type: 'object', required: ['verdict', 'notes', 'taskAssignments'],
124
+ properties: {
125
+ verdict: { type: 'string', enum: ['APPROVED', 'CHANGES NEEDED'] },
126
+ notes: { type: 'string' },
127
+ taskAssignments: {
128
+ type: 'array',
129
+ items: {
130
+ type: 'object', required: ['id', 'bucket', 'model'],
131
+ properties: {
132
+ id: { type: 'string' },
133
+ bucket: { type: 'string', enum: ['S', 'M', 'L'] },
134
+ model: { type: 'string' },
135
+ },
136
+ },
137
+ },
138
+ },
139
+ };
140
+
141
+ const SHELL_OUTPUTS_SCHEMA = {
142
+ type: 'object', required: ['outputs'],
143
+ properties: {
144
+ outputs: { type: 'array', items: { type: 'string' } },
145
+ },
146
+ };
147
+
148
+ const DOER_STATUS_SCHEMA = {
149
+ type: 'object', required: ['status'],
150
+ properties: {
151
+ status: { type: 'string', enum: ['VERIFY'] },
152
+ notes: { type: 'string' },
153
+ },
154
+ };
155
+
156
+ const HARVEST_SCHEMA = {
157
+ type: 'object', required: ['status'],
158
+ properties: {
159
+ status: { type: 'string', enum: ['OK', 'FAILED'] },
160
+ notes: { type: 'string' },
161
+ },
162
+ };
163
+
164
+ const SETUP_SCHEMA = {
165
+ type: 'object', required: ['repo', 'branch', 'deployMdExists', 'playbookExists', 'startedAt'],
166
+ properties: {
167
+ repo: { type: 'string' },
168
+ branch: { type: 'string' },
169
+ deployMdExists: { type: 'boolean' },
170
+ playbookExists: { type: 'boolean' },
171
+ startedAt: { type: 'string', description: 'yyyymmdd_hhmmss from date +%Y%m%d_%H%M%S' },
172
+ calibrationRaw: { type: 'string' }, // verbatim stdout of cat calibration.json; JS parses it
173
+ transcriptDir: { type: 'string', description: 'Directory where subagent JSONL conversation logs are written (best-effort; may be empty string if not resolvable)' },
174
+ },
175
+ };
176
+
177
+ const BEADS_BLOCKERS_SCHEMA = {
178
+ type: 'object', required: ['count', 'ids'],
179
+ properties: {
180
+ count: { type: 'number' },
181
+ ids: { type: 'array', items: { type: 'string' } },
182
+ },
183
+ };
184
+
185
+ // One entry per model streak: tasks sharing the same model that can be worked
186
+ // in a single doer dispatch. Ordered by priority (P0 first).
187
+ const READY_STREAKS_SCHEMA = {
188
+ type: 'object', required: ['streaks', 'totalCount'],
189
+ properties: {
190
+ totalCount: { type: 'number' },
191
+ streaks: {
192
+ type: 'array',
193
+ items: {
194
+ type: 'object', required: ['model', 'ids'],
195
+ properties: {
196
+ model: { type: 'string' },
197
+ ids: { type: 'array', items: { type: 'string' } },
198
+ },
199
+ },
200
+ },
201
+ },
202
+ };
203
+
204
+ const CI_SCHEMA = {
205
+ type: 'object', required: ['status'],
206
+ properties: {
207
+ status: { type: 'string', enum: ['green', 'red', 'not_configured', 'pending'] },
208
+ notes: { type: 'string' },
209
+ },
210
+ };
211
+
212
+ const INTEG_RUN_SCHEMA = {
213
+ type: 'object', required: ['featuresClosed', 'issuesCreated', 'summary'],
214
+ properties: {
215
+ featuresClosed: { type: 'number' },
216
+ issuesCreated: { type: 'number' },
217
+ summary: { type: 'string' },
218
+ },
219
+ };
220
+
221
+ // Returned by the resume-check agent at the top of every cycle.
222
+ // planDone -- true if the sprint goal already has children AND every feature has at
223
+ // least one task with non-empty acceptance criteria; skip plan loop.
224
+ // inProgressIds -- tasks currently in_progress; reset to open before the develop
225
+ // loop so a crashed doer never orphans work forever.
226
+
227
+ // ------------------------------------------------------------------ helpers
228
+
229
+ function approved(review) {
230
+ return review && typeof review.verdict === 'string' && review.verdict.trim() === 'APPROVED';
231
+ }
232
+
233
+ // Live pricing for dispatch cost tracking. Initialized from DEFAULT_CALIBRATION;
234
+ // synced to calibration.json values after setup() returns.
235
+ // Prices are output tokens only in USD per 1M. Source: Anthropic pricing 2026-06-04.
236
+ // Keys are tier names (cheap/standard/premium), not model IDs.
237
+ // See also: sprint-logs/calibration.json model_prices_per_1m_output_tokens.
238
+ let OUTPUT_PRICE_PER_M = {
239
+ [TIER_CHEAP]: 5.00,
240
+ [TIER_STANDARD]: 15.00,
241
+ [TIER_PREMIUM]: 25.00,
242
+ };
243
+
244
+ // ------------------------------------------------------------------ CALIBRATION DEFAULTS
245
+ // Single source of truth for all estimation constants. On first sprint run the setup
246
+ // agent writes this to sprint-logs/calibration.json; subsequent runs read that file.
247
+ // To change prices or buckets: update this object -- the file is regenerated next run.
248
+ const DEFAULT_CALIBRATION = {
249
+ _doc: 'Sprint cost calibration. All estimation constants live here -- nothing is hardcoded in agents. Fields named _doc are documentation strings; skip them when reading values. The historical section is written automatically by the harvester after each sprint; do not edit it manually.',
250
+ schema_version: 1,
251
+ model_prices_per_1m_output_tokens: {
252
+ _doc: 'USD per 1M output tokens, keyed by tier name (cheap/standard/premium). Source: Anthropic published pricing 2026-06-04. Update when pricing changes. Provider-specific model IDs are resolved from tier names in auto-sprint.js TIER_TO_MODEL -- they never appear in this file.',
253
+ [TIER_CHEAP]: 5.00,
254
+ [TIER_STANDARD]: 15.00,
255
+ [TIER_PREMIUM]: 25.00,
256
+ },
257
+ role_models: {
258
+ _doc: "Tier name per workflow role. 'doer' and 'reviewer' are NOT here -- the planner sets tier per task in beads metadata; reviewer escalates to max(task_tier, standard). Change an entry here to reroute a role to a different tier.",
259
+ 'setup': TIER_CHEAP,
260
+ 'planner': TIER_PREMIUM,
261
+ 'plan-reviewer': TIER_STANDARD,
262
+ 'deployer': TIER_STANDARD,
263
+ 'integ-test-runner': TIER_STANDARD,
264
+ 'ci-watcher': TIER_CHEAP,
265
+ 'harvester': TIER_STANDARD,
266
+ 'log-flush': TIER_CHEAP,
267
+ 'check-blockers': TIER_CHEAP,
268
+ 'ready-streaks': TIER_CHEAP,
269
+ },
270
+ doer_model_fallback: {
271
+ _doc: 'Tier assumed for doer cost estimation when a task has no tier metadata in beads. In practice the planner always sets tier metadata -- this is a safety net only.',
272
+ model: TIER_STANDARD,
273
+ },
274
+ reviewer_model_rule: {
275
+ _doc: 'Reviewer tier is max(doer_task_tier, minimum). If the doer used premium, reviewer uses premium; otherwise reviewer uses standard. This mirrors the reviewerModel selection in auto-sprint.js.',
276
+ minimum: TIER_STANDARD,
277
+ },
278
+ complexity_buckets: {
279
+ _doc: 'Estimated doer output tokens per task by complexity bucket S/M/L. Plan-reviewer assigns a bucket to each task by reading its description. historical.bucket_avg_tokens overrides these defaults once enough sprint data has been collected.',
280
+ S: { _doc: 'Small: 1 file, narrow scoped change -- rename, config key, simple wiring, pure boilerplate', doer_tokens: 600 },
281
+ M: { _doc: 'Medium: 2-3 files, moderate logic -- new API endpoint, test suite, small focused refactor', doer_tokens: 1400 },
282
+ L: { _doc: 'Large: 3+ files or non-trivial design -- new auth flow, data migration, cross-cutting refactor', doer_tokens: 2800 },
283
+ },
284
+ reviewer_ratio: {
285
+ _doc: 'Reviewer estimated output tokens as a fraction of doer tokens for the same task. 0.4 means reviewer uses ~40% as many output tokens as the doer. Overridden by historical.reviewer_ratio_avg when available.',
286
+ value: 0.4,
287
+ },
288
+ cycle_assumptions: {
289
+ _doc: "Expected number of dev/review cycles. Per-task cost is multiplied by these to produce sprint-level cost scenarios. Update 'expected' if your team consistently lands at a different cycle count.",
290
+ optimistic: 1.0, expected: 1.5, pessimistic: 2.5,
291
+ },
292
+ fixed_overhead_tokens: {
293
+ _doc: "Estimated output tokens for agents that run once per sprint regardless of task count. 'log_flush_per_cycle' is multiplied by the expected cycle count. Keys use underscores; the role lookup strips underscores to match role_models keys.",
294
+ setup: 200,
295
+ planner: 2000,
296
+ plan_reviewer: 1500,
297
+ harvester: 3000,
298
+ ci_watcher: 300,
299
+ log_flush_per_cycle: 100,
300
+ },
301
+ input_cost_multiplier: {
302
+ _doc: 'Multiply output-only USD estimate by this to approximate true cost (input + output). 4.0 is conservative for long-context agents. Replace with an empirical ratio once the workflow harness exposes input token counts.',
303
+ value: 4.0,
304
+ },
305
+ outlier_thresholds: {
306
+ _doc: 'Percentage deviation bands used to classify estimation accuracy in the sprint analysis report.',
307
+ notable_pct: 50,
308
+ outlier_pct: 200,
309
+ calibration_failure_pct: 500,
310
+ },
311
+ historical: {
312
+ _doc: 'Written by harvester after each sprint. Contains actual per-role output token averages from sprint-log JSONL files. Used by auto-sprint.js computeSprintQuote() to improve future estimates. Do not edit manually.',
313
+ max_sprints_in_sample: 5,
314
+ sprints_sampled: 0,
315
+ last_updated: null,
316
+ cycle_avg: null,
317
+ reviewer_ratio_avg: null,
318
+ bucket_avg_tokens: {},
319
+ roles: {},
320
+ },
321
+ };
322
+
323
+ // ------------------------------------------------------------------ COST ARITHMETIC
324
+ // All sprint cost computations are pure JavaScript -- no agent touches a number.
325
+
326
+ // Reviewer tier mirrors auto-sprint dispatch logic: max(taskTier, standard).
327
+ function reviewerModelFor(taskModel) {
328
+ return taskModel === TIER_PREMIUM ? TIER_PREMIUM : TIER_STANDARD;
329
+ }
330
+
331
+ function computeSprintQuote(taskAssignments, calibration) {
332
+ const prices = calibration.model_prices_per_1m_output_tokens;
333
+ const hist = calibration.historical || {};
334
+ const buckets = calibration.complexity_buckets;
335
+ const revRatio = (hist.sprints_sampled >= 1 && hist.reviewer_ratio_avg != null)
336
+ ? hist.reviewer_ratio_avg : calibration.reviewer_ratio.value;
337
+ const cycles = calibration.cycle_assumptions;
338
+ const overhead = calibration.fixed_overhead_tokens;
339
+ const inputMult = calibration.input_cost_multiplier.value;
340
+ const fallback = (calibration.doer_model_fallback || {}).model || MODEL_SONNET;
341
+ const calibSrc = hist.sprints_sampled >= 1
342
+ ? `historical (${hist.sprints_sampled} sprint${hist.sprints_sampled !== 1 ? 's' : ''})`
343
+ : 'defaults';
344
+
345
+ const tasks = (taskAssignments || []).map(t => {
346
+ const model = t.model || fallback;
347
+ const histToks = (hist.bucket_avg_tokens || {})[t.bucket];
348
+ const doerTokens = (hist.sprints_sampled >= 1 && histToks != null)
349
+ ? Math.round(histToks) : (buckets[t.bucket] || buckets.M).doer_tokens;
350
+ const reviewerTokens = Math.round(doerTokens * revRatio);
351
+ const doerPrice = prices[model] || prices[MODEL_SONNET];
352
+ const revPrice = prices[reviewerModelFor(model)] || prices[MODEL_SONNET];
353
+ const outputUsd = (doerTokens * doerPrice + reviewerTokens * revPrice) / 1_000_000;
354
+ return { id: t.id, bucket: t.bucket, model, doerTokens, reviewerTokens, outputUsd };
355
+ });
356
+
357
+ const perTaskSubtotal = tasks.reduce((s, t) => s + t.outputUsd, 0);
358
+
359
+ const rm = calibration.role_models || {};
360
+ let overheadUsd = 0;
361
+ for (const [key, tokens] of Object.entries(overhead)) {
362
+ if (typeof tokens !== 'number') continue;
363
+ if (key === 'log_flush_per_cycle') continue;
364
+ const role = key.replace(/_/g, '-');
365
+ const model = rm[role] || MODEL_SONNET;
366
+ overheadUsd += tokens * (prices[model] || prices[MODEL_SONNET]) / 1_000_000;
367
+ }
368
+ const logFlushUsd = (overhead.log_flush_per_cycle || 0)
369
+ * (prices[rm['log-flush'] || MODEL_HAIKU] || prices[MODEL_HAIKU]) / 1_000_000;
370
+
371
+ const scenario = mult => {
372
+ const out = perTaskSubtotal * mult + overheadUsd + logFlushUsd * mult;
373
+ return { outputOnly: out, total: out * inputMult };
374
+ };
375
+
376
+ return {
377
+ tasks,
378
+ calibrationSource: calibSrc,
379
+ inputMultiplier: inputMult,
380
+ scenarios: {
381
+ optimistic: scenario(cycles.optimistic),
382
+ expected: scenario(cycles.expected),
383
+ pessimistic: scenario(cycles.pessimistic),
384
+ },
385
+ };
386
+ }
387
+
388
+ function computeSprintAnalysis(quote, logEntries, calibration, actualCycles) {
389
+ const prices = calibration.model_prices_per_1m_output_tokens;
390
+ const inputMult = calibration.input_cost_multiplier.value;
391
+ const thr = calibration.outlier_thresholds;
392
+ const cycles = calibration.cycle_assumptions;
393
+ const rm = calibration.role_models || {};
394
+ const overhead = calibration.fixed_overhead_tokens;
395
+
396
+ const roleOf = label => label.replace(/-c\d.*$/, '');
397
+
398
+ const byRole = {};
399
+ for (const e of (logEntries || [])) {
400
+ const role = roleOf(e.label || '');
401
+ if (!role) continue;
402
+ if (!byRole[role]) byRole[role] = { tokens: 0, costUsd: 0, dispatches: 0 };
403
+ byRole[role].tokens += e.outTokens || 0;
404
+ byRole[role].costUsd += e.costUsd || 0;
405
+ byRole[role].dispatches++;
406
+ }
407
+
408
+ const estCycles = cycles.expected;
409
+ const tasks = quote ? quote.tasks || [] : [];
410
+
411
+ const estDoerTokens = tasks.reduce((s, t) => s + t.doerTokens, 0) * estCycles;
412
+ const estReviewerTokens = tasks.reduce((s, t) => s + t.reviewerTokens, 0) * estCycles;
413
+ const estDoerUsd = tasks.reduce((s, t) =>
414
+ s + t.doerTokens * (prices[t.model] || prices[MODEL_SONNET]) / 1_000_000, 0) * estCycles;
415
+ const estReviewerUsd = tasks.reduce((s, t) =>
416
+ s + t.reviewerTokens * (prices[reviewerModelFor(t.model)] || prices[MODEL_SONNET]) / 1_000_000, 0) * estCycles;
417
+
418
+ let estOverheadTokens = 0, estOverheadUsd = 0;
419
+ for (const [key, tokens] of Object.entries(overhead)) {
420
+ if (typeof tokens !== 'number') continue;
421
+ const mult = key === 'log_flush_per_cycle' ? estCycles : 1;
422
+ const role = key.replace(/_/g, '-');
423
+ const model = key === 'log_flush_per_cycle' ? (rm['log-flush'] || MODEL_HAIKU) : (rm[role] || MODEL_SONNET);
424
+ estOverheadTokens += tokens * mult;
425
+ estOverheadUsd += tokens * mult * (prices[model] || prices[MODEL_SONNET]) / 1_000_000;
426
+ }
427
+
428
+ const actDoerTokens = byRole['doer']?.tokens || 0;
429
+ const actDoerUsd = byRole['doer']?.costUsd || 0;
430
+ const actReviewerTokens = byRole['reviewer']?.tokens || 0;
431
+ const actReviewerUsd = byRole['reviewer']?.costUsd || 0;
432
+ let actOverheadTokens = 0, actOverheadUsd = 0;
433
+ for (const [role, data] of Object.entries(byRole)) {
434
+ if (role !== 'doer' && role !== 'reviewer') {
435
+ actOverheadTokens += data.tokens;
436
+ actOverheadUsd += data.costUsd;
437
+ }
438
+ }
439
+
440
+ const totEstTokens = Math.round(estDoerTokens + estReviewerTokens + estOverheadTokens);
441
+ const totActTokens = actDoerTokens + actReviewerTokens + actOverheadTokens;
442
+ const totEstUsd = estDoerUsd + estReviewerUsd + estOverheadUsd;
443
+ const totActUsd = actDoerUsd + actReviewerUsd + actOverheadUsd;
444
+
445
+ const pct = (est, act) => est > 0 ? `${act > est ? '+' : ''}${Math.round((act - est) / est * 100)}%` : 'n/a';
446
+ const fmtN = n => Math.round(n).toLocaleString('en-US');
447
+ const fmtU = n => `$${n.toFixed(3)}`;
448
+
449
+ const rows = [
450
+ ['doer', Math.round(estDoerTokens), actDoerTokens, estDoerUsd, actDoerUsd ],
451
+ ['reviewer', Math.round(estReviewerTokens), actReviewerTokens, estReviewerUsd, actReviewerUsd ],
452
+ ['overhead', Math.round(estOverheadTokens), actOverheadTokens, estOverheadUsd, actOverheadUsd ],
453
+ ['TOTAL', totEstTokens, totActTokens, totEstUsd, totActUsd ],
454
+ ];
455
+
456
+ const header =
457
+ `| Role | Est tokens | Act tokens | D% | Est USD | Act USD |\n` +
458
+ `|------------|------------|------------|-------|----------|----------|\n`;
459
+ const body = rows.map(([role, et, at, eu, au]) =>
460
+ `| ${role.padEnd(10)} | ${fmtN(et).padStart(10)} | ${fmtN(at).padStart(10)} | ${pct(et, at).padStart(5)} | ${fmtU(eu).padStart(8)} | ${fmtU(au).padStart(8)} |`
461
+ ).join('\n');
462
+
463
+ const outliers = rows.slice(0, 3).filter(([, et, at]) => et > 0 && Math.abs((at - et) / et * 100) > thr.outlier_pct).map(r => r[0]);
464
+ const failures = rows.slice(0, 3).filter(([, et, at]) => et > 0 && Math.abs((at - et) / et * 100) > thr.calibration_failure_pct).map(r => r[0]);
465
+
466
+ const src = quote ? quote.calibrationSource : 'none';
467
+ const analysisText =
468
+ `#### Sprint cost analysis\n` +
469
+ `Calibration: ${src} Cycles: estimated ${estCycles}, actual ${actualCycles}\n\n` +
470
+ header + body + `\n` +
471
+ `True-cost estimate (output x ${inputMult}x): ${fmtU(totEstUsd * inputMult)}\n\n` +
472
+ `Outliers (>${thr.outlier_pct}% variance): ${outliers.length ? outliers.join(', ') : 'none'}\n` +
473
+ `Calibration failures (>${thr.calibration_failure_pct}%): ${failures.length ? failures.join(', ') : 'none'}\n`;
474
+
475
+ return { analysisText, byRole, actualCycles, totEstOutputUsd: totEstUsd, totEstTrueUsd: totEstUsd * inputMult, totActUsd };
476
+ }
477
+
478
+ // accumulateBucketTokens: join doer log entries back to their S/M/L buckets.
479
+ // Each doer dispatch entry carries label 'doer-c<N>-i<M>' and context
480
+ // 'tasks A, B, C'. We map every listed task ID to its bucket (via the
481
+ // id->bucket map built from taskAssignments) and attribute the entry's
482
+ // outTokens to those buckets, split evenly across the listed IDs that resolve
483
+ // to a known bucket. Returns { S?:{tokens,n}, M?:..., L?:... } -- only buckets
484
+ // that were actually exercised appear (absent buckets stay absent so
485
+ // computeSprintQuote keeps using its calibration defaults).
486
+ function accumulateBucketTokens(logEntries, taskAssignments) {
487
+ const bucketOf = {};
488
+ for (const t of (taskAssignments || [])) {
489
+ if (t && t.id != null && t.bucket != null) bucketOf[String(t.id)] = t.bucket;
490
+ }
491
+ const acc = {};
492
+ for (const e of (logEntries || [])) {
493
+ const label = e.label || '';
494
+ if (label.replace(/-c\d.*$/, '') !== 'doer') continue; // doer entries only
495
+ const tokens = e.outTokens || 0;
496
+ if (tokens <= 0) continue;
497
+ const ctx = String(e.context || '');
498
+ const m = ctx.match(/tasks\s+(.+)$/i);
499
+ if (!m) continue;
500
+ const ids = m[1].split(',').map(s => s.trim()).filter(Boolean);
501
+ // Resolve each listed ID to a bucket; skip IDs we can't map.
502
+ const buckets = ids.map(id => bucketOf[id]).filter(b => b != null);
503
+ if (buckets.length === 0) continue;
504
+ const share = tokens / buckets.length; // even split
505
+ for (const b of buckets) {
506
+ if (!acc[b]) acc[b] = { tokens: 0, n: 0 };
507
+ acc[b].tokens += share;
508
+ acc[b].n += 1;
509
+ }
510
+ }
511
+ return acc;
512
+ }
513
+
514
+ function computeUpdatedCalibration(calibration, analysis, startedAt, taskAssignments, logEntries) {
515
+ const hist = JSON.parse(JSON.stringify(calibration.historical || {}));
516
+ const max = hist.max_sprints_in_sample || 5;
517
+ const prev = Math.min(hist.sprints_sampled || 0, max - 1);
518
+ const n = prev + 1;
519
+ const blend = (old, val) => old == null ? val : (old * prev + val) / n;
520
+
521
+ hist.sprints_sampled = n;
522
+ hist.last_updated = startedAt.replace(/^(\d{4})(\d{2})(\d{2}).*/, '$1-$2-$3');
523
+ hist.cycle_avg = blend(hist.cycle_avg, analysis.actualCycles);
524
+ hist.roles = hist.roles || {};
525
+
526
+ for (const [role, data] of Object.entries(analysis.byRole)) {
527
+ if (data.tokens === 0) continue;
528
+ const avg = data.tokens / data.dispatches;
529
+ const prev_r = hist.roles[role] || { avg_output_tokens: null, sample_n: 0 };
530
+ hist.roles[role] = {
531
+ avg_output_tokens: blend(prev_r.avg_output_tokens, avg),
532
+ sample_n: prev_r.sample_n + data.dispatches,
533
+ };
534
+ }
535
+
536
+ const doerTok = analysis.byRole['doer']?.tokens || 0;
537
+ const revTok = analysis.byRole['reviewer']?.tokens || 0;
538
+ if (doerTok > 0) hist.reviewer_ratio_avg = blend(hist.reviewer_ratio_avg, revTok / doerTok);
539
+
540
+ // bucket_avg_tokens join: attribute each doer log entry's outTokens to the
541
+ // S/M/L bucket(s) of the task IDs in its context string, then blend the
542
+ // per-bucket average into hist.bucket_avg_tokens using the same sprints_sampled
543
+ // accounting as roles above. Buckets with no data this sprint keep their prior
544
+ // value untouched (and unexercised buckets stay absent), so computeSprintQuote
545
+ // defaults still apply where we have no history.
546
+ hist.bucket_avg_tokens = hist.bucket_avg_tokens || {};
547
+ const bucketAcc = accumulateBucketTokens(logEntries, taskAssignments);
548
+ for (const [bucket, data] of Object.entries(bucketAcc)) {
549
+ if (data.n === 0) continue;
550
+ const avg = data.tokens / data.n;
551
+ hist.bucket_avg_tokens[bucket] = blend(hist.bucket_avg_tokens[bucket], avg);
552
+ }
553
+
554
+ return { ...calibration, historical: hist };
555
+ }
556
+
557
+ // ---- shell-dispatch parsers (pure) -------------------------------------------
558
+ // These parse the outputs[] array returned by the bounded Haiku shell dispatches
559
+ // (countBeadsBlockers / getReadyStreaks / checkCycleState). Factoring the parse
560
+ // logic out keeps it unit-testable and guarantees a single, side-effect-free
561
+ // parse path -- the dispatch wrappers never loop or branch on parse failure, they
562
+ // just feed outputs here and accept whatever this returns.
563
+ //
564
+ // `outputs` is the agent-returned array of strings (one per command). `rootCount`
565
+ // is the number of leading `bd graph` ID-list commands; the final element is the
566
+ // JSON list command. All functions degrade safely on missing/garbage input.
567
+
568
+ // collectSubtreeIds: union the IDs from the leading rootCount whitespace-joined
569
+ // ID-list outputs (one per sprint goal) into a Set.
570
+ function collectSubtreeIds(outputs, rootCount) {
571
+ const ids = new Set();
572
+ for (let i = 0; i < rootCount; i++) {
573
+ String(outputs[i] || '').trim().split(/\s+/).filter(Boolean).forEach(id => ids.add(id));
574
+ }
575
+ return ids;
576
+ }
577
+
578
+ // parseBlockers: contract {count, ids} of open issues with priority<=thr inside
579
+ // the sprint-goal subtree. Missing/short outputs => sentinel {count: 999, ids: []} so the
580
+ // caller treats blockers as present (fail-safe, never exits the sprint early).
581
+ function parseBlockers(outputs, rootCount, thr) {
582
+ if (!Array.isArray(outputs) || outputs.length < rootCount + 1) return { count: 999, ids: [] };
583
+ const subtree = collectSubtreeIds(outputs, rootCount);
584
+ let ids = [];
585
+ try {
586
+ const open = JSON.parse(outputs[rootCount]);
587
+ ids = Array.isArray(open)
588
+ ? open.filter(x => subtree.has(x.id) && x.p <= thr).map(x => x.id)
589
+ : [];
590
+ } catch { ids = []; }
591
+ return { count: ids.length, ids };
592
+ }
593
+
594
+ // parseReadyStreaks: contract {totalCount, streaks[]} grouping ready tasks in the
595
+ // subtree by model, ordered by min priority.
596
+ function parseReadyStreaks(outputs, rootCount, defaultModel) {
597
+ if (!Array.isArray(outputs) || outputs.length < rootCount + 1) return { totalCount: 0, streaks: [] };
598
+ const subtree = collectSubtreeIds(outputs, rootCount);
599
+ let readyTasks = [];
600
+ try {
601
+ const all = JSON.parse(outputs[rootCount]);
602
+ readyTasks = Array.isArray(all) ? all.filter(t => subtree.has(t.id)) : [];
603
+ } catch { readyTasks = []; }
604
+
605
+ // Hoist the known-tiers set and reverse map outside the loop (constant across tasks).
606
+ const KNOWN_TIERS = new Set([TIER_CHEAP, TIER_STANDARD, TIER_PREMIUM]);
607
+ const MODEL_TO_TIER = Object.fromEntries(Object.entries(TIER_TO_MODEL).map(([t, id]) => [id, t]));
608
+
609
+ const byModel = {};
610
+ for (const t of readyTasks) {
611
+ const rawModel = t.m || defaultModel;
612
+ // Normalise: if the stored value is a provider-specific model ID rather than a tier
613
+ // name, resolve it back to a tier so dispatch() works correctly. This handles tasks
614
+ // created before the cheap/standard/premium tier rename. Uses console.warn (not log)
615
+ // so it is safe when this block is extracted into a vm/require context for testing.
616
+ let model = rawModel;
617
+ if (!KNOWN_TIERS.has(rawModel)) {
618
+ const tier = MODEL_TO_TIER[rawModel];
619
+ if (tier) {
620
+ model = tier;
621
+ typeof console !== 'undefined' && console.warn(`[apra-pm] Task ${t.id}: pre-migration model '${rawModel}' normalised to tier '${model}'`);
622
+ } else {
623
+ model = defaultModel;
624
+ typeof console !== 'undefined' && console.warn(`[apra-pm] Task ${t.id}: unrecognised model '${rawModel}', defaulting to '${defaultModel}'`);
625
+ }
626
+ }
627
+ if (!byModel[model]) byModel[model] = [];
628
+ byModel[model].push({ id: t.id, priority: t.p });
629
+ }
630
+ const streaks = Object.entries(byModel).map(([model, tasks]) => ({
631
+ model,
632
+ ids: tasks.slice().sort((a, b) => a.priority - b.priority).map(x => x.id),
633
+ _min: Math.min(...tasks.map(x => x.priority)),
634
+ })).sort((a, b) => a._min - b._min).map(({ model, ids }) => ({ model, ids }));
635
+
636
+ return { totalCount: readyTasks.length, streaks };
637
+ }
638
+
639
+ // parseCycleState: contract {planDone, inProgressIds}. planDone is true for a
640
+ // sprint goal when it has >=1 feature and either all features closed or every task has a
641
+ // description. Missing/short outputs => {planDone: false, ...} (fail-safe: never
642
+ // declares planning complete on bad input).
643
+ function parseCycleState(outputs, rootCount) {
644
+ if (!Array.isArray(outputs) || outputs.length < rootCount + 1) return { planDone: false, inProgressIds: [] };
645
+ const inProgressIds = String(outputs[rootCount] || '').trim().split(/\s+/).filter(Boolean);
646
+ const planDone = Array.from({ length: rootCount }).every((_, i) => {
647
+ try {
648
+ const issues = JSON.parse(outputs[i]);
649
+ if (!Array.isArray(issues)) return false;
650
+ const features = issues.filter(x => x.t === 'feature');
651
+ if (features.length === 0) return false;
652
+ const openFts = features.filter(x => x.s !== 'closed');
653
+ if (openFts.length === 0) return true;
654
+ const tasks = issues.filter(x => x.t === 'task');
655
+ if (tasks.length === 0) return false;
656
+ return tasks.every(x => x.d);
657
+ } catch { return false; }
658
+ });
659
+ return { planDone, inProgressIds };
660
+ }
661
+
662
+ // buildSprintSummary assembles a structured human-readable end-of-sprint summary
663
+ // from already-computed inputs. Pure function -- no I/O.
664
+ //
665
+ // Parameters:
666
+ // analysis -- result of computeSprintAnalysis (analysisText, byRole, actualCycles, totActUsd...)
667
+ // sprintQuote -- result of computeSprintQuote or null
668
+ // calibration -- current calibration object
669
+ // opts -- { branch, goal, goalMet, cycleCount, tasksCompleted, tasksOpen, startedAt }
670
+ //
671
+ // Returns: { summaryText } -- markdown string suitable for writing to .analysis.md
672
+ function buildSprintSummary(analysis, sprintQuote, calibration, opts) {
673
+ const { branch = '', goal = '', goalMet = false, cycleCount = 0,
674
+ tasksCompleted = 0, tasksOpen = 0, startedAt = '' } = opts || {};
675
+ const thr = (calibration && calibration.outlier_thresholds) || { outlier_pct: 200, calibration_failure_pct: 500 };
676
+ const cycles = (calibration && calibration.cycle_assumptions) || {};
677
+ const estCycles = cycles.expected || 1;
678
+
679
+ // ---- goal / cycle section
680
+ const goalLine = `**Goal:** ${goal || '(unset)'} -> ${goalMet ? 'MET' : 'NOT MET'}`;
681
+ const cyclesLine = `**Cycles:** estimated ${estCycles}, actual ${cycleCount}`;
682
+ const tasksLine = `**Tasks:** ${tasksCompleted} completed, ${tasksOpen} open/carried-forward`;
683
+
684
+ // ---- cost table (re-use the analysisText already computed)
685
+ const costSection = analysis ? analysis.analysisText : '(no cost analysis available)';
686
+
687
+ // ---- outlier role suggestions
688
+ // sprintQuote.tasks have shape {id,bucket,model,doerTokens,reviewerTokens,outputUsd} -- no `role` field.
689
+ // Estimates per role:
690
+ // doer -> sum of t.doerTokens across all tasks, scaled by estCycles
691
+ // reviewer -> sum of t.reviewerTokens across all tasks, scaled by estCycles
692
+ // overhead -> calibration.fixed_overhead_tokens[role_key] (log-flush scaled by estCycles)
693
+ const overhead = (calibration && calibration.fixed_overhead_tokens) || {};
694
+ const suggestions = [];
695
+ if (analysis && analysis.byRole) {
696
+ for (const [role, data] of Object.entries(analysis.byRole)) {
697
+ if (!data.tokens) continue;
698
+ let estTokensForRole = 0;
699
+ if (role === 'doer') {
700
+ if (!sprintQuote) continue;
701
+ estTokensForRole = (sprintQuote.tasks || [])
702
+ .reduce((s, t) => s + (t.doerTokens || 0), 0) * estCycles;
703
+ } else if (role === 'reviewer') {
704
+ if (!sprintQuote) continue;
705
+ estTokensForRole = (sprintQuote.tasks || [])
706
+ .reduce((s, t) => s + (t.reviewerTokens || 0), 0) * estCycles;
707
+ } else {
708
+ // overhead role: look up in fixed_overhead_tokens (keys use underscores)
709
+ const key = role.replace(/-/g, '_');
710
+ const tok = overhead[key];
711
+ if (typeof tok !== 'number') continue;
712
+ // log-flush runs once per cycle; other overhead roles run once per sprint
713
+ estTokensForRole = role === 'log-flush' ? tok * estCycles : tok;
714
+ }
715
+ if (estTokensForRole <= 0) continue;
716
+ const pctOver = (data.tokens - estTokensForRole) / estTokensForRole * 100;
717
+ if (Math.abs(pctOver) > thr.outlier_pct) {
718
+ const dir = pctOver > 0 ? 'over' : 'under';
719
+ suggestions.push(
720
+ `- \`${role}\` actual ${Math.round(Math.abs(pctOver))}% ${dir} estimate -> ` +
721
+ `consider ${pctOver > 0 ? 'bumping' : 'reducing'} \`fixed_overhead_tokens.${role.replace(/-/g, '_')}\` or bucket sizes`
722
+ );
723
+ }
724
+ }
725
+ }
726
+ const suggestSection = suggestions.length
727
+ ? `### Suggested calibration adjustments\n\n${suggestions.join('\n')}\n`
728
+ : `### Suggested calibration adjustments\n\n_No outliers detected -- calibration looks good._\n`;
729
+
730
+ const summaryText =
731
+ `# Sprint summary: ${branch}\n\n` +
732
+ `**Started:** ${startedAt || '(unknown)'} \n` +
733
+ `${goalLine} \n` +
734
+ `${cyclesLine} \n` +
735
+ `${tasksLine}\n\n` +
736
+ `---\n\n` +
737
+ `### Cost analysis\n\n` +
738
+ costSection + `\n` +
739
+ `---\n\n` +
740
+ suggestSection;
741
+
742
+ return { summaryText };
743
+ }
744
+
745
+ // PURE_FUNCTIONS_END
746
+
747
+ function outputCostUsd(tier, tokens) {
748
+ const rate = OUTPUT_PRICE_PER_M[tier] || OUTPUT_PRICE_PER_M[TIER_STANDARD];
749
+ return (tokens / 1_000_000) * rate;
750
+ }
751
+
752
+ // Resolve a tier name to the provider-specific model ID for agent() dispatch.
753
+ // Falls back to standard tier if the tier is unrecognised.
754
+ function resolveModel(tier) {
755
+ return TIER_TO_MODEL[tier] || TIER_TO_MODEL[TIER_STANDARD];
756
+ }
757
+
758
+ // Real output-token cost via differential budget.spent() snapshots.
759
+ // budget.spent() is the only actual usage the harness exposes (output tokens only).
760
+ // opts.model is a tier name (cheap/standard/premium); resolved to a model ID for agent().
761
+ // opts.context -- short human string describing what was worked (e.g. "tasks BD-5,BD-6")
762
+ let cycleCostUsd = 0;
763
+ const dispatchLedger = []; // accumulates across all cycles; flushed to sprint-logs/<branch>.jsonl per cycle
764
+
765
+ async function dispatch(prompt, opts) {
766
+ const tier = opts.model || TIER_STANDARD;
767
+ const modelId = resolveModel(tier);
768
+ const before = budget.spent();
769
+ const result = await agent(prompt, { ...opts, model: modelId });
770
+ const outTokens = budget.spent() - before;
771
+ const cost = outputCostUsd(tier, outTokens);
772
+ cycleCostUsd += cost;
773
+ const entry = {
774
+ cycle: cycleCount === 0 ? 'setup' : cycleCount,
775
+ phase: opts.phase || '?',
776
+ label: opts.label || '?',
777
+ model: tier,
778
+ context: opts.context || '',
779
+ outTokens,
780
+ costUsd: parseFloat(cost.toFixed(4)),
781
+ };
782
+ dispatchLedger.push(entry);
783
+ if (outTokens > 0) log(`$${cost.toFixed(4)} ${opts.label || '?'} -- ${opts.context || opts.phase || '?'}`);
784
+ return result;
785
+ }
786
+
787
+
788
+ // ------------------------------------------------------------ shell dispatch
789
+ //
790
+ // All three exit-check helpers below run a tiny, fixed set of read-only commands
791
+ // (`bd graph --json <goal-id> | node-extract` plus one `bd list ... | node-extract`)
792
+ // via a single Haiku dispatch and parse the result with a pure parser above.
793
+ //
794
+ // Latency-hardening (gh-7: check-blockers once took 12.5 min):
795
+ // * Root cause -- the dispatch prompt said "return each command's stdout
796
+ // verbatim" against a strict array-of-strings schema, with NO turn cap. A
797
+ // stray escaping/parse concern on the (potentially large) `bd graph` output
798
+ // made the agent re-run commands and re-emit output across many turns, so a
799
+ // 5-second job could burn minutes. The node extractors already shrink output
800
+ // to an ID list / tiny JSON, so the only real failure mode was looping.
801
+ // * Fix -- (a) every shell dispatch is a SINGLE-ATTEMPT contract: maxTurns is
802
+ // bounded to (#commands + 1), so the agent physically cannot loop for
803
+ // minutes; (b) the prompt is explicit that it must run each command exactly
804
+ // once and never retry/re-run; (c) parsing is fully tolerant (pure parsers
805
+ // return a fail-safe sentinel on bad/short output) so there is never a reason
806
+ // to bounce work back to the agent.
807
+ const SHELL_DISPATCH_PROMPT_HEADER =
808
+ `Run each command below EXACTLY ONCE, in order. Return each command's stdout ` +
809
+ `as one string element of outputs[] (same order; outputs.length must equal the ` +
810
+ `number of commands).\n` +
811
+ `Rules: do NOT summarize, reformat, interpret, or escape the output. Do NOT ` +
812
+ `re-run any command. Do NOT retry on empty or unexpected output -- an empty ` +
813
+ `string is a valid result; just return it. This is a single attempt: run, ` +
814
+ `capture, return, stop.\n\n`;
815
+
816
+ function buildShellPrompt(cmds) {
817
+ return SHELL_DISPATCH_PROMPT_HEADER + cmds.map((c, i) => `${i + 1}. ${c}`).join('\n');
818
+ }
819
+
820
+ // Bound the agent to one turn per command plus a single wrap-up turn. The harness
821
+ // stops the dispatch at maxTurns, so a misbehaving agent cannot stall for minutes.
822
+ function shellMaxTurns(cmds) {
823
+ return cmds.length + 1;
824
+ }
825
+
826
+ async function dispatchShell(cmds, opts) {
827
+ return dispatch(buildShellPrompt(cmds), {
828
+ schema: SHELL_OUTPUTS_SCHEMA,
829
+ maxTurns: shellMaxTurns(cmds),
830
+ ...opts,
831
+ });
832
+ }
833
+
834
+ async function countBeadsBlockers(thr, roots) {
835
+ // Extract only IDs from bd graph to keep output small (avoids $(cat ...) file-reference issue).
836
+ const idExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{console.log(JSON.parse(d).issues.map(i=>i.id).join(' '))}catch{}"`;
837
+ const openExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{console.log(JSON.stringify(JSON.parse(d).map(i=>({id:i.id,p:i.priority}))))}catch{console.log('[]')}"`;
838
+ const cmds = [
839
+ ...roots.map(id => `bd graph --json ${id} | ${idExtract}`),
840
+ `bd list --status=open --json | ${openExtract}`,
841
+ ];
842
+ const r = await dispatchShell(cmds, { model: MODEL_HAIKU, label: 'check-blockers', phase: 'Develop' });
843
+ return parseBlockers(r?.outputs, roots.length, thr);
844
+ }
845
+
846
+ async function getReadyStreaks(rootIds) {
847
+ // Extract only IDs from bd graph to keep output small (avoids $(cat ...) file-reference issue).
848
+ const idExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{console.log(JSON.parse(d).issues.map(i=>i.id).join(' '))}catch{}"`;
849
+ const taskExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{console.log(JSON.stringify(JSON.parse(d).map(i=>({id:i.id,p:i.priority,m:(i.metadata||{}).model}))))}catch{console.log('[]')}"`;
850
+ const cmds = [
851
+ ...rootIds.map(id => `bd graph --json ${id} | ${idExtract}`),
852
+ `bd list --ready --type=task --json | ${taskExtract}`,
853
+ ];
854
+ const r = await dispatchShell(cmds, { model: MODEL_HAIKU, label: 'ready-streaks', phase: 'Develop' });
855
+ return parseReadyStreaks(r?.outputs, rootIds.length, TIER_STANDARD);
856
+ }
857
+
858
+ async function commitFeedback(repo, branch, notes, role, label, phase) {
859
+ await dispatch(
860
+ `Repo: ${repo}\nBranch: ${branch}\n\n` +
861
+ `Write the following reviewer feedback to feedback.md (overwrite if it exists):\n\n` +
862
+ `${notes}\n\n` +
863
+ `Then commit and push:\n` +
864
+ ` git -C "${repo}" add feedback.md\n` +
865
+ ` git -C "${repo}" -c user.name='${role}' -c user.email='${role}@pm.local' commit -m "feedback: ${label}"\n` +
866
+ ` git -C "${repo}" push origin ${branch}`,
867
+ { model: MODEL_HAIKU, label: `feedback-commit-${label}`, phase }
868
+ );
869
+ }
870
+
871
+ async function checkCycleState(rootIds) {
872
+ // Extract only the fields needed for planDone check to keep output small.
873
+ const graphExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{const issues=(JSON.parse(d).issues||[]);console.log(JSON.stringify(issues.map(i=>({id:i.id,t:i.issue_type,s:i.status,d:!!(i.description||'').trim()}))))}catch{console.log('[]')}"`;
874
+ const ipExtract = `node -e "const d=require('fs').readFileSync(0,'utf8');try{console.log(JSON.parse(d).map(i=>i.id).join(' '))}catch{}"`;
875
+ const cmds = [
876
+ ...rootIds.map(id => `bd graph --json ${id} | ${graphExtract}`),
877
+ `bd list --status=in_progress --type=task --json | ${ipExtract}`,
878
+ ];
879
+ const r = await dispatchShell(cmds, { model: MODEL_HAIKU, label: 'cycle-state', phase: 'Plan' });
880
+ return parseCycleState(r?.outputs, rootIds.length);
881
+ }
882
+
883
+ // ------------------------------------------------------------------ STATE
884
+
885
+ let cycleCount = 0;
886
+ let goalMet = false;
887
+ let prevOpenIds = [];
888
+ let headSha = '';
889
+ let abortReason = '';
890
+
891
+ // ------------------------------------------------------------------ SETUP
892
+
893
+ phase('Plan');
894
+
895
+ const setup = await dispatch(
896
+ `Sprint workspace setup.\n\n` +
897
+ `Step 1: Get repo root.\n` +
898
+ ` Run: git rev-parse --show-toplevel\n\n` +
899
+ (branch
900
+ ? `Step 2: Assert sprint branch "${branch}".\n` +
901
+ ` - Already on "${branch}": do nothing.\n` +
902
+ ` - Exists locally: git checkout "${branch}"\n` +
903
+ ` - Exists on origin: git checkout --track origin/"${branch}"\n` +
904
+ ` - Otherwise: git checkout -b "${branch}"\n\n`
905
+ : `Step 2: Detect current branch.\n` +
906
+ ` Run: git rev-parse --abbrev-ref HEAD\n` +
907
+ ` Use this as the sprint branch. Do NOT switch or create any branch.\n\n`) +
908
+ `Step 3: Capture start timestamp.\n` +
909
+ ` Run: date +%Y%m%d_%H%M%S\n` +
910
+ ` Return the output as startedAt (e.g. "20260620_143022").\n\n` +
911
+ `Step 4: Check for required project files.\n` +
912
+ ` Run: test -f deploy.md && echo YES || echo NO -> deployMdExists\n` +
913
+ ` Run: test -f integ-test-playbook.md && echo YES || echo NO -> playbookExists\n\n` +
914
+ `Step 5: Merge deploy permissions into .claude/settings.json.\n` +
915
+ ` For each of deploy.md and integ-test-playbook.md that exists:\n` +
916
+ ` a. Read the file and extract lines under the "## Permissions" section\n` +
917
+ ` (stop at the next ## heading). Each non-empty line is a permission entry\n` +
918
+ ` such as "Bash(docker *)" or "Bash(npm run *)".\n` +
919
+ ` b. Read .claude/settings.json (create it as {} if absent).\n` +
920
+ ` c. For each extracted permission not already in permissions.allow, add it.\n` +
921
+ ` d. Write the updated .claude/settings.json back.\n` +
922
+ ` If neither file has a ## Permissions section, skip this step.\n\n` +
923
+ `Step 6: Load or bootstrap calibration data.\n` +
924
+ ` If sprint-logs/calibration.json exists in the repo root:\n` +
925
+ ` Run: cat sprint-logs/calibration.json\n` +
926
+ ` Return the exact stdout of that command as the "calibrationRaw" field (verbatim -- do not reformat or summarize).\n` +
927
+ ` If it does NOT exist (first run):\n` +
928
+ ` Create the sprint-logs/ directory: mkdir -p sprint-logs\n` +
929
+ ` Write the following JSON exactly to sprint-logs/calibration.json:\n` +
930
+ JSON.stringify(DEFAULT_CALIBRATION, null, 2) + `\n` +
931
+ ` Return that same JSON text verbatim as the "calibrationRaw" field.\n\n` +
932
+ `Step 7: Resolve transcript directory.\n` +
933
+ ` Claude subagent conversation logs (JSONL) are stored under:\n` +
934
+ ` $HOME/.claude/projects/<project-slug>/\n` +
935
+ ` where <project-slug> is derived from the repo absolute path by uppercasing the\n` +
936
+ ` drive letter and replacing path separators with dashes.\n` +
937
+ ` Run: ls "$HOME/.claude/projects/" 2>/dev/null\n` +
938
+ ` Find the entry whose slug matches the repo path (e.g. repo=/c/foo/bar -> C--foo-bar).\n` +
939
+ ` If found, return the full path as transcriptDir. If not found, return an empty string.\n\n` +
940
+ `Return repo (absolute path), branch (confirmed), deployMdExists, playbookExists, startedAt, calibrationRaw, transcriptDir.`,
941
+ { model: MODEL_HAIKU, label: 'setup', phase: 'Plan', schema: SETUP_SCHEMA }
942
+ );
943
+
944
+ if (!setup || !setup.repo || !setup.branch) {
945
+ log('ERROR: setup failed -- could not assert branch or locate repo');
946
+ return { error: 'setup failed' };
947
+ }
948
+
949
+ const repo = setup.repo;
950
+ branch = setup.branch; // use the confirmed/detected branch for all subsequent agent prompts
951
+
952
+ // Refuse to run a sprint directly on a protected branch -- all work must go on a feature branch.
953
+ if (branch === 'main' || branch === 'master') {
954
+ log(`ERROR: sprint branch resolved to "${branch}" -- refusing to run on a protected branch. Pass a branch arg to create or switch to a sprint branch.`);
955
+ return { error: 'protected branch' };
956
+ }
957
+
958
+ // Parse calibration from the raw string the setup agent returned verbatim.
959
+ // Deep-merge with DEFAULT_CALIBRATION so any missing/new field always has a valid value.
960
+ // historical gets its own merge because it accumulates real sprint history on top of the zeros.
961
+ let _parsedCalib = {};
962
+ try { _parsedCalib = JSON.parse(setup.calibrationRaw || '{}'); } catch {}
963
+ const calibration = Object.assign({}, DEFAULT_CALIBRATION, _parsedCalib, {
964
+ historical: Object.assign({}, DEFAULT_CALIBRATION.historical, _parsedCalib.historical || {}),
965
+ complexity_buckets: _parsedCalib.complexity_buckets || DEFAULT_CALIBRATION.complexity_buckets,
966
+ model_prices_per_1m_output_tokens: _parsedCalib.model_prices_per_1m_output_tokens || DEFAULT_CALIBRATION.model_prices_per_1m_output_tokens,
967
+ role_models: _parsedCalib.role_models || DEFAULT_CALIBRATION.role_models,
968
+ fixed_overhead_tokens: _parsedCalib.fixed_overhead_tokens || DEFAULT_CALIBRATION.fixed_overhead_tokens,
969
+ cycle_assumptions: _parsedCalib.cycle_assumptions || DEFAULT_CALIBRATION.cycle_assumptions,
970
+ reviewer_ratio: _parsedCalib.reviewer_ratio || DEFAULT_CALIBRATION.reviewer_ratio,
971
+ input_cost_multiplier: _parsedCalib.input_cost_multiplier || DEFAULT_CALIBRATION.input_cost_multiplier,
972
+ outlier_thresholds: _parsedCalib.outlier_thresholds || DEFAULT_CALIBRATION.outlier_thresholds,
973
+ });
974
+ // Sync output prices from loaded calibration so dispatchLedger uses correct rates.
975
+ Object.assign(OUTPUT_PRICE_PER_M, calibration.model_prices_per_1m_output_tokens || {});
976
+
977
+ // State for cost estimation -- populated after plan is APPROVED.
978
+ let sprintQuote = null;
979
+ // taskAssignments (id->bucket->model) from the last approved plan-review.
980
+ // Held at workflow scope so computeUpdatedCalibration can join doer log entries
981
+ // back to S/M/L buckets at sprint close without re-querying beads.
982
+ let taskAssignments = [];
983
+
984
+ // Derive a filename-safe version of the branch for sprint-logs/.
985
+ // Replaces path separators and non-safe chars with dashes so that parallel
986
+ // sprints on different branches never write to the same file.
987
+ // Timestamp (yyyymmdd_hhmmss) is captured by the setup agent so it stays
988
+ // stable across workflow resumes (Date.now() is banned in workflow scripts).
989
+ const sprintLogBranch = branch.replace(/[^a-zA-Z0-9._-]/g, '-').replace(/-{2,}/g, '-').replace(/^-|-$/g, '') || 'default';
990
+ const sprintLogFile = `sprint-logs/${sprintLogBranch}-${setup.startedAt}.jsonl`;
991
+ const integTestEnabled = setup.deployMdExists && setup.playbookExists;
992
+ // startedAt "20260622_020952" -> ISO "2026-06-22T02:09:52Z" (pure string, no Date.now())
993
+ const sprintTs = setup.startedAt.replace(/^(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3T$4:$5:$6Z');
994
+ let flushedCount = 0; // how many dispatchLedger entries have been appended to sprintLogFile
995
+
996
+ // Appends only the NEW (not yet flushed) ledger entries to the sprint log file,
997
+ // commits, and pushes. Call after each meaningful agent boundary for JIT visibility.
998
+ async function appendNewEntries(label, phase) {
999
+ const newEntries = dispatchLedger.slice(flushedCount);
1000
+ if (newEntries.length === 0) return;
1001
+ // ts placeholder is replaced by the agent with the real wall-clock time at flush,
1002
+ // not the fixed sprint-start timestamp, so each flush batch gets its own timestamp.
1003
+ const lines = newEntries.map(e => JSON.stringify({ ts: '__FLUSH_TS__', ...e })).join('\n');
1004
+ flushedCount = dispatchLedger.length; // update before dispatch so log-append entry goes in next batch
1005
+ await dispatch(
1006
+ `Step 1: Run: date +%Y-%m-%dT%H:%M:%S%z\n` +
1007
+ `Save the output as FLUSH_TS (e.g. "2026-06-22T22:15:30+0530").\n\n` +
1008
+ `Step 2: Append (do NOT overwrite) the following lines to ${sprintLogFile} (full path: "${repo}/${sprintLogFile}").\n` +
1009
+ `If the file does not exist, create it. If the sprint-logs/ directory does not exist, create it first:\n` +
1010
+ ` mkdir -p "${repo}/sprint-logs"\n\n` +
1011
+ `In the lines below, replace every occurrence of "__FLUSH_TS__" with the FLUSH_TS value from Step 1.\n` +
1012
+ `Lines to append (one JSON object per line):\n${lines}\n\n` +
1013
+ `Then commit and push:\n` +
1014
+ ` git -C "${repo}" add sprint-logs/\n` +
1015
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "chore: sprint-log ${label}"\n` +
1016
+ ` git -C "${repo}" push origin ${branch}\n` +
1017
+ `Do not modify any other file.`,
1018
+ { model: MODEL_HAIKU, label: `log-append-${label}`, phase: phase || 'Develop',
1019
+ context: `${newEntries.length} new entries` }
1020
+ );
1021
+ }
1022
+
1023
+ log(`Repo: ${repo} | Branch: ${setup.branch}`);
1024
+ log(`deploy.md: ${setup.deployMdExists} | integ-test-playbook.md: ${setup.playbookExists}`);
1025
+ if (!setup.deployMdExists) log('WARNING: deploy.md not found -- integration test phase will be skipped');
1026
+ if (!setup.playbookExists) log('WARNING: integ-test-playbook.md not found -- integration test phase will be skipped');
1027
+ if (!integTestEnabled) log('Integration testing disabled for this sprint. Harvest will run after Develop.');
1028
+
1029
+ const rootSummary = rootIds.join(', ');
1030
+ log(`Sprint goals: ${rootSummary} | Goal: ${goal} (P<=${threshold}) | Max cycles: ${maxCycles}`);
1031
+
1032
+ // ------------------------------------------------------------------ SPRINT META RECORD
1033
+ // Write the first JSONL entry (type=meta) capturing sprint metadata and transcript dir.
1034
+ // This is benign for existing consumers: computeSprintAnalysis skips entries without a label.
1035
+ {
1036
+ const metaLine = JSON.stringify({
1037
+ ts: sprintTs, type: 'meta',
1038
+ branch, startedAt: setup.startedAt,
1039
+ roots: rootIds, goal,
1040
+ transcriptDir: setup.transcriptDir || '',
1041
+ });
1042
+ await dispatch(
1043
+ `Write sprint meta record and commit.\n\n` +
1044
+ `Step 1: Ensure sprint-logs/ directory exists:\n` +
1045
+ ` mkdir -p "${repo}/sprint-logs"\n\n` +
1046
+ `Step 2: Append (do NOT overwrite) the following line to ${sprintLogFile} (full path: "${repo}/${sprintLogFile}").\n` +
1047
+ ` If the file does not exist, create it first.\n\n` +
1048
+ `Line:\n${metaLine}\n\n` +
1049
+ `Step 3: Commit and push:\n` +
1050
+ ` git -C "${repo}" add sprint-logs/\n` +
1051
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "chore: sprint-meta ${branch} ${setup.startedAt}"\n` +
1052
+ ` git -C "${repo}" push origin ${branch}\n` +
1053
+ `Do not modify any other file. Return "OK" when done.`,
1054
+ { model: MODEL_HAIKU, label: 'sprint-meta', phase: 'Plan' }
1055
+ );
1056
+ }
1057
+
1058
+ // ------------------------------------------------------------------ SPRINT LOOP
1059
+
1060
+ while (cycleCount < maxCycles) {
1061
+ cycleCount++;
1062
+ cycleCostUsd = 0;
1063
+ log(`\n=== Cycle ${cycleCount}/${maxCycles} | goal: ${goal} ===`);
1064
+
1065
+ // ---------------------------------------------------------------- RESUME CHECK
1066
+
1067
+ phase('Plan');
1068
+
1069
+ const cycleState = await checkCycleState(rootIds);
1070
+ log(`Cycle state: planDone=${cycleState.planDone} inProgress=[${cycleState.inProgressIds.join(', ')}]`);
1071
+
1072
+ // Reset any tasks orphaned in_progress from a previous crashed run.
1073
+ if (cycleState.inProgressIds.length > 0) {
1074
+ log(`Resetting ${cycleState.inProgressIds.length} orphaned in_progress task(s) to open`);
1075
+ for (const id of cycleState.inProgressIds) {
1076
+ await dispatch(
1077
+ `Run: bd update ${id} --status=open`,
1078
+ { model: MODEL_HAIKU, label: `reset-${id}`, phase: 'Plan' }
1079
+ );
1080
+ }
1081
+ }
1082
+
1083
+ // ---------------------------------------------------------------- PLAN
1084
+
1085
+ let planApproved = cycleState.planDone;
1086
+ let planFeedback = '';
1087
+ const MAX_PLAN_ITER = 3;
1088
+
1089
+ if (planApproved) {
1090
+ log(`Plan already complete -- skipping plan loop for cycle ${cycleCount}`);
1091
+ }
1092
+
1093
+ for (let pi = 0; pi < MAX_PLAN_ITER && !planApproved; pi++) {
1094
+ const plannerLabel = `planner-c${cycleCount}-r${pi}`;
1095
+
1096
+ const plannerResult = await dispatch(
1097
+ `Repo: ${repo}\nBranch: ${branch}\nBase branch: ${base_branch}\n` +
1098
+ `Sprint goals: ${rootSummary}\n` +
1099
+ (requirementsFile ? `Additional context: ${requirementsFile}\n` : '') +
1100
+ `\n` +
1101
+ (planFeedback
1102
+ ? `Plan-reviewer feedback from the previous round (read feedback.md in ${repo} for full details):\n${planFeedback}\nAddress every item before proceeding.\n\n`
1103
+ : '') +
1104
+ `Inspect existing state first:\n` +
1105
+ ` ${rootIds.map(id => `bd show ${id} && bd graph --compact ${id}`).join('\n ')}\n` +
1106
+ `Run: bd show <id> on any existing features/tasks to read their current descriptions.\n` +
1107
+ `Then build or complete the feature+task DAG -- create only what is missing:\n` +
1108
+ ` - BEFORE creating any feature or task, run: bd search "<title>" --status all\n` +
1109
+ ` If a matching issue already exists, update it instead of creating a duplicate.\n` +
1110
+ `\n` +
1111
+ `DEPENDENCY WIRING -- read this carefully. "bd dep add A B" means A CANNOT CLOSE until B is done.\n` +
1112
+ `The correct wiring direction is: parents depend on children (children unblock first).\n` +
1113
+ `\n` +
1114
+ ` Step 1 -- wire sprint goal -> child (goal waits for children):\n` +
1115
+ ` bd dep add <goal-id> <child-id>\n` +
1116
+ ` After this: "bd ready" will NOT show the sprint goal (it's waiting). Children show as ready.\n` +
1117
+ `\n` +
1118
+ ` Step 2 -- wire feature -> tasks (feature waits for tasks):\n` +
1119
+ ` bd dep add <feature-id> <impl-task-id>\n` +
1120
+ ` bd dep add <feature-id> <test-task-id>\n` +
1121
+ ` After this: "bd ready" will show impl-task (the leaf). Feature is now blocked.\n` +
1122
+ `\n` +
1123
+ ` Step 3 -- wire test after impl:\n` +
1124
+ ` bd dep add <test-task-id> <impl-task-id>\n` +
1125
+ ` After this: "bd ready" shows only impl-task. test-task unblocks once impl-task closes.\n` +
1126
+ `\n` +
1127
+ ` VERIFY after wiring: run "bd ready" -- it must return impl tasks, NOT sprint goals or blocked parents.\n` +
1128
+ ` If sprint goals appear in "bd ready" the deps are backwards -- fix them before continuing.\n` +
1129
+ `\n` +
1130
+ ` IMPORTANT: Each task belongs to exactly ONE feature. Never share a task across features.\n` +
1131
+ `\n` +
1132
+ ` Break each sprint goal into child issues: bd create --parent <goal-id> (use type=feature for sub-goals, type=task for leaf work).\n` +
1133
+ ` Create type=task issues for each feature: implementation tasks AND integration\n` +
1134
+ ` test development tasks (prefix test tasks with "[test]" in the title)\n` +
1135
+ ` Features P1/P2; tasks one level below their parent feature (P1 feature -> P2 tasks, P2 feature -> P3 tasks)\n` +
1136
+ ` Each task must be completable in one agent session (1-3 file changes max)\n` +
1137
+ ` Every task needs clear acceptance criteria in its description\n` +
1138
+ ` - Assign each task a tier AND complexity bucket based on complexity -- after creating or updating each\n` +
1139
+ ` task, run: bd update <id> --set-metadata model=<tier>\n` +
1140
+ ` Available tiers and when to use them:\n` +
1141
+ ` ${TIER_CHEAP} -- mechanical work: rename, config tweak, move file, simple wiring\n` +
1142
+ ` ${TIER_STANDARD} -- standard work: new function, test suite, API endpoint, refactor\n` +
1143
+ ` ${TIER_PREMIUM} -- hard work: architecture, multi-file design, ambiguous requirements\n` +
1144
+ ` Complexity buckets (S/M/L) are assigned by the plan-reviewer based on task scope.\n` +
1145
+ ` Every task MUST receive a bucket assignment -- tasks without a bucket cannot be cost-estimated.\n` +
1146
+ ` - Group tasks so consecutive tasks in dependency order share a tier where\n` +
1147
+ ` possible -- this minimises tier-switching overhead during execution\n` +
1148
+ (cycleCount > 1
1149
+ ? `This is cycle ${cycleCount}. Focus on open issues only.\n` +
1150
+ `Do NOT add new scope beyond the original sprint goals and open bugs/enhancements.\n` +
1151
+ `Do NOT re-create tasks that are already closed.\n`
1152
+ : '') +
1153
+ `Confirm with any text when done.`,
1154
+ { model: MODEL_OPUS, label: plannerLabel, phase: 'Plan', agentType: 'planner',
1155
+ context: `planning sprint goals ${rootSummary}` }
1156
+ );
1157
+
1158
+ if (!plannerResult) {
1159
+ log(`Planner returned null on cycle ${cycleCount} round ${pi} -- retrying`);
1160
+ continue;
1161
+ }
1162
+
1163
+ const planReviewerLabel = `plan-reviewer-c${cycleCount}-r${pi}`;
1164
+ const planReview = await dispatch(
1165
+ `Repo: ${repo}\nBranch: ${branch}\nSprint goals: ${rootSummary}\n` +
1166
+ `Calibration file: ${repo}/sprint-logs/calibration.json (read this first if it exists)\n\n` +
1167
+ `Review the beads DAG for these sprint goals ONLY: ${rootSummary}\n` +
1168
+ `Run: ${rootIds.map(id => `bd show ${id}`).join(' && ')} to inspect each sprint goal.\n` +
1169
+ `Run: ${rootIds.map(id => `bd graph --compact ${id}`).join(' && ')} for the full dependency subtree.\n` +
1170
+ `Run: bd show <id> to inspect individual issues in depth.\n` +
1171
+ `Run: bd ready -- this is your FIRST correctness check.\n` +
1172
+ `Do NOT review or comment on issues outside these sprint goals.\n\n` +
1173
+ `Follow your runbook (plan-reviewer.md) step by step:\n` +
1174
+ ` Steps 1-2: inspect the DAG and check all quality criteria.\n` +
1175
+ ` Step 3: classify each task -- assign complexity bucket (S/M/L) and read its model\n` +
1176
+ ` from beads metadata. If a task has no model metadata, note it in your verdict\n` +
1177
+ ` notes as a warning but do NOT return CHANGES NEEDED for it -- the workflow has a fallback.\n` +
1178
+ ` Step 4: return verdict, notes, and taskAssignments (id + bucket + model per task).\n\n` +
1179
+ `Notes must be specific: include issue IDs and exact "bd dep add" commands to fix\n` +
1180
+ `any dependency direction problems.`,
1181
+ { model: MODEL_SONNET, label: planReviewerLabel, phase: 'Plan', schema: PLAN_REVIEW_SCHEMA, agentType: 'plan-reviewer',
1182
+ context: `reviewing plan for sprint goals ${rootSummary}` }
1183
+ );
1184
+
1185
+ if (approved(planReview)) {
1186
+ planApproved = true;
1187
+ log(`Plan APPROVED on cycle ${cycleCount} round ${pi + 1}`);
1188
+
1189
+ // Persist taskAssignments at workflow scope for the calibration join at sprint close.
1190
+ taskAssignments = planReview.taskAssignments || [];
1191
+
1192
+ // Compute sprint cost quote in pure JS -- no agent does arithmetic.
1193
+ sprintQuote = computeSprintQuote(taskAssignments, calibration);
1194
+ const sc = sprintQuote.scenarios;
1195
+ log(`Sprint quote (${sprintQuote.calibrationSource}, ${taskAssignments.length} tasks): ` +
1196
+ `output-only: opt=$${sc.optimistic.outputOnly.toFixed(3)} ` +
1197
+ `exp=$${sc.expected.outputOnly.toFixed(3)} ` +
1198
+ `pess=$${sc.pessimistic.outputOnly.toFixed(3)} ` +
1199
+ `| true-est (x${sprintQuote.inputMultiplier.toFixed(1)}): ` +
1200
+ `exp=$${sc.expected.total.toFixed(3)}`);
1201
+
1202
+ // Write per-task cost estimates to beads notes via a lightweight haiku dispatch.
1203
+ if (sprintQuote.tasks.length > 0) {
1204
+ const bdCmds = sprintQuote.tasks.map(t =>
1205
+ `bd update ${t.id} --notes="cost-estimate: bucket=${t.bucket} model=${t.model} ` +
1206
+ `doer_tokens=${t.doerTokens} reviewer_tokens=${t.reviewerTokens} output_usd=${t.outputUsd.toFixed(4)}"`
1207
+ ).join('\n');
1208
+ await dispatch(
1209
+ `Write cost estimates to beads task notes.\n\nRun these commands:\n${bdCmds}`,
1210
+ { model: MODEL_HAIKU, label: `write-quote-c${cycleCount}`, phase: 'Plan' }
1211
+ );
1212
+ }
1213
+
1214
+ // Commit plan: marker so the independent gate checker can confirm the plan phase ran.
1215
+ await dispatch(
1216
+ `Export beads snapshot and commit a plan: marker commit.\n\n` +
1217
+ `Run these steps in order:\n` +
1218
+ ` bd export -o "${repo}/.beads/issues.jsonl"\n` +
1219
+ ` git -C "${repo}" add .beads/issues.jsonl\n` +
1220
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "plan: approve task DAG"\n\n` +
1221
+ `If that last git commit fails with "nothing to commit" (file unchanged), run instead:\n` +
1222
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit --allow-empty -m "plan: approve task DAG"\n\n` +
1223
+ `The commit message MUST start with "plan:" -- do not change it.\n\n` +
1224
+ `After committing, push the branch:\n` +
1225
+ ` git -C "${repo}" push origin ${branch}`,
1226
+ { model: MODEL_HAIKU, label: `plan-commit-c${cycleCount}`, phase: 'Plan' }
1227
+ );
1228
+ } else {
1229
+ planFeedback = (planReview && planReview.notes) || '';
1230
+ log(`Plan needs changes: ${planFeedback.slice(0, 120)}`);
1231
+ await commitFeedback(repo, branch, planFeedback, 'pm-plan-reviewer', planReviewerLabel, 'Plan');
1232
+ }
1233
+ }
1234
+
1235
+ if (!planApproved) {
1236
+ log(`Plan not approved after ${MAX_PLAN_ITER} rounds -- aborting sprint`);
1237
+ abortReason = 'plan not approved';
1238
+ break;
1239
+ }
1240
+
1241
+ // ---------------------------------------------------------------- DEVELOP
1242
+
1243
+ phase('Develop');
1244
+
1245
+ const MAX_DEV_ITER = 20;
1246
+ let devIter = 0;
1247
+ let devFeedback = '';
1248
+
1249
+ while (devIter < MAX_DEV_ITER) {
1250
+ const streakResult = await getReadyStreaks(rootIds);
1251
+ if (streakResult.totalCount === 0) {
1252
+ log(`No ready tasks -- develop phase complete (${devIter} iterations)`);
1253
+ break;
1254
+ }
1255
+ log(`Ready: ${streakResult.totalCount} task(s) across ${streakResult.streaks.length} model streak(s)`);
1256
+
1257
+ // Dispatch one doer per model streak; collect all worked task IDs for the reviewer.
1258
+ const workedIds = [];
1259
+ let streakAbort = false;
1260
+
1261
+ for (const streak of streakResult.streaks) {
1262
+ const doerLabel = `doer-c${cycleCount}-i${devIter}-${streak.model}`;
1263
+ log(`Streak: model=${streak.model} tasks=${streak.ids.join(', ')}`);
1264
+
1265
+ const doerResult = await dispatch(
1266
+ `Repo: ${repo}\nBranch: ${branch}\n\n` +
1267
+ (devFeedback
1268
+ ? `Reviewer feedback from the previous iteration (read feedback.md in ${repo} for full details):\n${devFeedback}\nAddress every finding before closing tasks.\n\n`
1269
+ : '') +
1270
+ `Work ONLY these tasks (in order): ${streak.ids.join(', ')}\n` +
1271
+ `Confirm each is still unblocked with: bd show <id>\n` +
1272
+ `For each task:\n` +
1273
+ ` - Run: bd update <id> --claim\n` +
1274
+ ` - Implement the work described (code, tests, config -- whatever the task requires)\n` +
1275
+ ` - Run: bd close <id> when the task is complete\n` +
1276
+ ` - NEVER close a type=feature or type=bug issue -- only close type=task\n` +
1277
+ `Work all listed tasks then stop and return status "VERIFY".\n` +
1278
+ `Always return VERIFY -- never return anything else.`,
1279
+ { model: streak.model, label: doerLabel, phase: 'Develop', schema: DOER_STATUS_SCHEMA, agentType: 'doer',
1280
+ context: `tasks ${streak.ids.join(', ')}` }
1281
+ );
1282
+
1283
+ if (!doerResult) {
1284
+ log(`Doer returned null (streak ${streak.model}) -- aborting`);
1285
+ abortReason = 'doer null';
1286
+ streakAbort = true;
1287
+ break;
1288
+ }
1289
+
1290
+ if (doerResult.status !== 'VERIFY') {
1291
+ log(`Unexpected doer status "${doerResult.status}" -- aborting`);
1292
+ abortReason = 'unexpected doer status';
1293
+ streakAbort = true;
1294
+ break;
1295
+ }
1296
+ workedIds.push(...streak.ids);
1297
+ }
1298
+
1299
+ devIter++;
1300
+ if (streakAbort) break;
1301
+
1302
+ // Reviewer tier matches the highest tier used across all streaks:
1303
+ // any premium streak -> premium; otherwise standard (cheap work reviewed at standard minimum).
1304
+ const usedModels = streakResult.streaks.map(s => s.model);
1305
+ const reviewerModel = usedModels.includes(TIER_PREMIUM) ? TIER_PREMIUM : TIER_STANDARD;
1306
+
1307
+ // One reviewer pass covering all streaks worked this iteration.
1308
+ const reviewerLabel = `reviewer-c${cycleCount}-i${devIter}`;
1309
+ const review = await dispatch(
1310
+ `Repo: ${repo}\nBranch: ${branch}\nBase branch: ${base_branch}\n` +
1311
+ `Sprint goals: ${rootSummary}\nTasks worked this iteration: ${workedIds.join(', ')}\n\n` +
1312
+ `Review ONLY the work done for the tasks listed above.\n` +
1313
+ `Run: bd show <id> for each task to read its acceptance criteria.\n` +
1314
+ `Run: git -C "${repo}" diff ${base_branch}...${branch} to see the changes.\n` +
1315
+ `Do NOT comment on code or issues outside the listed tasks.\n` +
1316
+ `Check: code correctness, test coverage, adherence to each task's acceptance criteria.\n` +
1317
+ `If a task needs rework, reopen it: bd update <id> --status=open\n` +
1318
+ `CHANGES NEEDED verdict must include specific actionable feedback tied to a task ID.\n` +
1319
+ `APPROVED means all committed work meets acceptance criteria.`,
1320
+ { model: reviewerModel, label: reviewerLabel, phase: 'Develop', schema: REVIEW_SCHEMA, agentType: 'reviewer',
1321
+ context: `reviewing tasks ${workedIds.join(', ')}` }
1322
+ );
1323
+ log(`Reviewer verdict: ${review && review.verdict || 'null'}`);
1324
+
1325
+ if (!approved(review)) {
1326
+ devFeedback = (review && review.notes) || '';
1327
+ log(`Reviewer feedback: ${devFeedback.slice(0, 120)}`);
1328
+ await commitFeedback(repo, branch, devFeedback, 'pm-reviewer', reviewerLabel, 'Develop');
1329
+ // Reopened tasks will show in bd ready next iteration
1330
+ } else {
1331
+ devFeedback = '';
1332
+ }
1333
+
1334
+ // JIT flush: append this iteration's entries immediately so the log grows as work lands.
1335
+ await appendNewEntries(`iter-c${cycleCount}-i${devIter}`, 'Develop');
1336
+ }
1337
+
1338
+ if (abortReason) break;
1339
+
1340
+ // Push branch so CI can trigger, then record HEAD SHA.
1341
+ await dispatch(
1342
+ `Run: git push origin ${branch}\nIf the branch does not yet exist on origin, use: git push -u origin ${branch}`,
1343
+ { model: MODEL_HAIKU, label: `push-c${cycleCount}`, phase: 'Develop' }
1344
+ );
1345
+
1346
+ const shaAgent = await dispatch(
1347
+ `Run: git rev-parse HEAD\nReturn the full SHA string.`,
1348
+ { model: MODEL_HAIKU, label: `head-sha-c${cycleCount}`, phase: 'Develop',
1349
+ schema: { type: 'object', required: ['sha'], properties: { sha: { type: 'string' } } } }
1350
+ );
1351
+ if (shaAgent && shaAgent.sha) headSha = shaAgent.sha;
1352
+ log(`HEAD SHA: ${headSha}`);
1353
+
1354
+ // ---------------------------------------------------------------- INTEGRATION TEST (skip if files missing)
1355
+
1356
+ if (integTestEnabled) {
1357
+ phase('Test');
1358
+
1359
+ // -- Deploy --
1360
+ const deployLabel = `deployer-c${cycleCount}`;
1361
+ const deployResult = await dispatch(
1362
+ `Repo: ${repo}\nBranch: ${branch}\nCycle: ${cycleCount}\n\n` +
1363
+ `Follow the integration test playbook and deploy.md:\n` +
1364
+ (cycleCount === 1
1365
+ ? `1. Run the Setup section of integ-test-playbook.md to bring up the test environment.\n`
1366
+ : `1. Run the Reset section of integ-test-playbook.md to restore pristine state.\n`) +
1367
+ `2. Follow all steps in deploy.md to deploy the build.\n` +
1368
+ `3. Run the smoke test defined in deploy.md.\n` +
1369
+ `4. Return deployed: true if the smoke test passes, false otherwise.\n` +
1370
+ `5. If deployed is false, include the error output in notes.`,
1371
+ { model: MODEL_SONNET, label: deployLabel, phase: 'Test', agentType: 'deployer',
1372
+ schema: { type: 'object', required: ['deployed'], properties: {
1373
+ deployed: { type: 'boolean' }, notes: { type: 'string' } } } }
1374
+ );
1375
+
1376
+ if (!deployResult || !deployResult.deployed) {
1377
+ const msg = (deployResult && deployResult.notes) || 'no details';
1378
+ log(`Deploy failed on cycle ${cycleCount}: ${msg.slice(0, 200)}`);
1379
+ log('Skipping integration tests this cycle -- teardown and continue');
1380
+ // Teardown before next cycle
1381
+ await dispatch(
1382
+ `Run the Teardown section of integ-test-playbook.md to clean up the test environment.`,
1383
+ { model: MODEL_SONNET, label: `teardown-c${cycleCount}-fail`, phase: 'Test', agentType: 'deployer' }
1384
+ );
1385
+ } else {
1386
+ // -- Integration test run --
1387
+ const integLabel = `integ-runner-c${cycleCount}`;
1388
+
1389
+ const integResult = await dispatch(
1390
+ `Repo: ${repo}\nBranch: ${branch}\nCycle: ${cycleCount}\n` +
1391
+ `Sprint goals: ${rootSummary}\n\n` +
1392
+ `Run: bd list --type=feature --status=open\n` +
1393
+ `For each open feature, execute its integration tests.\n\n` +
1394
+ `For each feature:\n` +
1395
+ ` PASS: all tests pass -> bd close <feature-id>\n` +
1396
+ ` FAIL: tests fail -> bd create --title="[integ] <description>" ` +
1397
+ `--description="Feature: <id>\\nExpected: <what>\\nActual: <what>\\nTest: <which>" ` +
1398
+ `--type=bug --priority=<1=core requirement unmet, 2=partial, 3=quality>\n` +
1399
+ ` Keep feature open on failure or if inconclusive.\n\n` +
1400
+ `Priority rules:\n` +
1401
+ ` P0: system won't start or core path completely broken\n` +
1402
+ ` P1: requirement from sprint goal explicitly not met\n` +
1403
+ ` P2: requirement partially met, degraded behaviour\n` +
1404
+ ` P3: quality, performance, or UX issue not blocking core function\n\n` +
1405
+ `Before creating a new bug, check bd search "[integ]" -- update existing if duplicate.\n\n` +
1406
+ `Return featuresClosed (count), issuesCreated (count), summary (one paragraph).`,
1407
+ { model: MODEL_SONNET, label: integLabel, phase: 'Test', schema: INTEG_RUN_SCHEMA, agentType: 'integ-test-runner' }
1408
+ );
1409
+ if (integResult) {
1410
+ log(`Integration: ${integResult.featuresClosed} features closed, ${integResult.issuesCreated} issues created`);
1411
+ log(`Summary: ${integResult.summary}`);
1412
+ }
1413
+
1414
+ // -- Teardown --
1415
+ await dispatch(
1416
+ `Run the Teardown section of integ-test-playbook.md to fully clean up the test environment.`,
1417
+ { model: MODEL_SONNET, label: `teardown-c${cycleCount}`, phase: 'Test', agentType: 'deployer' }
1418
+ );
1419
+
1420
+ // JIT flush: append test-phase entries (deployer, integ-runner, teardown) immediately.
1421
+ await appendNewEntries(`test-c${cycleCount}`, 'Test');
1422
+ }
1423
+ }
1424
+
1425
+ // ---------------------------------------------------------------- EXIT CHECK
1426
+
1427
+ const blockers = await countBeadsBlockers(threshold, rootIds);
1428
+ const currentOpenIds = (blockers.ids || []).slice().sort();
1429
+ log(`Exit check: ${blockers.count} open issues at P<=${threshold} -- IDs: [${currentOpenIds.join(', ')}]`);
1430
+
1431
+ // Straggler flush: catches plan-phase, push, head-sha, check-blockers, and any entries
1432
+ // not yet appended (e.g. when integ tests are disabled, or on abortReason paths).
1433
+ const cycleLedger = dispatchLedger.filter(e => e.cycle === cycleCount);
1434
+ const cycleTotal = cycleLedger.reduce((s, e) => s + e.costUsd, 0);
1435
+ log(`Cycle ${cycleCount} cost: $${cycleTotal.toFixed(4)} output across ${cycleLedger.length} dispatches`);
1436
+ await appendNewEntries(`end-c${cycleCount}`, integTestEnabled ? 'Test' : 'Develop');
1437
+
1438
+ // No-progress check: if no issue from the previous cycle was resolved, abort.
1439
+ if (cycleCount > 1 && prevOpenIds.length > 0) {
1440
+ const closedFromPrev = prevOpenIds.filter(id => !currentOpenIds.includes(id));
1441
+ if (closedFromPrev.length === 0) {
1442
+ log(`No progress in cycle ${cycleCount}: same ${prevOpenIds.length} issues unresolved -- aborting`);
1443
+ abortReason = 'no progress';
1444
+ break;
1445
+ }
1446
+ log(`Progress: ${closedFromPrev.length} issue(s) resolved this cycle`);
1447
+ }
1448
+
1449
+ if (blockers.count === 0) {
1450
+ goalMet = true;
1451
+ log(`Goal met after ${cycleCount} cycle(s)`);
1452
+ break;
1453
+ }
1454
+
1455
+ prevOpenIds = currentOpenIds;
1456
+ }
1457
+
1458
+ // ------------------------------------------------------------------ CI CHECK
1459
+
1460
+ phase('Harvest');
1461
+
1462
+ let ciResult = null;
1463
+ if (headSha) {
1464
+ ciResult = await dispatch(
1465
+ `Check CI status for commit ${headSha} on branch ${branch}.\n` +
1466
+ `Run: gh run list --branch ${branch} --limit 3 --json status,conclusion,databaseId\n` +
1467
+ `If runs exist and are in_progress: poll with gh run watch <id> (timeout 10 min).\n` +
1468
+ `If runs exist and conclusion is "success": return status "green".\n` +
1469
+ `If runs exist and conclusion is "failure": return status "red" with notes (include run URL).\n` +
1470
+ `If no runs found: return status "not_configured".\n` +
1471
+ `Do not block for more than 10 minutes total.`,
1472
+ { model: MODEL_HAIKU, label: 'ci-watcher', phase: 'Harvest', schema: CI_SCHEMA, agentType: 'ci-watcher' }
1473
+ );
1474
+
1475
+ if (ciResult) {
1476
+ log(`CI status: ${ciResult.status}`);
1477
+ if (ciResult.status === 'not_configured') {
1478
+ log('CI not configured -- creating beads task');
1479
+ await dispatch(
1480
+ `Run: bd create --title="Add CI pipeline to project" ` +
1481
+ `--description="The auto-sprint workflow found no CI runs for branch ${branch}. ` +
1482
+ `CI is required for the sprint exit gate. ` +
1483
+ `This task covers: choosing a CI provider, writing the workflow config, and verifying it triggers on push." ` +
1484
+ `--type=task --priority=2\n` +
1485
+ `Then run: bd show <new-id> and confirm it was created.`,
1486
+ { model: MODEL_HAIKU, label: 'ci-task-create', phase: 'Harvest' }
1487
+ );
1488
+ log('ACTION REQUIRED: Set up CI for this project. Task created in beads.');
1489
+ } else if (ciResult.status === 'red') {
1490
+ log(`CI FAILED: ${(ciResult.notes || '').slice(0, 200)}`);
1491
+ log('Proceeding to harvest with CI failure noted in PR.');
1492
+ }
1493
+ }
1494
+ }
1495
+
1496
+ // ------------------------------------------------------------------ FINAL REVIEW
1497
+
1498
+ const finalReviewLabel = 'final-reviewer';
1499
+ const finalReview = await dispatch(
1500
+ `Repo: ${repo}\nBranch: ${branch}\nBase branch: ${base_branch}\n` +
1501
+ `Sprint goals: ${rootSummary}\nGoal: ${goal}\n` +
1502
+ (abortReason ? `Sprint ended early: ${abortReason}. Review what was completed.\n` : '') +
1503
+ (goalMet ? `Goal was met: all P<=${threshold} issues resolved.\n` : `Goal not yet met.\n`) +
1504
+ `\nReview the overall output of this sprint:\n` +
1505
+ ` - Does the work address the original sprint goals?\n` +
1506
+ ` - Are there obvious gaps or regressions?\n` +
1507
+ ` - Is the codebase in a releasable state for what was completed?\n` +
1508
+ `APPROVED means the work is ready to harvest and raise as a PR.\n` +
1509
+ `CHANGES NEEDED means critical issues were found; include specific findings in notes.`,
1510
+ { model: MODEL_OPUS, label: finalReviewLabel, phase: 'Harvest', schema: REVIEW_SCHEMA, agentType: 'reviewer' }
1511
+ );
1512
+ log(`Final review: ${finalReview && finalReview.verdict || 'null'}`);
1513
+
1514
+ if (!approved(finalReview)) {
1515
+ const notes = (finalReview && finalReview.notes) || '';
1516
+ log(`Final review not approved -- aborting before harvest. Notes: ${notes.slice(0, 300)}`);
1517
+ return { cycles: cycleCount, goalMet, goal, abortReason: abortReason || 'final review rejected', finalReviewNotes: notes };
1518
+ }
1519
+
1520
+ // ------------------------------------------------------------------ HARVEST
1521
+
1522
+ const logEntries = dispatchLedger;
1523
+
1524
+ // Compute estimate-vs-actual analysis entirely in JS.
1525
+ const sprintAnalysis = computeSprintAnalysis(sprintQuote, logEntries, calibration, cycleCount);
1526
+ log('Sprint cost analysis computed (JS):\n' + sprintAnalysis.analysisText);
1527
+
1528
+ // Build structured summary and write sprint-logs/<branch>-<ts>.analysis.md artefact.
1529
+ const tasksCompleted = goalMet
1530
+ ? (sprintQuote ? sprintQuote.tasks.length : 0)
1531
+ : Math.max(0, (sprintQuote ? sprintQuote.tasks.length : 0) - prevOpenIds.length);
1532
+ const tasksOpen = goalMet ? 0 : prevOpenIds.length;
1533
+ const sprintSummary = buildSprintSummary(sprintAnalysis, sprintQuote, calibration, {
1534
+ branch, goal, goalMet, cycleCount, tasksCompleted, tasksOpen, startedAt: setup.startedAt,
1535
+ });
1536
+ log('Sprint summary:\n' + sprintSummary.summaryText);
1537
+ const analysisArtifactFile = `sprint-logs/${sprintLogBranch}-${setup.startedAt}.analysis.md`;
1538
+ await dispatch(
1539
+ `Write sprint analysis artefact and commit.\n\n` +
1540
+ `Step 1: Ensure sprint-logs/ directory exists:\n` +
1541
+ ` mkdir -p "${repo}/sprint-logs"\n\n` +
1542
+ `Step 2: Write the following content to "${repo}/${analysisArtifactFile}" (overwrite if exists):\n\n` +
1543
+ sprintSummary.summaryText + `\n\n` +
1544
+ `Step 3: Commit and push:\n` +
1545
+ ` git -C "${repo}" add "${repo}/${analysisArtifactFile}"\n` +
1546
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "chore: sprint-analysis ${branch} ${setup.startedAt}"\n` +
1547
+ ` git -C "${repo}" push origin ${branch}\n` +
1548
+ `Do not modify any other file. Return "OK" when done.`,
1549
+ { model: MODEL_HAIKU, label: 'sprint-analysis-write', phase: 'Harvest' }
1550
+ );
1551
+
1552
+ const harvestLabel = 'harvester';
1553
+ const harvestResult = await dispatch(
1554
+ `Repo: ${repo}\nBranch: ${branch}\nBase branch: ${base_branch}\n` +
1555
+ `Sprint goals: ${rootSummary}\nCycles completed: ${cycleCount}\nGoal met: ${goalMet}\n` +
1556
+ `sprintLogFile: ${sprintLogFile}\n\n` +
1557
+ `The sprint is complete. Harvest the sprint artefacts.\n` +
1558
+ `Follow your runbook (agents/harvester.md).\n\n` +
1559
+ `costAnalysis (insert this block verbatim into CHANGELOG.md after the summary paragraph):\n` +
1560
+ `${sprintAnalysis.analysisText}\n` +
1561
+ `Final review notes to include in CHANGELOG:\n` +
1562
+ `${(finalReview && finalReview.notes) || '(none)'}\n\n` +
1563
+ `Return status "OK" if successful, "FAILED" with notes otherwise.`,
1564
+ { model: MODEL_SONNET, label: harvestLabel, phase: 'Harvest', schema: HARVEST_SCHEMA, agentType: 'harvester' }
1565
+ );
1566
+
1567
+ if (!harvestResult || harvestResult.status !== 'OK') {
1568
+ log(`Harvest failed: ${(harvestResult && harvestResult.notes) || 'null'} -- skipping PR`);
1569
+ return { cycles: cycleCount, goalMet, goal, harvest: 'failed' };
1570
+ }
1571
+
1572
+ // ------------------------------------------------------------------ CALIBRATION UPDATE
1573
+ // Update historical averages in calibration.json after every successful sprint.
1574
+ // All arithmetic is in JS; the haiku agent only writes the resulting JSON file.
1575
+
1576
+ const updatedCalibration = computeUpdatedCalibration(calibration, sprintAnalysis, setup.startedAt, taskAssignments, logEntries);
1577
+ const calibrationJson = JSON.stringify(updatedCalibration, null, 2);
1578
+ await dispatch(
1579
+ `Write updated calibration file and commit.\n\n` +
1580
+ `Step 1: Ensure sprint-logs/ directory exists: mkdir -p "${repo}/sprint-logs"\n` +
1581
+ `Step 2: Write this JSON to "${repo}/sprint-logs/calibration.json" exactly as provided below:\n\n` +
1582
+ calibrationJson + `\n\n` +
1583
+ `Step 3: Commit the file:\n` +
1584
+ ` git -C "${repo}" add sprint-logs/calibration.json\n` +
1585
+ ` git -C "${repo}" commit -m "chore: update sprint calibration after ${cycleCount} cycle(s) on ${branch}"\n\n` +
1586
+ `If the file content is unchanged, the commit may be a no-op -- that is fine.\n` +
1587
+ `Return "OK" when done.`,
1588
+ { model: MODEL_HAIKU, label: 'calibration-update', phase: 'Harvest' }
1589
+ );
1590
+
1591
+ // ------------------------------------------------------------------ CLOSE DELIVERED SPRINT GOALS
1592
+
1593
+ // The doer closes tasks; the original sprint-goal epics must be closed explicitly.
1594
+ await dispatch(
1595
+ `Close the delivered sprint goals in beads.\n\n` +
1596
+ `Run:\n` +
1597
+ rootIds.map(id => ` bd close ${id} --reason="implemented in sprint ${branch}"`).join('\n') + `\n\n` +
1598
+ `If an issue is already closed, bd close is a no-op. Return "OK" when done.`,
1599
+ { model: MODEL_HAIKU, label: 'close-sprint-goals', phase: 'Harvest' }
1600
+ );
1601
+
1602
+ // ------------------------------------------------------------------ BEADS EXPORT + SCAFFOLD CLEANUP
1603
+
1604
+ // Export beads state so committed .beads/*.jsonl reflects all closed P1 issues.
1605
+ // Also remove sprint process files (requirements.md, feedback.md) from the PR net diff.
1606
+ await dispatch(
1607
+ `Persist beads state and clean sprint scaffolding from the PR diff.\n\n` +
1608
+ `Step 1 -- Export beads state:\n` +
1609
+ ` bd export -o "${repo}/.beads/issues.jsonl"\n` +
1610
+ ` git -C "${repo}" add .beads/issues.jsonl\n` +
1611
+ ` git -C "${repo}" diff --cached --quiet || git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "chore: export beads state"\n` +
1612
+ ` (The "diff --cached --quiet || commit" pattern only commits if something actually changed.)\n\n` +
1613
+ `Step 2 -- Check what process files are still in the PR diff:\n` +
1614
+ ` git -C "${repo}" diff --name-only ${base_branch}...${branch}\n\n` +
1615
+ `Step 3 -- For each of requirements.md, feedback.md that appears in the diff:\n` +
1616
+ ` a) Check if the file existed on ${base_branch}:\n` +
1617
+ ` git -C "${repo}" ls-tree --name-only ${base_branch} | grep -F <filename>\n` +
1618
+ ` b) If NOT on base (sprint created it): git -C "${repo}" rm --force <filepath>\n` +
1619
+ ` c) If on base (sprint modified it): git -C "${repo}" checkout ${base_branch} -- <filepath>\n` +
1620
+ ` After handling all such files:\n` +
1621
+ ` git -C "${repo}" add -A\n` +
1622
+ ` git -C "${repo}" -c user.name='pm' -c user.email='pm@pm.local' commit -m "chore: drop sprint scaffolding"\n` +
1623
+ ` (If no scaffold files remain in diff, skip the commit.)\n\n` +
1624
+ `Step 4 -- Verify the diff is clean:\n` +
1625
+ ` git -C "${repo}" diff --name-only ${base_branch}...${branch}\n` +
1626
+ ` The output must NOT contain requirements.md or feedback.md. If it does, repeat Step 3.\n\n` +
1627
+ `Step 5 -- Push all local commits to remote:\n` +
1628
+ ` git -C "${repo}" push origin ${branch}\n\n` +
1629
+ `Return "OK" when done.`,
1630
+ { model: MODEL_HAIKU, label: 'beads-export-cleanup', phase: 'Harvest' }
1631
+ );
1632
+
1633
+ // ------------------------------------------------------------------ PR
1634
+
1635
+ await dispatch(
1636
+ `In repo ${repo} on branch ${branch}, create a GitHub pull request targeting ${base_branch}.\n` +
1637
+ `Command: gh pr create --base ${base_branch} --head ${branch}\n` +
1638
+ `Title: summarise what was implemented across ${cycleCount} cycle(s).\n` +
1639
+ `Body:\n` +
1640
+ ` - What was built (per sprint goal)\n` +
1641
+ ` - Sprint goal: ${goal} -- ${goalMet ? 'MET' : 'NOT MET (partial delivery)'}\n` +
1642
+ ` - Cycles run: ${cycleCount}\n` +
1643
+ ` - Open items carried forward (if any): bd list --status=open and summarise\n` +
1644
+ ` - Final review notes: ${(finalReview && finalReview.notes) || '(none)'}\n` +
1645
+ (headSha && ciResult && ciResult.status !== 'green'
1646
+ ? ` - CI: ${ciResult.status} -- see notes\n` : '') +
1647
+ ` - Token cost summary from: bd memories auto-sprint`,
1648
+ { model: MODEL_SONNET, label: 'harvest-pr', phase: 'Harvest' }
1649
+ );
1650
+
1651
+ // ------------------------------------------------------------------ COST SUMMARY
1652
+ // Pure JS -- no agent call. Groups dispatchLedger by role (derived from label prefix)
1653
+ // and by model, prints a table, and reports total sprint cost.
1654
+
1655
+ const roleOf = label => label.replace(/-c\d.*$/, ''); // "doer-c1-i0-haiku" -> "doer"
1656
+
1657
+ const byRole = {};
1658
+ for (const e of dispatchLedger) {
1659
+ const role = roleOf(e.label);
1660
+ if (!byRole[role]) byRole[role] = { costUsd: 0, outTokens: 0, calls: 0 };
1661
+ byRole[role].costUsd += e.costUsd;
1662
+ byRole[role].outTokens += e.outTokens;
1663
+ byRole[role].calls += 1;
1664
+ }
1665
+
1666
+ const sprintTotal = dispatchLedger.reduce((s, e) => s + e.costUsd, 0);
1667
+
1668
+ log('\n=== Sprint cost summary (output tokens only) ===');
1669
+ for (const [role, s] of Object.entries(byRole).sort((a, b) => b[1].costUsd - a[1].costUsd)) {
1670
+ log(` ${role.padEnd(20)} $${s.costUsd.toFixed(4).padStart(8)} ${String(s.outTokens).padStart(8)} tok ${s.calls} call(s)`);
1671
+ }
1672
+ log(` ${'TOTAL'.padEnd(20)} $${sprintTotal.toFixed(4).padStart(8)}`);
1673
+ log(` (input token cost not included -- see ${sprintLogFile} for per-dispatch detail)`);
1674
+ log('================================================\n');
1675
+
1676
+ return { cycles: cycleCount, goalMet, goal, harvest: 'ok', sprintCostUsd: parseFloat(sprintTotal.toFixed(4)) };