@wrongstack/sdd 0.284.1 → 0.285.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 (55) hide show
  1. package/dist/auto-executor.d.ts +89 -0
  2. package/dist/auto-executor.d.ts.map +1 -0
  3. package/dist/board-types.d.ts +144 -0
  4. package/dist/board-types.d.ts.map +1 -0
  5. package/dist/conflict-resolver.d.ts +45 -0
  6. package/dist/conflict-resolver.d.ts.map +1 -0
  7. package/dist/critical-path.d.ts +36 -0
  8. package/dist/critical-path.d.ts.map +1 -0
  9. package/dist/decompose-task.d.ts +20 -0
  10. package/dist/decompose-task.d.ts.map +1 -0
  11. package/dist/index.d.ts +26 -1864
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +192 -76
  14. package/dist/index.js.map +7 -1
  15. package/dist/sdd-board-projector.d.ts +83 -0
  16. package/dist/sdd-board-projector.d.ts.map +1 -0
  17. package/dist/sdd-board-store.d.ts +59 -0
  18. package/dist/sdd-board-store.d.ts.map +1 -0
  19. package/dist/sdd-interview-driver.d.ts +131 -0
  20. package/dist/sdd-interview-driver.d.ts.map +1 -0
  21. package/dist/sdd-lifecycle.d.ts +146 -0
  22. package/dist/sdd-lifecycle.d.ts.map +1 -0
  23. package/dist/sdd-parallel-run.d.ts +427 -0
  24. package/dist/sdd-parallel-run.d.ts.map +1 -0
  25. package/dist/sdd-run-registry.d.ts +68 -0
  26. package/dist/sdd-run-registry.d.ts.map +1 -0
  27. package/dist/sdd-supervisor.d.ts +52 -0
  28. package/dist/sdd-supervisor.d.ts.map +1 -0
  29. package/dist/sdd-task-decomposer.d.ts +89 -0
  30. package/dist/sdd-task-decomposer.d.ts.map +1 -0
  31. package/dist/spec-builder.d.ts +139 -0
  32. package/dist/spec-builder.d.ts.map +1 -0
  33. package/dist/spec-parser.d.ts +14 -0
  34. package/dist/spec-parser.d.ts.map +1 -0
  35. package/dist/spec-store.d.ts +36 -0
  36. package/dist/spec-store.d.ts.map +1 -0
  37. package/dist/spec-templates.d.ts +22 -0
  38. package/dist/spec-templates.d.ts.map +1 -0
  39. package/dist/spec-versioning.d.ts +49 -0
  40. package/dist/spec-versioning.d.ts.map +1 -0
  41. package/dist/start-sdd-run.d.ts +67 -0
  42. package/dist/start-sdd-run.d.ts.map +1 -0
  43. package/dist/task-flow.d.ts +99 -0
  44. package/dist/task-flow.d.ts.map +1 -0
  45. package/dist/task-generator.d.ts +39 -0
  46. package/dist/task-generator.d.ts.map +1 -0
  47. package/dist/task-graph-store.d.ts +33 -0
  48. package/dist/task-graph-store.d.ts.map +1 -0
  49. package/dist/task-tracker.d.ts +2 -0
  50. package/dist/task-tracker.d.ts.map +1 -0
  51. package/dist/task-visualizer.d.ts +26 -0
  52. package/dist/task-visualizer.d.ts.map +1 -0
  53. package/dist/verify-task.d.ts +23 -0
  54. package/dist/verify-task.d.ts.map +1 -0
  55. package/package.json +4 -5
package/dist/index.d.ts CHANGED
@@ -1,1864 +1,26 @@
1
- import { Specification, SpecAnalysis, SpecValidationResult, TaskType, TaskPriority, TaskGraph, DoneCondition, TaskNode, SpecStatus, TaskProgress, TaskResult, SpecTemplate, SpecRequirement } from '@wrongstack/core/types';
2
- import { TaskTracker } from '@wrongstack/core/tasking';
3
- export { DefaultTaskStore, TaskStore, TaskTracker, TaskTrackerChange, TaskTrackerListener, TaskTrackerOptions, TaskTransition } from '@wrongstack/core/tasking';
4
- import { EventBus } from '@wrongstack/core/kernel';
5
- import { Agent, AgentFactory, WorktreeManager, BrainArbiter } from '@wrongstack/core';
6
-
7
- declare class SpecParser {
8
- parse(content: string): Specification;
9
- private extractTitle;
10
- private extractVersion;
11
- private extractOverview;
12
- private extractSections;
13
- private extractRequirements;
14
- private parseRequirementLine;
15
- private mapSectionType;
16
- analyze(spec: Specification): SpecAnalysis;
17
- validate(spec: Specification): SpecValidationResult;
18
- }
19
-
20
- interface TaskGeneratorOptions {
21
- taskTracker: TaskTracker;
22
- /**
23
- * Opt-in (default off): derive each task's completion-gate
24
- * `metadata.verificationCommand` from an acceptance criterion that carries a
25
- * runnable-command marker (`$ <cmd>`, or `run:`/`verify:`/`cmd:` prefix). Off
26
- * by default so the common case stays fast — auto-running a check per task is
27
- * exactly the slowness the robustness initiative set out to avoid; enable it
28
- * explicitly (the CLI gates it behind WRONGSTACK_SDD_VERIFY_FROM_ACCEPTANCE).
29
- */
30
- verificationFromAcceptance?: boolean | undefined;
31
- }
32
- /**
33
- * Pull a runnable verification command out of a requirement's acceptance
34
- * criteria. A criterion qualifies only when it carries an explicit marker —
35
- * `$ <cmd>` (shell-prompt style) or a `run:` / `verify:` / `cmd:` prefix — so
36
- * free-text criteria are never mistaken for commands. Returns the first match.
37
- */
38
- declare function extractVerificationCommand(criteria: readonly string[]): string | undefined;
39
- interface GeneratedTask {
40
- specRequirementId?: string | undefined;
41
- title: string;
42
- description: string;
43
- type: TaskType;
44
- priority: TaskPriority;
45
- estimateHours?: number | undefined;
46
- tags?: string[] | undefined;
47
- }
48
- declare class TaskGenerator {
49
- private readonly opts;
50
- constructor(opts: TaskGeneratorOptions);
51
- generateFromSpec(spec: Specification): Promise<TaskGraph>;
52
- generateSubtasks(parentTaskId: string, spec: Specification): Promise<void>;
53
- }
54
-
55
- /**
56
- * Extended event map used internally by TaskFlow and multi-agent components.
57
- * These events are emitted on the injected EventBus and are a subset of
58
- * the full EventMap — they do not require a separate registration.
59
- */
60
- interface TaskFlowEventMap {
61
- 'phase.change': {
62
- from: TaskFlowPhase;
63
- to: TaskFlowPhase;
64
- };
65
- 'task.started': {
66
- taskId: string;
67
- };
68
- 'task.completed': {
69
- taskId: string;
70
- result?: unknown | undefined;
71
- };
72
- 'task.failed': {
73
- taskId: string;
74
- error: string;
75
- };
76
- 'task.review': {
77
- taskId: string;
78
- };
79
- 'spec.analyzed': {
80
- analysis: SpecAnalysis;
81
- };
82
- progress: {
83
- percent: number;
84
- message: string;
85
- };
86
- done: {
87
- graph: TaskGraph;
88
- };
89
- error: {
90
- phase: TaskFlowPhase;
91
- error: Error;
92
- };
93
- }
94
- type TaskFlowPhase = 'idle' | 'parsing' | 'analyzing' | 'generating' | 'executing' | 'reviewing' | 'completing' | 'done' | 'failed';
95
- type TaskFlowEventName = keyof TaskFlowEventMap;
96
- interface TaskFlowOptions {
97
- tracker: TaskTracker;
98
- events: EventBus;
99
- doneCondition?: DoneCondition | undefined;
100
- maxConcurrent?: number | undefined;
101
- }
102
- interface TaskFlowExecutionContext {
103
- executeTask: (task: TaskNode) => Promise<unknown>;
104
- onTaskComplete?: (task: TaskNode | undefined, result: unknown) => void;
105
- onTaskFail?: (task: TaskNode | undefined, error: Error) => void;
106
- }
107
- declare class TaskFlow {
108
- private readonly opts;
109
- private phase;
110
- private spec;
111
- private graph;
112
- private stopped;
113
- constructor(opts: TaskFlowOptions);
114
- private emit;
115
- fromSpec(specContent: string): Promise<TaskGraph>;
116
- execute(ctx: TaskFlowExecutionContext): Promise<TaskGraph>;
117
- reviewTask(taskId: string, approved: boolean, comment?: string): Promise<void>;
118
- stop(): void;
119
- getPhase(): TaskFlowPhase;
120
- getGraph(): TaskGraph | null;
121
- getSpec(): Specification | null;
122
- private setPhase;
123
- private getExecutableTasks;
124
- private executeSingleTask;
125
- private checkDoneCondition;
126
- private emitProgress;
127
- }
128
- interface SpecDrivenDevOptions {
129
- workingDirectory: string;
130
- events: EventBus;
131
- doneCondition?: DoneCondition | undefined;
132
- }
133
- declare class SpecDrivenDev {
134
- private store;
135
- private tracker;
136
- private readonly events;
137
- private flows;
138
- constructor(opts: SpecDrivenDevOptions);
139
- createFlow(specContent: string, options?: Partial<TaskFlowOptions>): Promise<TaskFlow>;
140
- getTracker(): TaskTracker;
141
- getFlow(graphId: string): TaskFlow | undefined;
142
- listFlows(): {
143
- id: string;
144
- title: string;
145
- phase: TaskFlowPhase;
146
- }[];
147
- }
148
-
149
- interface SpecStoreOptions {
150
- /** Directory where spec files are stored. Defaults to `.wrongstack/specs`. */
151
- baseDir: string;
152
- }
153
- interface SpecIndexEntry {
154
- id: string;
155
- title: string;
156
- version: string;
157
- status: SpecStatus;
158
- updatedAt: number;
159
- filePath: string;
160
- }
161
- /**
162
- * File-backed spec storage. Each spec is a JSON file under `baseDir/`.
163
- * An index file (`_index.json`) tracks all specs for fast listing.
164
- */
165
- declare class SpecStore {
166
- private readonly baseDir;
167
- private readonly indexPath;
168
- constructor(opts: SpecStoreOptions);
169
- save(spec: Specification): Promise<void>;
170
- load(id: string): Promise<Specification | null>;
171
- list(): Promise<SpecIndexEntry[]>;
172
- delete(id: string): Promise<boolean>;
173
- exists(id: string): Promise<boolean>;
174
- /** Create a new spec with defaults, assign ID, and persist. */
175
- createDraft(title: string, overview?: string): Promise<Specification>;
176
- /** Update spec fields and persist. */
177
- update(id: string, patch: Partial<Omit<Specification, 'id' | 'createdAt'>>): Promise<Specification | null>;
178
- private filePath;
179
- private readIndex;
180
- private updateIndex;
181
- private removeFromIndex;
182
- }
183
-
184
- interface TaskGraphStoreOptions {
185
- /** Directory where task graph files are stored. Defaults to `.wrongstack/task-graphs`. */
186
- baseDir: string;
187
- }
188
- interface TaskGraphIndexEntry {
189
- id: string;
190
- specId: string;
191
- title: string;
192
- nodeCount: number;
193
- completedCount: number;
194
- updatedAt: number;
195
- filePath: string;
196
- }
197
- /**
198
- * File-backed task graph storage. Each graph is a JSON file under `baseDir/`.
199
- * An index file (`_index.json`) tracks all graphs for fast listing.
200
- */
201
- declare class TaskGraphStore {
202
- private readonly baseDir;
203
- private readonly indexPath;
204
- constructor(opts: TaskGraphStoreOptions);
205
- save(graph: TaskGraph): Promise<void>;
206
- load(id: string): Promise<TaskGraph | null>;
207
- list(): Promise<TaskGraphIndexEntry[]>;
208
- delete(id: string): Promise<boolean>;
209
- exists(id: string): Promise<boolean>;
210
- private filePath;
211
- private readIndex;
212
- private updateIndex;
213
- private removeFromIndex;
214
- }
215
-
216
- /**
217
- * SDD live board model.
218
- *
219
- * A board snapshot is the canonical, surface-agnostic projection of a running
220
- * (or persisted) SDD TaskGraph: tasks laid into topological dependency columns,
221
- * each carrying its short id, status, blockers and the agent currently on it.
222
- * The projector (sdd-board-projector.ts) emits these over the EventBus and
223
- * persists them (sdd-board-store.ts); every surface (WebUI/TUI) renders the
224
- * same shape.
225
- */
226
-
227
- type SddBoardStatus = 'idle' | 'running' | 'paused' | 'stopped' | 'completed' | 'failed' | 'deadlocked';
228
- /**
229
- * FORGE-style display status: `queued` = pending with all blockers done;
230
- * `cancelled` = a task the user stopped (stored as a terminal `failed` node
231
- * carrying `metadata.cancelled`, surfaced distinctly so it doesn't read as an
232
- * error). Display-only — not a core `TaskStatus`.
233
- */
234
- type SddTaskDisplayStatus = TaskNode['status'] | 'queued' | 'cancelled';
235
- interface SddBoardTask {
236
- id: string;
237
- /** Stable short id (t01, t02, …) in creation order. */
238
- shortId: string;
239
- title: string;
240
- description: string;
241
- status: TaskNode['status'];
242
- displayStatus: SddTaskDisplayStatus;
243
- priority: TaskNode['priority'];
244
- type: TaskNode['type'];
245
- /** Short ids of the tasks that block this one (depends_on edges). */
246
- deps: string[];
247
- /** Worker on the task right now (scientist nickname), if any. */
248
- agentName?: string | undefined;
249
- /** Git worktree branch this task runs in, when isolated. */
250
- worktreeBranch?: string | undefined;
251
- startedAt?: number | undefined;
252
- completedAt?: number | undefined;
253
- retries: number;
254
- /** Per-task model assignment (overrides the run default), if set. */
255
- model?: string | undefined;
256
- /** Per-task provider assignment (overrides the run default), if set. */
257
- provider?: string | undefined;
258
- /** Per-task fallback model chain (overrides the run default), if set. */
259
- fallbackModels?: string[] | undefined;
260
- /** Per-task completion-gate verification command, if set. */
261
- verificationCommand?: string | undefined;
262
- }
263
- /** A topological column: tasks whose deepest dependency chain is `depth`. */
264
- interface SddBoardColumn {
265
- label: string;
266
- /** Short ids of the tasks in this column (join against `tasks`). */
267
- taskIds: string[];
268
- }
269
- interface SddDeadlockChain {
270
- /** Short id of the blocked task. */
271
- blocked: string;
272
- /** Short ids of the failed/incomplete blockers holding it. */
273
- blockedBy: string[];
274
- }
275
- /** One entry in the live activity feed (the board's "what just happened" ticker). */
276
- interface SddBoardFeedEntry {
277
- ts: number;
278
- kind: 'started' | 'completed' | 'failed' | 'retrying' | 'wave' | 'deadlock' | 'verification_failed' | 'conflict' | 'split' | 'supervisor';
279
- /** Short id of the task this entry concerns, when applicable. */
280
- taskShortId?: string | undefined;
281
- /** Worker involved, when applicable. */
282
- agentName?: string | undefined;
283
- /** Human-readable one-line summary. */
284
- text: string;
285
- }
286
- interface SddBoardSnapshot {
287
- runId: string;
288
- specId?: string | undefined;
289
- graphId: string;
290
- title: string;
291
- status: SddBoardStatus;
292
- startedAt: number;
293
- updatedAt: number;
294
- progress: TaskProgress;
295
- /** Current wave index (0-based) of the parallel run. */
296
- wave: number;
297
- tasks: SddBoardTask[];
298
- columns: SddBoardColumn[];
299
- diagnostics?: {
300
- deadlockChains?: SddDeadlockChain[];
301
- } | undefined;
302
- /** Live activity feed — most recent first (capped). */
303
- feed?: SddBoardFeedEntry[] | undefined;
304
- /** Run-level default worker model (task overrides take precedence). */
305
- defaultModel?: string | undefined;
306
- /** Run-level default worker provider. */
307
- defaultProvider?: string | undefined;
308
- /** Run-level default fallback model chain. */
309
- fallbackModels?: string[] | undefined;
310
- /** Base branch the run's squash commits land on (worktree runs only). */
311
- baseBranch?: string | undefined;
312
- /**
313
- * Squash commits the run landed on the base branch, in landing order. Lets a
314
- * post-run `/sdd rollback` revert them from disk after the live run is gone.
315
- */
316
- mergedCommits?: Array<{
317
- taskId: string;
318
- sha: string;
319
- title: string;
320
- }> | undefined;
321
- }
322
- /**
323
- * Lay a TaskGraph's nodes into topological dependency columns with stable short
324
- * ids and per-task blocker refs. Shared by the projector (live) and any static
325
- * board browser. Pure; no run state — `agentName`/`worktreeBranch`/`retries`
326
- * are read from the node's `assignee`/`metadata` so a reload reflects the last
327
- * persisted run.
328
- */
329
- /**
330
- * Stable short-id map (t01, t02, …) for a graph's nodes in creation order.
331
- * Shared by the board renderer and the projector (deadlock-chain labelling).
332
- */
333
- declare function shortIdMap(graph: TaskGraph): Map<string, string>;
334
- declare function buildBoardTasks(graph: TaskGraph): {
335
- tasks: SddBoardTask[];
336
- columns: SddBoardColumn[];
337
- };
338
- /**
339
- * Build a full board snapshot from a graph + run state. The projector calls
340
- * this on every (throttled) change.
341
- */
342
- declare function buildBoardSnapshot(graph: TaskGraph, run: {
343
- runId: string;
344
- specId?: string | undefined;
345
- status: SddBoardStatus;
346
- startedAt: number;
347
- wave: number;
348
- deadlockChains?: SddDeadlockChain[] | undefined;
349
- defaultModel?: string | undefined;
350
- defaultProvider?: string | undefined;
351
- fallbackModels?: string[] | undefined;
352
- baseBranch?: string | undefined;
353
- mergedCommits?: Array<{
354
- taskId: string;
355
- sha: string;
356
- title: string;
357
- }> | undefined;
358
- }, now: number): SddBoardSnapshot;
359
-
360
- interface SddBoardStoreOptions {
361
- /** Directory for board snapshots + event logs (wpaths.projectSddBoards). */
362
- baseDir: string;
363
- }
364
- interface SddBoardIndexEntry {
365
- runId: string;
366
- specId?: string | undefined;
367
- title: string;
368
- status: string;
369
- total: number;
370
- completed: number;
371
- updatedAt: number;
372
- }
373
- /** One appended line in a board's JSONL event log. */
374
- interface SddBoardEvent {
375
- ts: number;
376
- type: string;
377
- payload?: unknown;
378
- }
379
- /**
380
- * File-backed SDD board storage. Each board (= one parallel run) has:
381
- * - `<runId>.json` — latest full snapshot (atomic; resume + standalone-webui mirror)
382
- * - `<runId>.events.jsonl`— append-only event log (audit / replay)
383
- * - `<runId>.control.jsonl` — append-only command queue (cross-process control, written by readers)
384
- * plus `_index.json` for fast listing. JSON for state, JSONL for streams.
385
- */
386
- declare class SddBoardStore {
387
- private readonly baseDir;
388
- private readonly indexPath;
389
- constructor(opts: SddBoardStoreOptions);
390
- snapshotPath(runId: string): string;
391
- eventsPath(runId: string): string;
392
- controlPath(runId: string): string;
393
- saveSnapshot(snapshot: SddBoardSnapshot): Promise<void>;
394
- load(runId: string): Promise<SddBoardSnapshot | null>;
395
- list(): Promise<SddBoardIndexEntry[]>;
396
- loadLatestForSpec(specId: string): Promise<SddBoardSnapshot | null>;
397
- /** Append one line to the board's JSONL event log (best-effort, never throws). */
398
- appendEvent(runId: string, event: SddBoardEvent): Promise<void>;
399
- /** Append a control command (used by readers to steer a CLI-owned run). */
400
- appendControl(runId: string, command: {
401
- ts: number;
402
- type: string;
403
- payload?: unknown;
404
- }): Promise<void>;
405
- /** Read + truncate the control queue (the run drains it). Returns parsed commands. */
406
- drainControl(runId: string): Promise<Array<{
407
- ts: number;
408
- type: string;
409
- payload?: unknown;
410
- }>>;
411
- delete(runId: string): Promise<void>;
412
- private safe;
413
- private readIndex;
414
- private updateIndex;
415
- private removeFromIndex;
416
- }
417
-
418
- interface SddBoardProjectorOptions {
419
- runId: string;
420
- graph: TaskGraph;
421
- tracker: TaskTracker;
422
- events: EventBus;
423
- /** Parent session id for emitted `sdd.board.snapshot` events. */
424
- sessionId?: string | (() => string | undefined) | undefined;
425
- /** Persist snapshots + JSONL events (optional — omit for in-memory only). */
426
- store?: SddBoardStore | undefined;
427
- specId?: string | undefined;
428
- /** Run-level default worker model/provider/fallbacks (shown in the board header). */
429
- defaultModel?: string | undefined;
430
- defaultProvider?: string | undefined;
431
- fallbackModels?: string[] | undefined;
432
- /** Base branch the run's squash commits land on (for the board + rollback). */
433
- baseBranch?: string | undefined;
434
- /** Snapshot coalescing window in ms (default 250). */
435
- throttleMs?: number | undefined;
436
- /** Clock injection for tests; defaults to Date.now. */
437
- now?: (() => number) | undefined;
438
- }
439
- declare class SddBoardProjector {
440
- private readonly o;
441
- private readonly now;
442
- private readonly throttleMs;
443
- private readonly shortId;
444
- private status;
445
- private wave;
446
- private startedAt;
447
- private deadlockChains;
448
- /** Live activity feed, most recent first (capped). */
449
- private feed;
450
- private static readonly FEED_CAP;
451
- private finished;
452
- private runDeadlocked;
453
- private runStopped;
454
- /** Squash commits the run landed on the base branch (for post-run rollback). */
455
- private mergedCommits;
456
- /** Base branch reported by the run at start (overrides the constructor option). */
457
- private runBaseBranch;
458
- private dirty;
459
- private timer;
460
- private readonly unsubs;
461
- /** Tail of in-flight persistence, so callers can await a settled state. */
462
- private lastSave;
463
- constructor(opts: SddBoardProjectorOptions);
464
- private pushFeed;
465
- /** ` (title…)` suffix for a feed line, or '' when the node/title is missing. */
466
- private titleOf;
467
- private assigneeOf;
468
- /** Latest snapshot, built on demand (e.g. for a late-joining client). */
469
- snapshot(): SddBoardSnapshot;
470
- /** Resolve once all in-flight snapshot persistence has settled. */
471
- drain(): Promise<void>;
472
- /** Stop projecting and release subscriptions. */
473
- dispose(): void;
474
- /** Subscribe to a run event scoped to this run id; also append to JSONL. */
475
- private onRun;
476
- private resolveStatus;
477
- private build;
478
- private markDirty;
479
- private flush;
480
- private currentSessionId;
481
- }
482
-
483
- /**
484
- * SddTaskDecomposer
485
- *
486
- * Converts a TaskGraph (from SDD's TaskGenerator) into a dependency-aware
487
- * sequence of batches for ParallelEternalEngine.
488
- *
489
- * Key behaviour:
490
- * - Each `nextBatch()` call returns up to `parallelSlots` ready tasks
491
- * (all blockers completed, sorted by priority).
492
- * - Tasks that are blocked by an in-progress task are NOT included
493
- * in the batch — they wait for the blocker to complete.
494
- * - When `isDone()` returns true the whole graph is either completed
495
- * or deadlocked (all remaining tasks are blocked by failed tasks).
496
- *
497
- * Usage:
498
- * ```
499
- * const decomposer = new SddTaskDecomposer(tracker, graph, { parallelSlots: 4 });
500
- * while (!decomposer.isDone()) {
501
- * const batch = decomposer.nextBatch();
502
- * if (batch.length === 0) break; // deadlock
503
- * await fanOut(batch);
504
- * decomposer.acknowledgeBatch(batch.map(t => t.id));
505
- * }
506
- * ```
507
- */
508
-
509
- interface SddTaskDecomposerOptions {
510
- /** Max tasks per batch. Default: 4. Range 1–16. */
511
- parallelSlots?: number | undefined;
512
- }
513
- interface TaskBatch {
514
- /** Tasks ready to execute in this wave. */
515
- tasks: TaskNode[];
516
- /** 0-based wave number since the decomposer was constructed. */
517
- wave: number;
518
- /** True when every node in the graph is either completed or failed. */
519
- allDone: boolean;
520
- /** True when no batch was produced because remaining tasks are all blocked by failed nodes. */
521
- deadlocked: boolean;
522
- }
523
- declare class SddTaskDecomposer {
524
- private readonly tracker;
525
- private readonly slots;
526
- private wave;
527
- constructor(tracker: TaskTracker, _graph: TaskGraph, opts?: SddTaskDecomposerOptions);
528
- /**
529
- * Return the next batch of runnable tasks.
530
- * Returns `allDone: true` when every node is completed.
531
- * Returns `deadlocked: true` when no batch can be produced because
532
- * all remaining tasks are blocked by failed nodes.
533
- */
534
- nextBatch(): TaskBatch;
535
- /**
536
- * Advance the wave counter after a batch completes.
537
- * Call this once per `nextBatch()` result that was fan-out.
538
- */
539
- acknowledgeBatch(_completedTaskIds: string[]): void;
540
- /**
541
- * True when every node in the graph is completed.
542
- * Use this to exit the fan-out loop after `isDone() || deadlocked`.
543
- */
544
- isDone(): boolean;
545
- /**
546
- * Total waves produced so far.
547
- */
548
- getWaveCount(): number;
549
- /**
550
- * All ready (dependency-satisfied) pending tasks, priority-sorted — UNSLICED.
551
- * The continuous scheduler fills its own free slots from this list, so unlike
552
- * `nextBatch()` it does not cap at `slots`.
553
- */
554
- readyNodes(): TaskNode[];
555
- /**
556
- * True when every node has reached a terminal state (completed or failed).
557
- * This — not `isDone()` (which requires ALL completed) — is the correct loop
558
- * exit for the continuous scheduler: a terminally-failed task must not keep
559
- * the run spinning to its backstop.
560
- */
561
- isSettled(): boolean;
562
- /**
563
- * Return pending nodes whose blockers are all completed.
564
- * Sorted by priority (critical first), then by creation time.
565
- */
566
- private pendingReadyNodes;
567
- /** True when at least one non-completed, non-failed task is blocked. */
568
- private hasAnyBlockedTasks;
569
- }
570
-
571
- /** A sub-task produced by splitting a parent task (see `splitTask`). */
572
- interface SddSubtaskSpec {
573
- title: string;
574
- description: string;
575
- type?: TaskNode['type'] | undefined;
576
- priority?: TaskNode['priority'] | undefined;
577
- }
578
- /**
579
- * Verdict returned by the optional failure supervisor when a task is about to go
580
- * terminal. `retry` re-queues with a fresh attempt budget; `reassign` swaps the
581
- * worker model (+ optional provider) then re-queues; `split` breaks the task
582
- * into sub-tasks; `fail` (or `undefined`) lets it terminal-fail.
583
- */
584
- type SddSupervisorVerdict = {
585
- action: 'retry';
586
- } | {
587
- action: 'reassign';
588
- model?: string | undefined;
589
- provider?: string | undefined;
590
- } | {
591
- action: 'split';
592
- subtasks: SddSubtaskSpec[];
593
- } | {
594
- action: 'fail';
595
- };
596
- interface SddParallelRunOptions {
597
- /** Pre-constructed TaskTracker (must already hold the graph's initial state). */
598
- tracker: TaskTracker;
599
- /** The TaskGraph produced by TaskGenerator from an approved spec. */
600
- graph: TaskGraph;
601
- /** The main agent — used as the subagent factory. */
602
- agent: Agent;
603
- /** Project root (used for coordinator id). */
604
- projectRoot: string;
605
- /**
606
- * Override default parallel slots (1–16). Default: 2 — deliberately low so a
607
- * run never juggles more git worktrees than a human can review. Independent
608
- * tasks still run concurrently up to this cap; dependency chains run in order.
609
- */
610
- parallelSlots?: number | undefined;
611
- /**
612
- * Hard wall-clock cap per task in ms. OPT-IN — `undefined` by default so a
613
- * long-but-productive task is never killed merely for running long (the old
614
- * 5-min default hard-killed real coding tasks with `budget_timeout`). When
615
- * set, the coordinator watchdog enforces it. Prefer `taskIdleTimeoutMs`.
616
- */
617
- taskTimeoutMs?: number | undefined;
618
- /**
619
- * Idle reaper per task in ms: reap a task only after this long with NO
620
- * activity (iteration / tool call / streamed token / tool progress). Resets
621
- * on every sign of forward motion, so an actively-working agent runs until
622
- * its task naturally ends. Default: 600_000 (10 min of silence = genuinely
623
- * stuck). This is the default guard — wall-clock (`taskTimeoutMs`) is opt-in.
624
- */
625
- taskIdleTimeoutMs?: number | undefined;
626
- /** Maximum in-run retry attempts for a failed task before it goes terminal. Default: 3. */
627
- maxRetries?: number | undefined;
628
- /**
629
- * After the graph settles with terminal-failed tasks, requeue ALL failed
630
- * (non-cancelled) tasks to `pending` and run them again — up to this many
631
- * sweeps. Each sweep gives every failed task a fresh `maxRetries` budget. The
632
- * loop stops early once a sweep produces no new completions (no progress).
633
- * 0 = off. Default: 2.
634
- */
635
- maxFailedRetrySweeps?: number | undefined;
636
- /** Override the default agent factory. */
637
- subagentFactory?: AgentFactory | undefined;
638
- /**
639
- * Run-level default model for worker subagents. A task's own
640
- * `metadata.model` (set per-task in the WebUI) takes precedence; this is the
641
- * fallback for every task that has no explicit assignment. Undefined → the
642
- * factory's own default (the leader's model).
643
- */
644
- defaultModel?: string | undefined;
645
- /** Run-level default provider id (same precedence rules as defaultModel). */
646
- defaultProvider?: string | undefined;
647
- /**
648
- * Run-level fallback model chain (entries: `model` / `provider/model`). A
649
- * task's `metadata.fallbackModels` overrides this. The subagent factory wires
650
- * these into a fallback extension so a 429/stream-hang rotates to the next.
651
- */
652
- fallbackModels?: string[] | undefined;
653
- /**
654
- * Post-task verification gate. When set, a task whose worker reported success
655
- * is NOT marked `completed` (and NOT merged) until this resolves `{ok:true}`.
656
- * Runs in the task's worktree cwd (or the project root when no worktree). Core
657
- * stays shell-agnostic — the caller injects a verifier that, e.g., runs the
658
- * task's `metadata.verificationCommand` (tests / typecheck). A task with no
659
- * command should return `{ok:true}`. An `{ok:false}` routes the task into the
660
- * normal failure path (retry while attempts remain, else terminal-fail).
661
- */
662
- verifyTask?: ((info: {
663
- task: TaskNode;
664
- result: TaskResult;
665
- cwd: string;
666
- }) => Promise<{
667
- ok: boolean;
668
- reason?: string;
669
- }>) | undefined;
670
- /**
671
- * Optional merge-conflict resolver, forwarded to `WorktreeManager.merge`. Given
672
- * the conflicted files + the base checkout cwd, return `true` once resolved (no
673
- * markers left). When omitted or it returns `false`, the task is requeued (a
674
- * re-run forks a fresh worktree off the advanced base) and, if retries are
675
- * exhausted, terminally failed with its worktree kept for review.
676
- */
677
- conflictResolver?: ((info: {
678
- task: TaskNode;
679
- conflictFiles: string[];
680
- cwd: string;
681
- }) => Promise<boolean>) | undefined;
682
- /**
683
- * Failure supervisor: consulted ONLY when a task has exhausted its retries and
684
- * is about to go terminal-failed. Returning a verdict lets a decision agent
685
- * keep the run moving — `retry` / `reassign` (swap model) / `split` — instead
686
- * of dead-ending. Returning `{action:'fail'}` / `undefined` lets it fail. Each
687
- * task can be rescued at most `maxSupervisorEscalations` times (loop guard).
688
- */
689
- superviseFailure?: ((info: {
690
- task: TaskNode;
691
- error: string;
692
- attempts: number;
693
- }) => Promise<SddSupervisorVerdict | undefined>) | undefined;
694
- /** Max times the supervisor may rescue a single task before it must fail. Default 2. */
695
- maxSupervisorEscalations?: number | undefined;
696
- /** Called after each wave completes. */
697
- onWave?: ((wave: WaveResult) => void) | undefined;
698
- /** Called with progress stats every ~2s during execution. */
699
- onProgress?: ((progress: SddProgress) => void) | undefined;
700
- /** Shared EventBus — when set, the run emits `sdd.*` live-board events. */
701
- events?: EventBus | undefined;
702
- /** Parent session id for every emitted `sdd.*` event. */
703
- sessionId?: string | (() => string | undefined) | undefined;
704
- /** Stable id correlating all events of this run (default: random). */
705
- runId?: string | undefined;
706
- /**
707
- * Optional git-worktree manager. When set (and the project is a git repo),
708
- * each task runs in its own isolated worktree and merges back into the base
709
- * branch after success — so parallel agents never collide on the same files.
710
- */
711
- worktrees?: WorktreeManager | undefined;
712
- /** Run-level backstops (prevent an autonomous run from looping forever). */
713
- maxTotalWaves?: number | undefined;
714
- maxWallClockMs?: number | undefined;
715
- /**
716
- * Deadlock auto-recovery rounds: when the graph deadlocks on failed blockers,
717
- * requeue those failed blockers `pending` and try again, up to N times. 0 = off.
718
- */
719
- maxRecoveryRounds?: number | undefined;
720
- }
721
- interface SddProgress {
722
- wave: number;
723
- total: number;
724
- completed: number;
725
- inProgress: number;
726
- failed: number;
727
- blocked: number;
728
- pending: number;
729
- percent: number;
730
- deadlocked: boolean;
731
- }
732
- interface WaveResult {
733
- wave: number;
734
- batch: TaskBatch;
735
- results: TaskResult[];
736
- successCount: number;
737
- failCount: number;
738
- durationMs: number;
739
- stopRequested: boolean;
740
- }
741
- /** Result of a single task's execution in the continuous scheduler. */
742
- interface TaskOutcome {
743
- taskId: string;
744
- success: boolean;
745
- result?: TaskResult | undefined;
746
- }
747
- interface RunResult {
748
- totalWaves: number;
749
- totalCompleted: number;
750
- totalFailed: number;
751
- totalDurationMs: number;
752
- deadlocked: boolean;
753
- stopRequested: boolean;
754
- finalProgress: TaskProgress;
755
- }
756
- declare class SddParallelRun {
757
- private readonly opts;
758
- private readonly slots;
759
- /** Opt-in hard wall-clock cap (undefined → no cap; idle reaper guards instead). */
760
- private readonly timeoutMs;
761
- /** Idle reaper window (ms) — resets on activity; reaps only a genuine stall. */
762
- private readonly idleTimeoutMs;
763
- private readonly maxRetries;
764
- /** Max supervisor rescues per task before it must terminal-fail (loop guard). */
765
- private readonly maxSupervisorEscalations;
766
- /** Per-task count of supervisor rescues used (resets nothing — bounds the loop). */
767
- private supervisorEscalations;
768
- /** Max end-of-run failed-task sweeps (see `maxFailedRetrySweeps`). */
769
- private readonly maxFailedSweeps;
770
- /** How many failed-task sweeps have run this `run()` so far. */
771
- private failedSweeps;
772
- /** Completed-count snapshot at the last sweep, to detect a no-progress sweep. */
773
- private lastSweepCompleted;
774
- private decomposer;
775
- private coordinator;
776
- private stopRequested;
777
- private retryMap;
778
- readonly runId: string;
779
- private readonly events?;
780
- private readonly sessionIdSource;
781
- private readonly maxTotalWaves;
782
- private readonly maxWallClockMs?;
783
- private readonly maxRecoveryRounds;
784
- private recoveryRounds;
785
- /** Per-run worker identities, so the board shows "who is on what". */
786
- private usedNicknames;
787
- /** Per-task git worktree cwd (Layer 2 worktree isolation; empty otherwise). */
788
- private taskCwds;
789
- /** Per-task git worktree branch, for board display. */
790
- private taskBranches;
791
- /** Live worktree handles keyed by task id (for commit/merge/release). */
792
- private taskWorktrees;
793
- /** Live subagent id per running task — lets cancelTask() abort exactly one. */
794
- private taskSubagents;
795
- /** Tasks the user cancelled mid-flight — skip retry, mark terminal-cancelled. */
796
- private cancelledTasks;
797
- /**
798
- * Base branch the run's squash commits land on (captured once at start when
799
- * worktrees are enabled). Anchors a later `rollback()`.
800
- */
801
- private baseBranch;
802
- /**
803
- * Squash-merge commits this run landed on the base branch, in landing order.
804
- * `rollback()` reverts these (newest → oldest). Persisted via the board
805
- * snapshot so a post-run rollback can read them off disk.
806
- */
807
- private mergedCommits;
808
- /** Monotonic dispatch counter (unique subagent ids) + dispatch-round counter. */
809
- private dispatchSeq;
810
- private round;
811
- constructor(opts: SddParallelRunOptions);
812
- /** Type-safe emit on the optional EventBus (no-op when unwired). */
813
- private emit;
814
- private currentSessionId;
815
- private paused;
816
- /** Trigger stop — causes run() to abort after the current wave. */
817
- stop(): void;
818
- /** Pause: no new wave starts until resume() (the current wave finishes). */
819
- pause(): void;
820
- resume(): void;
821
- isPaused(): boolean;
822
- isRunning(): boolean;
823
- /** Base branch the run's squash commits land on (undefined when worktrees off). */
824
- getBaseBranch(): string | undefined;
825
- /** Squash commits this run landed on the base branch, in landing order. */
826
- getMergedCommits(): ReadonlyArray<{
827
- taskId: string;
828
- sha: string;
829
- title: string;
830
- }>;
831
- /**
832
- * Remove every git worktree + branch this run (and any prior run) created.
833
- * Refuses while the run is still live — cleaning a checkout under an active
834
- * worker would corrupt it. Stop first. Returns the number of worktrees removed
835
- * (0 when worktrees are disabled). Idempotent.
836
- */
837
- cleanupWorktrees(): Promise<number>;
838
- /**
839
- * Undo the run's merged commits by reverting each on the base branch (history
840
- * preserving). Refuses while the run is still live (stop first). Returns the
841
- * revert outcome; a dirty tree or revert conflict surfaces as `ok:false`.
842
- */
843
- rollback(): Promise<{
844
- ok: boolean;
845
- reverted: number;
846
- reason?: string;
847
- }>;
848
- /** Requeue a task to `pending` so the scheduler re-runs it (clears retries + cancel marker). */
849
- retryTask(taskId: string): boolean;
850
- /** Reassign a task to a specific agent name (reflected on the board). */
851
- reassignTask(taskId: string, agentName: string): boolean;
852
- /**
853
- * Set/override a task's worker model (and optionally provider) — applied on its
854
- * NEXT dispatch (a running task must be cancelled + retried to take effect). The
855
- * assignment lives on node metadata so it survives crash → resume.
856
- */
857
- setTaskModel(taskId: string, model: string | undefined, provider?: string | undefined): boolean;
858
- /** Set/override a task's fallback model chain (applied on its next dispatch). */
859
- setTaskFallbacks(taskId: string, fallbackModels: string[] | undefined): boolean;
860
- /**
861
- * Set/override a task's verification command (the completion gate runs it in
862
- * the task's cwd and only lets the task complete on exit 0). Empty/undefined
863
- * clears it. Applied on the task's next verification — i.e. its next dispatch.
864
- */
865
- setTaskVerification(taskId: string, verificationCommand: string | undefined): boolean;
866
- /**
867
- * Cancel a task. If it is currently running, abort its subagent and mark the
868
- * node terminally failed+cancelled (so the scheduler frees the slot and does
869
- * NOT retry it). If it has not started, it is simply marked cancelled. Use
870
- * `retryTask` to bring a cancelled task back. Returns false for an unknown task.
871
- */
872
- cancelTask(taskId: string): Promise<boolean>;
873
- /**
874
- * Delete a not-yet-started task from the graph (pending/blocked/failed only —
875
- * never a running task; cancel it first). Removes the node and every edge
876
- * touching it; dependents lose this blocker. Returns false if missing or running.
877
- */
878
- deleteTask(taskId: string): boolean;
879
- /**
880
- * Split a task into sub-tasks and delegate them to separate workers. The new
881
- * leaves inherit the parent's blockers (so they don't start before the
882
- * parent's dependencies are met), every existing dependent is rewired to
883
- * depend on ALL leaves (so downstream work waits for the whole split), and the
884
- * parent becomes a `completed` container. Refuses a running task (cancel it
885
- * first) or empty subtask list. Returns the new leaf ids (empty on refusal).
886
- * The scheduler picks the new pending leaves up on its next dispatch pass.
887
- */
888
- splitTask(taskId: string, subtasks: SddSubtaskSpec[]): string[];
889
- private waitWhilePaused;
890
- /**
891
- * Continuous dependency-driven execution. Unlike a wave-barrier loop (where a
892
- * whole batch must finish before the next starts), this fills free worker
893
- * slots the instant a task's dependencies are satisfied: a fast task's
894
- * dependent starts immediately rather than waiting for a slow sibling. Truly
895
- * independent tasks run in parallel; dependency chains run in order. Returns
896
- * the final summary when the graph settles, deadlocks, stops, or hits a backstop.
897
- */
898
- run(): Promise<RunResult>;
899
- /**
900
- * Compute the blocking chains for a deadlock: every still-incomplete task and
901
- * the blockers (by node id) that are NOT completed. Failed blockers are
902
- * included since they're the usual deadlock cause once retries are exhausted.
903
- */
904
- private computeDeadlockChains;
905
- /** Requeue failed tasks that block an incomplete dependent. Returns true if any. */
906
- private recoverFailedBlockers;
907
- /**
908
- * Requeue every terminal-failed task that the user did NOT cancel, giving each
909
- * a fresh `maxRetries` budget. Shared by the automatic end-of-run sweep and
910
- * the manual "retry all failed" control. Returns the number requeued.
911
- */
912
- private requeueFailedTasks;
913
- /**
914
- * Manually requeue all failed tasks to `pending` (board "Retry all failed").
915
- * Unlike the automatic sweep this also clears any `cancelled` marker, so a
916
- * user can bring cancelled tasks back in the same action — mirroring
917
- * `retryTask`. Picked up by the running scheduler on its next dispatch pass.
918
- * Returns the number of tasks requeued.
919
- */
920
- retryAllFailed(): number;
921
- /** Restore per-task retry counts persisted in node metadata (resume support). */
922
- private restoreRetryMap;
923
- /**
924
- * Reset orphaned `in_progress` tasks (no agent runs them after a crash) back
925
- * to `pending` so a fresh run re-executes them. Call before constructing a run
926
- * from a reloaded graph. Static so callers don't need a run instance.
927
- */
928
- static resetOrphans(tracker: TaskTracker): number;
929
- /** Clean teardown after a stop: reset interrupted tasks + release worktrees. */
930
- private teardown;
931
- private buildCoordinator;
932
- private defaultFactory;
933
- /**
934
- * Execute a batch of tasks together. Retained as a thin wrapper over the
935
- * single-task primitive `executeOne` so the wave-oriented tests and any
936
- * batch callers keep working; the continuous scheduler in `run()` calls
937
- * `executeOne` directly. Throws if no coordinator is wired or a spawn fails
938
- * (surfaced from `executeOne`), preserving the original all-or-nothing contract.
939
- */
940
- executeWave(batch: TaskBatch): Promise<WaveResult>;
941
- /**
942
- * Execute one task end-to-end: assign a worker identity, allocate its worktree,
943
- * spawn + assign the subagent, await its result, then update tracker status
944
- * (success / retry / terminal-fail / cancelled) and resolve the worktree. This
945
- * is the unit the continuous scheduler dispatches into a free slot. Throws on a
946
- * missing coordinator or failed spawn so callers can enforce all-or-nothing.
947
- */
948
- executeOne(task: TaskNode): Promise<TaskOutcome>;
949
- /**
950
- * Apply a task failure: retry (→ pending, bump retry count) while attempts
951
- * remain, else consult the optional supervisor (which can rescue via
952
- * retry/reassign/split), else terminal-fail (→ failed). Shared by the
953
- * worker-failure, verification-gate, and merge-conflict paths so all three
954
- * negotiate the same retry budget and emit the same events.
955
- */
956
- private applyTaskFailure;
957
- /**
958
- * Consult `superviseFailure` for a task that has exhausted its retries.
959
- * Applies the verdict (retry / reassign+retry / split) and returns true when
960
- * the task was rescued (caller must NOT terminal-fail it). Bounded per task by
961
- * `maxSupervisorEscalations` so an always-"retry" supervisor can't loop forever.
962
- */
963
- private trySupervisorRescue;
964
- /**
965
- * Integrate a verified-successful task's worktree into the base branch.
966
- * Commits, squash-merges (optionally running `conflictResolver` first), and on
967
- * success releases the worktree. On an UNRESOLVED conflict it returns
968
- * `{ok:false}` with the conflicting files so the caller routes the task into
969
- * the failure path (a retry forks a fresh worktree off the now-advanced base,
970
- * which usually clears the conflict). No-op `{ok:true}` when worktrees are
971
- * disabled or none was allocated for this task. Never throws — a merge hiccup
972
- * degrades to a (retryable) failure rather than wedging the run.
973
- */
974
- private integrateWorktree;
975
- /** Allocate a fresh git worktree per task in the batch (no-op without a manager). */
976
- private allocateWorktrees;
977
- /**
978
- * Resolve each task's worktree after its result is known. Serialized merges
979
- * (one at a time) keep the base branch consistent; the wave structure already
980
- * guarantees dependency order (a task's blockers merged in an earlier wave).
981
- */
982
- private resolveWorktrees;
983
- private forgetWorktree;
984
- /** Persist a task's retry count into node metadata (survives crash → resume). */
985
- private persistRetries;
986
- private buildProgress;
987
- }
988
-
989
- /**
990
- * Control surface over a live SDD run, exposed to every steering surface
991
- * (TUI, CLI-hosted WebUI in-process; standalone WebUI via a control file the
992
- * run drains). The run itself stays CLI-owned — this is the only sanctioned
993
- * way to pause / retry / reassign from outside the run loop.
994
- */
995
- interface SddRunControl {
996
- runId: string;
997
- specId?: string | undefined;
998
- pause(): void;
999
- resume(): void;
1000
- stop(): void;
1001
- retryTask(taskId: string): boolean;
1002
- /** Requeue every failed task to pending (board "Retry all failed"). Returns the count. */
1003
- retryAllFailed(): number;
1004
- reassignTask(taskId: string, agentName: string): boolean;
1005
- /** Set/override a task's worker model (+ optional provider). Next dispatch. */
1006
- setTaskModel(taskId: string, model: string | undefined, provider?: string | undefined): boolean;
1007
- /** Set/override a task's fallback model chain. Next dispatch. */
1008
- setTaskFallbacks(taskId: string, fallbackModels: string[] | undefined): boolean;
1009
- /** Set/override a task's completion-gate verification command. Next dispatch. */
1010
- setTaskVerification(taskId: string, verificationCommand: string | undefined): boolean;
1011
- /** Cancel a task — abort it if running, else mark it cancelled. */
1012
- cancelTask(taskId: string): Promise<boolean> | boolean;
1013
- /** Delete a not-started task from the graph (refused while running). */
1014
- deleteTask(taskId: string): boolean;
1015
- /** Split a task into sub-tasks (refused while running). Returns the new leaf ids. */
1016
- splitTask(taskId: string, subtasks: SddSubtaskSpec[]): string[];
1017
- /**
1018
- * Remove every git worktree + branch the run created (refused while running —
1019
- * stop first). Returns the number removed.
1020
- */
1021
- cleanupWorktrees(): Promise<number>;
1022
- /**
1023
- * Undo the run's merged commits by reverting each on the base branch (refused
1024
- * while running). History-preserving; refuses on a dirty tree / revert conflict.
1025
- */
1026
- rollback(): Promise<{
1027
- ok: boolean;
1028
- reverted: number;
1029
- reason?: string;
1030
- }>;
1031
- /** Base branch the run's squash commits land on (worktree runs only). */
1032
- getBaseBranch(): string | undefined;
1033
- /** Squash commits the run landed on the base branch, in landing order. */
1034
- getMergedCommits(): ReadonlyArray<{
1035
- taskId: string;
1036
- sha: string;
1037
- title: string;
1038
- }>;
1039
- /** Latest board snapshot (built on demand). */
1040
- snapshot(): SddBoardSnapshot;
1041
- isRunning(): boolean;
1042
- }
1043
- /**
1044
- * In-process registry of the active SDD run. One run is active at a time (a
1045
- * single fleet drives it); a new run replaces the previous. Lives in the CLI
1046
- * process where the fleet runs.
1047
- */
1048
- declare class SddRunRegistry {
1049
- private current;
1050
- register(control: SddRunControl): void;
1051
- clear(runId: string): void;
1052
- getActive(): SddRunControl | null;
1053
- }
1054
-
1055
- type AISpecPhase = 'questioning' | 'spec_review' | 'implementation' | 'task_review' | 'executing' | 'done';
1056
- interface CollectedAnswer {
1057
- question: string;
1058
- answer: string;
1059
- timestamp: number;
1060
- }
1061
- interface AISpecSession {
1062
- id: string;
1063
- phase: AISpecPhase;
1064
- title: string;
1065
- userIntent: string;
1066
- projectContext: string;
1067
- answers: CollectedAnswer[];
1068
- questionCount: number;
1069
- spec?: Specification | undefined;
1070
- implementation?: string | undefined;
1071
- taskGraphId?: string | undefined;
1072
- approved: boolean;
1073
- createdAt: number;
1074
- updatedAt: number;
1075
- }
1076
- interface AISpecBuilderOptions {
1077
- store: SpecStore;
1078
- /** Minimum questions the AI should ask. Default: 2 */
1079
- minQuestions?: number | undefined;
1080
- /** Maximum questions before forcing spec generation. Default: 10 */
1081
- maxQuestions?: number | undefined;
1082
- /** Project context string (package.json, file structure, etc.) */
1083
- projectContext?: string | undefined;
1084
- /** Path to persist session state. If set, session survives process restarts. */
1085
- sessionPath?: string | undefined;
1086
- }
1087
- /**
1088
- * AI-driven specification builder. Instead of static questions, this builder
1089
- * tracks conversation state and generates prompts that instruct the AI agent
1090
- * to ask contextual questions and build specifications interactively.
1091
- */
1092
- declare class AISpecBuilder {
1093
- private session;
1094
- private readonly store;
1095
- private readonly minQuestions;
1096
- private readonly maxQuestions;
1097
- private readonly sessionPath?;
1098
- constructor(opts: AISpecBuilderOptions);
1099
- /** Save session state to disk. */
1100
- saveSession(): Promise<void>;
1101
- /** Load session state from disk. Returns true if a session was loaded. */
1102
- loadSession(): Promise<boolean>;
1103
- /** Delete saved session from disk. */
1104
- deleteSession(): Promise<void>;
1105
- /** Auto-save helper — calls saveSession() but never throws.
1106
- * Failures are surfaced via process.emitWarning so a persistent
1107
- * ENOSPC / EACCES doesn't silently strand session edits in memory. */
1108
- private autoSave;
1109
- /** Start a new session with a title and optional intent. */
1110
- startSession(title: string, intent?: string): void;
1111
- /** Get current session state (readonly). */
1112
- getSession(): Readonly<AISpecSession>;
1113
- /** Get the current phase. */
1114
- getPhase(): AISpecPhase;
1115
- /**
1116
- * Get the AI prompt for the current phase.
1117
- * This prompt is injected into the conversation so the AI agent knows
1118
- * what to do next (ask a question, generate a spec, etc.).
1119
- */
1120
- getAIPrompt(): string;
1121
- /**
1122
- * Record a question/answer pair from the AI conversation.
1123
- * Call this when the AI asks a question and the user responds.
1124
- */
1125
- addAnswer(question: string, answer: string): void;
1126
- /**
1127
- * Check if more questions should be asked.
1128
- * Returns false if max reached or if the AI has signaled it has enough info.
1129
- */
1130
- shouldContinueQuestioning(): boolean;
1131
- /**
1132
- * Check if minimum questions have been asked.
1133
- */
1134
- hasMetMinimumQuestions(): boolean;
1135
- /**
1136
- * Set the generated specification and move to spec_review phase.
1137
- */
1138
- setSpec(spec: Specification): void;
1139
- /**
1140
- * Approve the current phase and advance to the next.
1141
- * questioning → spec_review (requires spec to be set)
1142
- * spec_review → implementation
1143
- * implementation → task_review (requires implementation to be set)
1144
- * task_review → executing
1145
- * executing → done
1146
- */
1147
- approve(): AISpecPhase;
1148
- /**
1149
- * Set the implementation plan text.
1150
- */
1151
- setImplementation(plan: string): void;
1152
- /**
1153
- * Mark session as done.
1154
- */
1155
- markDone(): void;
1156
- /**
1157
- * Set the task graph ID for this session.
1158
- */
1159
- setTaskGraphId(graphId: string): void;
1160
- /**
1161
- * Get the task graph ID for this session.
1162
- */
1163
- getTaskGraphId(): string | undefined;
1164
- /**
1165
- * Save the current spec to the store.
1166
- */
1167
- saveSpec(): Promise<Specification>;
1168
- /**
1169
- * Parse a spec from a JSON string (from AI output).
1170
- * Validates and normalizes the structure.
1171
- */
1172
- parseSpecFromJSON(jsonStr: string): Specification;
1173
- /**
1174
- * Extract JSON from AI output (handles ```json blocks and raw JSON).
1175
- */
1176
- extractJSON(text: string): string | null;
1177
- /**
1178
- * Detect if AI output contains a spec (JSON block).
1179
- */
1180
- hasSpecInOutput(text: string): boolean;
1181
- /**
1182
- * Try to parse a spec from AI output text.
1183
- * Returns null if no valid spec found.
1184
- */
1185
- tryParseSpecFromOutput(text: string): Specification | null;
1186
- /**
1187
- * Extract a JSON array from AI output (for task lists).
1188
- */
1189
- extractJSONArray(text: string): string | null;
1190
- }
1191
-
1192
- interface SddInterviewDriverOptions {
1193
- /** Disk-backed spec store (`wpaths.projectSpecs`). */
1194
- specStore: SpecStore;
1195
- /** Disk-backed task-graph store (`wpaths.projectTaskGraphs`). */
1196
- graphStore: TaskGraphStore;
1197
- /** Persist the interview session here so a reconnect can resume it. */
1198
- sessionPath?: string | undefined;
1199
- /** Project context string injected into the questioning prompt. */
1200
- projectContext?: string | undefined;
1201
- minQuestions?: number | undefined;
1202
- maxQuestions?: number | undefined;
1203
- }
1204
- /** A serialisable view of the interview, streamed to observing surfaces. */
1205
- interface SddInterviewSnapshot {
1206
- sessionId: string;
1207
- phase: AISpecPhase;
1208
- title: string;
1209
- /** The operator's original goal prompt (verbatim). `title` is a short heading. */
1210
- goal: string;
1211
- questionCount: number;
1212
- minQuestions: number;
1213
- maxQuestions: number;
1214
- answers: Array<{
1215
- question: string;
1216
- answer: string;
1217
- }>;
1218
- spec?: {
1219
- id: string;
1220
- title: string;
1221
- overview: string;
1222
- requirements: Array<{
1223
- priority: string;
1224
- description: string;
1225
- }>;
1226
- } | undefined;
1227
- graphId?: string | undefined;
1228
- taskCount: number;
1229
- /**
1230
- * Topologically-laid-out task graph (once decomposed) — lets the wizard
1231
- * render the same animated DAG as the live board ("decomposition reveal").
1232
- */
1233
- board?: {
1234
- tasks: SddBoardTask[];
1235
- columns: SddBoardColumn[];
1236
- } | undefined;
1237
- /** The current AI prompt for this phase (what to send the agent next). */
1238
- prompt: string;
1239
- }
1240
- /** What `ingestAgentOutput` detected and acted on. */
1241
- interface SddIngestResult {
1242
- specDetected: boolean;
1243
- implementationDetected: boolean;
1244
- tasksDetected: boolean;
1245
- graphId?: string | undefined;
1246
- }
1247
- declare class SddInterviewDriver {
1248
- readonly builder: AISpecBuilder;
1249
- private readonly o;
1250
- private readonly minQuestions;
1251
- private readonly maxQuestions;
1252
- private tracker;
1253
- private graph;
1254
- constructor(opts: SddInterviewDriverOptions);
1255
- /** Begin a fresh interview. Returns the first AI prompt (a question kickoff). */
1256
- start(title: string, intent?: string): string;
1257
- /**
1258
- * Resume a previously-persisted interview from disk. Re-hydrates the task
1259
- * graph too when one was already produced. Returns true if a session loaded.
1260
- */
1261
- loadExisting(): Promise<boolean>;
1262
- phase(): AISpecPhase;
1263
- currentPrompt(): string;
1264
- getTracker(): TaskTracker | null;
1265
- getGraph(): TaskGraph | null;
1266
- /** Record a Q/A pair (the agent asked `question`, the user replied `answer`). */
1267
- submitAnswer(question: string, answer: string): void;
1268
- /**
1269
- * Feed the agent's text output back into the interview. Detects, in order:
1270
- * 1. a Specification JSON → setSpec (phase → spec_review) + persist to SpecStore
1271
- * 2. an implementation plan (implementation phase) → setImplementation
1272
- * 3. a task JSON array → build + persist a TaskGraph
1273
- * Each step is independent and best-effort; a malformed payload is ignored
1274
- * rather than thrown, so a chatty agent turn never breaks the interview.
1275
- */
1276
- ingestAgentOutput(text: string): Promise<SddIngestResult>;
1277
- /**
1278
- * Advance to the next phase (mirrors `/sdd approve`). When moving into the
1279
- * executing phase, guarantees a task graph exists — deterministically
1280
- * generating one from the approved spec if the agent never emitted a valid
1281
- * task array. Returns the new phase and its AI prompt.
1282
- */
1283
- approve(): Promise<{
1284
- phase: AISpecPhase;
1285
- prompt: string;
1286
- }>;
1287
- /**
1288
- * Ensure a TaskGraph exists for the approved spec. If the agent already
1289
- * produced one (via `ingestAgentOutput`), returns it; otherwise builds a
1290
- * deterministic graph from the spec's requirements via TaskGenerator. This is
1291
- * the robustness backstop: a run can always start, even if the model never
1292
- * emitted a parseable task array.
1293
- */
1294
- ensureTaskGraph(): Promise<TaskGraph | null>;
1295
- snapshot(): SddInterviewSnapshot;
1296
- private persistSpec;
1297
- private persistGraph;
1298
- /**
1299
- * Port of the CLI `trySaveImplementationPlan` operating on this driver's
1300
- * builder. Captures the prose plan that precedes the task JSON block.
1301
- */
1302
- private trySaveImplementationPlan;
1303
- /**
1304
- * Port of the CLI `trySaveTasksFromAIOutput`: parse a task JSON array from the
1305
- * agent output, build (or extend) the tracker + graph, persist to disk, and
1306
- * link the graphId to the session. Returns the graphId on success.
1307
- */
1308
- private tryBuildTasksFromOutput;
1309
- }
1310
- /**
1311
- * True when the text reads like conversational filler rather than a structured
1312
- * implementation plan. Ported verbatim from the CLI detection so behaviour is
1313
- * identical across surfaces.
1314
- */
1315
- declare function isExplanatoryText(text: string): boolean;
1316
-
1317
- interface StartSddRunOptions {
1318
- tracker: TaskTracker;
1319
- graph: TaskGraph;
1320
- /** Leader agent — seeds the default factory and the run's project context. */
1321
- agent: Agent;
1322
- projectRoot: string;
1323
- events: EventBus;
1324
- /** Parent session id for all SDD EventBus emissions. */
1325
- sessionId?: string | (() => string | undefined) | undefined;
1326
- /** Per-task agent factory. Omit to run every task on the leader agent. */
1327
- subagentFactory?: AgentFactory | undefined;
1328
- /** Board snapshot/event persistence (also drained for cross-process control). */
1329
- boardStore: SddBoardStore;
1330
- /** Registry the run is registered with for in-process control. */
1331
- registry?: SddRunRegistry | undefined;
1332
- parallelSlots?: number | undefined;
1333
- /** Opt-in hard wall-clock cap per task (ms). Omit → no cap (idle reaper guards). */
1334
- taskTimeoutMs?: number | undefined;
1335
- /** Idle reaper per task (ms); resets on activity. Default 600_000 (10 min). */
1336
- taskIdleTimeoutMs?: number | undefined;
1337
- /** End-of-run failed-task auto-retry sweeps (bounded). Default 2. */
1338
- maxFailedRetrySweeps?: number | undefined;
1339
- /** Post-task verification gate (forwarded to SddParallelRun). Omit → no gate. */
1340
- verifyTask?: SddParallelRunOptions['verifyTask'];
1341
- /** Merge-conflict resolver (forwarded to SddParallelRun). Omit → retry-on-fresh-base then fail. */
1342
- conflictResolver?: SddParallelRunOptions['conflictResolver'];
1343
- /** Failure supervisor (forwarded to SddParallelRun). Omit → no rescue, plain terminal-fail. */
1344
- superviseFailure?: SddParallelRunOptions['superviseFailure'];
1345
- /** Run-level default worker model / provider / fallback chain (task overrides win). */
1346
- defaultModel?: string | undefined;
1347
- defaultProvider?: string | undefined;
1348
- fallbackModels?: string[] | undefined;
1349
- /** Per-task git worktree isolation. Omit → tasks share the working tree. */
1350
- worktrees?: WorktreeManager | undefined;
1351
- /** Bounded deadlock recovery rounds (default 1). */
1352
- maxRecoveryRounds?: number | undefined;
1353
- /** Progress callback (e.g. CLI renderer line). */
1354
- onProgress?: ((p: SddProgress) => void) | undefined;
1355
- /** Control-file drain interval in ms (default 500). */
1356
- controlDrainMs?: number | undefined;
1357
- }
1358
- interface SddRunHandle {
1359
- run: SddParallelRun;
1360
- runId: string;
1361
- projector: SddBoardProjector;
1362
- /** Resolves when the run finishes AND all teardown (drain/dispose/clear) is done. */
1363
- completion: Promise<RunResult>;
1364
- /** Request a clean stop (idempotent). */
1365
- stop(): void;
1366
- }
1367
- /**
1368
- * Wire up and start an SDD parallel run. Returns immediately with a handle whose
1369
- * `completion` promise resolves once the run finishes and teardown is complete.
1370
- * Orphaned in_progress tasks are reset up-front so a crashed prior run re-executes.
1371
- */
1372
- declare function startSddRun(opts: StartSddRunOptions): SddRunHandle;
1373
-
1374
- /** Force-remove every git worktree + branch a previous run left behind. */
1375
- declare function cleanupSddWorktrees(projectRoot: string): Promise<{
1376
- removed: number;
1377
- }>;
1378
- /**
1379
- * Detect and clean up stale worktrees from a crashed previous run.
1380
- * No-op when the project is clean. Called on SDD/Director boot to
1381
- * prevent orphaned worktrees from conflicting with the next run's
1382
- * `allocate()`.
1383
- *
1384
- * P2 #B6 (sprint2 audit).
1385
- */
1386
- declare function cleanupStaleWorktrees(projectRoot: string): Promise<{
1387
- removed: number;
1388
- detected: number;
1389
- }>;
1390
- interface CleanupStaleSddOptions {
1391
- projectRoot: string;
1392
- /** Board snapshot dir (`wpaths.projectSddBoards`) — read for the liveness guard. */
1393
- boardsDir: string;
1394
- /** A `running` board updated within this window is treated as live → skip. Default 120_000 (2 min). */
1395
- runningLiveMs?: number | undefined;
1396
- /** A `paused` board updated within this window is treated as live → skip. Default 1_800_000 (30 min). */
1397
- pausedLiveMs?: number | undefined;
1398
- /** Injectable clock for tests. */
1399
- now?: (() => number) | undefined;
1400
- }
1401
- interface CleanupStaleSddResult {
1402
- /** True when a sweep ran (orphans were found and removed). */
1403
- swept: boolean;
1404
- removed: number;
1405
- detected: number;
1406
- /** Set when the sweep was skipped because a run appears live. */
1407
- skippedReason?: string | undefined;
1408
- }
1409
- /**
1410
- * Liveness-guarded stale-worktree sweep for boot + run-start. Worktrees live
1411
- * under `<projectRoot>/.wrongstack/worktrees` and a sweep force-removes ALL of
1412
- * them — so it must NEVER run under a genuinely live run (possibly in another
1413
- * process). The guard reads the latest board: a `running` board updated within
1414
- * `runningLiveMs`, or a `paused` one within `pausedLiveMs`, is treated as live
1415
- * and the sweep is skipped. A crashed run leaves its board frozen as `running`
1416
- * → once it ages past the window it is correctly swept. Any other status
1417
- * (completed / failed / stopped / deadlocked / idle) is always sweepable.
1418
- * Never throws — best-effort cleanup.
1419
- */
1420
- declare function cleanupStaleSddWorktrees(opts: CleanupStaleSddOptions): Promise<CleanupStaleSddResult>;
1421
- interface RollbackFromDiskOptions {
1422
- projectRoot: string;
1423
- /** Directory holding persisted board snapshots (`wpaths.projectSddBoards`). */
1424
- boardsDir: string;
1425
- /** Specific run to roll back. Omit → the most recently updated board. */
1426
- runId?: string | undefined;
1427
- }
1428
- /**
1429
- * Roll back a finished run's merged commits by reading its persisted board
1430
- * snapshot (base branch + commit SHAs) and reverting each. History-preserving;
1431
- * refuses on a dirty tree or revert conflict (surfaced in `reason`). Returns
1432
- * `ok:false` with a reason when there is no board, no base branch, or nothing to
1433
- * revert.
1434
- */
1435
- declare function rollbackSddRunFromDisk(opts: RollbackFromDiskOptions): Promise<{
1436
- ok: boolean;
1437
- reverted: number;
1438
- reason?: string;
1439
- }>;
1440
- interface DestroySddProjectOptions {
1441
- projectRoot: string;
1442
- /** Resolved wstack paths to delete. */
1443
- paths: {
1444
- projectSpecs: string;
1445
- projectTaskGraphs: string;
1446
- projectSddSession: string;
1447
- projectSddBoards: string;
1448
- };
1449
- /**
1450
- * Also revert this run's already-merged squash commits (history-preserving
1451
- * `git revert`) BEFORE deleting the board that records them. Off by default —
1452
- * a plain destroy wipes worktrees + artifacts but leaves merged commits on the
1453
- * base branch (un-merged worktree work is destroyed regardless, since its
1454
- * branch is force-removed). When on and the working tree is dirty, the revert
1455
- * is refused and surfaced in `revertReason` (the destroy still proceeds).
1456
- */
1457
- revertMerged?: boolean | undefined;
1458
- /** Which run's merged commits to revert. Omit → the most recently updated board. */
1459
- runId?: string | undefined;
1460
- }
1461
- interface DestroySddProjectResult {
1462
- worktreesRemoved: number;
1463
- /** Human labels of the artifacts that were deleted. */
1464
- deleted: string[];
1465
- /** Number of merged commits reverted (only when `revertMerged` was set). */
1466
- reverted: number;
1467
- /** Whether the optional merged-commit revert succeeded (undefined → not requested). */
1468
- revertOk?: boolean | undefined;
1469
- /** Why the revert did not fully apply (dirty tree, conflict, nothing to revert). */
1470
- revertReason?: string | undefined;
1471
- }
1472
- /**
1473
- * Destroy an SDD project: optionally revert its merged commits, then clean every
1474
- * worktree + branch, then delete the on-disk artifacts (specs, task-graphs,
1475
- * session, boards). The revert is opt-in (`revertMerged`) and runs FIRST — it
1476
- * reads the board snapshot that the artifact deletion removes. Best-effort: a
1477
- * missing path is simply skipped. The caller is responsible for stopping any
1478
- * active run first.
1479
- */
1480
- declare function destroySddProject(opts: DestroySddProjectOptions): Promise<DestroySddProjectResult>;
1481
- /** Lifecycle operation kinds shared by every surface (WebUI / TUI / CLI). */
1482
- type SddLifecycleOp = 'cleanup_worktrees' | 'rollback' | 'destroy';
1483
- interface SddLifecycleOptions {
1484
- projectRoot: string;
1485
- /** Resolved wstack paths (required for `destroy`; boards dir is enough for `rollback`). */
1486
- paths: {
1487
- projectSpecs: string;
1488
- projectTaskGraphs: string;
1489
- projectSddSession: string;
1490
- projectSddBoards: string;
1491
- };
1492
- /** Target a specific run (rollback / destroy). Omit → most recently updated board. */
1493
- runId?: string | undefined;
1494
- /** `destroy` only: also revert merged commits before wiping. */
1495
- revertMerged?: boolean | undefined;
1496
- }
1497
- /** Uniform result for any lifecycle op — drives identical UI wording everywhere. */
1498
- interface SddLifecycleResult {
1499
- op: SddLifecycleOp;
1500
- ok: boolean;
1501
- /** Worktrees removed (cleanup_worktrees / destroy). */
1502
- removed?: number | undefined;
1503
- /** Merged commits reverted (rollback / destroy with revertMerged). */
1504
- reverted?: number | undefined;
1505
- /** Artifact labels deleted (destroy). */
1506
- deleted?: string[] | undefined;
1507
- /** Failure / partial reason, surfaced verbatim in the UI. */
1508
- reason?: string | undefined;
1509
- }
1510
- /**
1511
- * Apply a post-run SDD lifecycle operation from disk and return a uniform result.
1512
- * The single entry point shared by the WebUI board handler, the TUI overlay, and
1513
- * the CLI `/sdd` host so every surface reports the same thing. The caller must
1514
- * ensure no run is active (these operate on git + on-disk state, not the live
1515
- * run) — `cleanup`/`destroy` force-remove worktrees, `rollback` refuses on a
1516
- * dirty tree. Never throws.
1517
- */
1518
- declare function applySddLifecycle(op: SddLifecycleOp, opts: SddLifecycleOptions): Promise<SddLifecycleResult>;
1519
-
1520
- /**
1521
- * Built-in spec templates for common development scenarios.
1522
- */
1523
- declare const SPEC_TEMPLATES: SpecTemplate[];
1524
- /**
1525
- * Get a template by ID.
1526
- */
1527
- declare function getTemplate(id: string): SpecTemplate | undefined;
1528
- /**
1529
- * List all available templates.
1530
- */
1531
- declare function listTemplates(): Array<{
1532
- id: string;
1533
- name: string;
1534
- description: string;
1535
- }>;
1536
- /**
1537
- * Generate a markdown skeleton from a template.
1538
- */
1539
- declare function templateToMarkdown(template: SpecTemplate, title?: string): string;
1540
-
1541
- /**
1542
- * Render a task graph as ASCII art for terminal display.
1543
- */
1544
- declare function renderTaskGraph(graph: TaskGraph, opts?: {
1545
- compact?: boolean | undefined;
1546
- }): string;
1547
- /**
1548
- * Render a progress bar.
1549
- */
1550
- declare function renderProgress(progress: TaskProgress): string;
1551
- /**
1552
- * Render a compact task list (for quick status checks).
1553
- */
1554
- declare function renderTaskList(graph: TaskGraph): string;
1555
- /**
1556
- * Render spec analysis summary.
1557
- */
1558
- declare function renderSpecAnalysis(spec: Specification, analysis: {
1559
- completeness: number;
1560
- gaps: string[];
1561
- risks: string[];
1562
- suggestions: string[];
1563
- }): string;
1564
-
1565
- /**
1566
- * Enhanced critical path analysis with bottleneck detection,
1567
- * parallel execution groups, and time estimation.
1568
- */
1569
- interface CriticalPathAnalysis {
1570
- /** Ordered list of critical path task IDs. */
1571
- criticalPath: string[];
1572
- /** Total estimated hours for the critical path. */
1573
- totalHours: number;
1574
- /** Tasks that block the most downstream work. */
1575
- bottlenecks: BottleneckTask[];
1576
- /** Groups of tasks that can run in parallel. */
1577
- parallelGroups: string[][];
1578
- /** Recommended execution order respecting dependencies. */
1579
- executionOrder: string[];
1580
- /** Tasks with no blockers (can start immediately). */
1581
- readyTasks: string[];
1582
- /** Tasks that are blocked and cannot start. */
1583
- blockedTasks: string[];
1584
- }
1585
- interface BottleneckTask {
1586
- taskId: string;
1587
- title: string;
1588
- /** Number of tasks directly or transitively blocked by this task. */
1589
- blockedCount: number;
1590
- /** Total estimated hours of blocked downstream work. */
1591
- blockedHours: number;
1592
- /** Severity score (0-100). */
1593
- severity: number;
1594
- }
1595
- /**
1596
- * Analyze a task graph and return critical path analysis.
1597
- */
1598
- declare function analyzeCriticalPath(graph: TaskGraph): CriticalPathAnalysis;
1599
-
1600
- interface SpecVersion {
1601
- version: string;
1602
- spec: Specification;
1603
- timestamp: number;
1604
- changeDescription?: string | undefined;
1605
- }
1606
- interface SpecDiff {
1607
- added: SpecRequirement[];
1608
- removed: SpecRequirement[];
1609
- modified: Array<{
1610
- requirement: SpecRequirement;
1611
- previousVersion: SpecRequirement;
1612
- changes: string[];
1613
- }>;
1614
- summary: string;
1615
- }
1616
- /**
1617
- * Track spec versions and compute diffs between versions.
1618
- */
1619
- declare class SpecVersioning {
1620
- private versions;
1621
- /** Record a new version of a spec. */
1622
- recordVersion(spec: Specification, changeDescription?: string): SpecVersion;
1623
- /** Get version history for a spec. */
1624
- getHistory(specId: string): SpecVersion[];
1625
- /** Get a specific version of a spec. */
1626
- getVersion(specId: string, version: string): SpecVersion | undefined;
1627
- /** Get the latest version of a spec. */
1628
- getLatest(specId: string): SpecVersion | undefined;
1629
- /** Compute diff between two versions of a spec. */
1630
- diff(oldSpec: Specification, newSpec: Specification): SpecDiff;
1631
- /**
1632
- * Update a task graph incrementally based on spec changes.
1633
- * - Added requirements → new tasks
1634
- * - Removed requirements → remove tasks
1635
- * - Modified requirements → update task descriptions
1636
- * Returns the updated graph and list of changes made.
1637
- */
1638
- updateTaskGraph(graph: TaskGraph, oldSpec: Specification, newSpec: Specification): {
1639
- graph: TaskGraph;
1640
- changes: string[];
1641
- };
1642
- private compareRequirements;
1643
- private buildTaskDescription;
1644
- private mapReqType;
1645
- }
1646
-
1647
- interface AutoExecutorOptions {
1648
- tracker: TaskTracker;
1649
- events: EventBus;
1650
- /** Maximum concurrent tasks. Defaults to 1 (sequential). */
1651
- maxConcurrent?: number | undefined;
1652
- /** Maximum retry attempts for failed tasks. */
1653
- maxRetries?: number | undefined;
1654
- /** Custom task executor function. */
1655
- executeTask: (task: TaskNode, context: TaskExecutionContext) => Promise<TaskExecutionResult>;
1656
- /** Called before each task starts. */
1657
- onTaskStart?: (((task: TaskNode) => void)) | undefined;
1658
- /** Called after each task completes. */
1659
- onTaskComplete?: (task: TaskNode, result: TaskExecutionResult) => void;
1660
- /** Called when a task fails. */
1661
- onTaskFail?: (task: TaskNode, error: Error, retryCount: number) => void;
1662
- /** Called when all tasks are done or no more can execute. */
1663
- onDone?: (((summary: ExecutionSummary) => void)) | undefined;
1664
- }
1665
- interface TaskExecutionContext {
1666
- /** The spec being implemented. */
1667
- spec: Specification;
1668
- /** The full task graph. */
1669
- graph: TaskGraph;
1670
- /** The current task being executed. */
1671
- task: TaskNode;
1672
- /** Tasks that this task depends on. */
1673
- dependencies: TaskNode[];
1674
- /** Tasks that depend on this task. */
1675
- dependents: TaskNode[];
1676
- /** Retry count for this task (0 = first attempt). */
1677
- retryCount: number;
1678
- }
1679
- interface TaskExecutionResult {
1680
- success: boolean;
1681
- output?: string | undefined;
1682
- error?: string | undefined;
1683
- /** If true, the task will be retried. */
1684
- retry?: boolean | undefined;
1685
- }
1686
- interface ExecutionSummary {
1687
- total: number;
1688
- completed: number;
1689
- failed: number;
1690
- skipped: number;
1691
- retried: number;
1692
- duration: number;
1693
- criticalPath: string[];
1694
- }
1695
- /**
1696
- * Auto-executor that drives task execution with dependency resolution,
1697
- * retry logic, and critical path awareness.
1698
- */
1699
- declare class AutoExecutor {
1700
- private readonly opts;
1701
- private stopped;
1702
- private retryMap;
1703
- constructor(opts: AutoExecutorOptions);
1704
- /**
1705
- * Execute all tasks in the graph, respecting dependencies.
1706
- */
1707
- execute(graph: TaskGraph, spec: Specification): Promise<ExecutionSummary>;
1708
- /** Stop execution. */
1709
- stop(): void;
1710
- /** Get tasks that are ready to execute (all dependencies completed). */
1711
- private getReadyTasks;
1712
- /** Execute a single task with retry logic. */
1713
- private executeTaskWithRetry;
1714
- /** Get tasks that this task depends on. */
1715
- private getTaskDependencies;
1716
- /** Get tasks that depend on this task. */
1717
- private getTaskDependents;
1718
- /** Detect deadlock: all remaining tasks are blocked by failed tasks. */
1719
- private detectDeadlock;
1720
- }
1721
- /**
1722
- * Create an auto-executor that works with TaskFlow.
1723
- */
1724
- declare function createAutoExecutor(opts: {
1725
- tracker: TaskTracker;
1726
- events: EventBus;
1727
- executeTask: AutoExecutorOptions['executeTask'];
1728
- maxConcurrent?: number | undefined;
1729
- maxRetries?: number | undefined;
1730
- }): AutoExecutor;
1731
-
1732
- interface SddSupervisorOptions {
1733
- /** Decision authority (policy/LLM/human). Reuse the session's TOKENS.BrainArbiter. */
1734
- brain: BrainArbiter;
1735
- /**
1736
- * Models to rotate through on a `reassign` verdict (e.g. the run's fallback
1737
- * chain). Omit to drop the reassign option entirely.
1738
- */
1739
- reassignModels?: string[] | undefined;
1740
- /**
1741
- * Optional sub-task generator for a `split` verdict — typically an LLM call
1742
- * that decomposes the failing task into smaller pieces. Omit to drop the split
1743
- * option. Returning an empty array degrades the split into a retry.
1744
- */
1745
- generateSubtasks?: ((info: {
1746
- task: TaskNode;
1747
- error: string;
1748
- }) => Promise<SddSubtaskSpec[]>) | undefined;
1749
- /**
1750
- * Let the tiered brain's LLM layer actually pick the verdict.
1751
- *
1752
- * Default (false) requests `fallback: 'continue'`, which the policy layer
1753
- * answers immediately (a bounded retry) — the LLM never runs, so `reassign`/
1754
- * `split` can't be chosen. Set true to request `fallback: 'ask_human'`, which
1755
- * makes the policy escalate so the autonomous (LLM) layer decides.
1756
- *
1757
- * ONLY enable this when the supplied `brain` will NOT block on a human prompt
1758
- * for an unresolved decision (i.e. it has an autonomous layer and is NOT
1759
- * wrapped in `HumanEscalatingBrainArbiter`). When the LLM can't decide (no
1760
- * autonomous layer / over the risk ceiling / LLM down) the brain returns
1761
- * `ask_human`, which the supervisor degrades to a **bounded retry** (never a
1762
- * block, never a dead-end). A human-escalating brain would instead block
1763
- * inside `decide()` and wedge the run — keep this false there.
1764
- */
1765
- requestLlmVerdict?: boolean | undefined;
1766
- }
1767
- declare class SddSupervisor {
1768
- private readonly opts;
1769
- constructor(opts: SddSupervisorOptions);
1770
- /**
1771
- * Bind this as `SddParallelRunOptions.superviseFailure`. Returns a verdict the
1772
- * run applies, or `undefined`/`{action:'fail'}` to let the task terminal-fail.
1773
- */
1774
- readonly superviseFailure: (info: {
1775
- task: TaskNode;
1776
- error: string;
1777
- attempts: number;
1778
- }) => Promise<SddSupervisorVerdict | undefined>;
1779
- }
1780
-
1781
- interface CommandVerifierOptions {
1782
- /** Metadata key holding the shell command to run. Default 'verificationCommand'. */
1783
- metadataKey?: string;
1784
- /** Kill + fail the verification after this many ms. Default 180_000 (3 min). */
1785
- timeoutMs?: number;
1786
- }
1787
- /**
1788
- * Build a `verifyTask` closure (shape matches {@link SddParallelRunOptions.verifyTask}).
1789
- * Returns `{ ok: true }` immediately when the task carries no verification command,
1790
- * otherwise spawns the command in `cwd` (shell, output discarded) and resolves
1791
- * `{ ok: false, reason }` on non-zero exit, spawn error, or timeout.
1792
- */
1793
- declare function makeCommandVerifier(options?: CommandVerifierOptions): (info: {
1794
- task: TaskNode;
1795
- result: TaskResult;
1796
- cwd: string;
1797
- }) => Promise<{
1798
- ok: boolean;
1799
- reason?: string;
1800
- }>;
1801
-
1802
- interface SubtaskGeneratorOptions {
1803
- /** Runs one self-contained, isolated LLM turn and resolves its final text. */
1804
- run: (prompt: string) => Promise<string>;
1805
- /** Minimum well-formed sub-tasks required to accept a split. Default 2. */
1806
- minSubtasks?: number;
1807
- /** Maximum sub-tasks kept (excess is dropped). Default 4. */
1808
- maxSubtasks?: number;
1809
- }
1810
- /**
1811
- * Build a `SddSupervisorOptions.generateSubtasks` closure backed by an LLM turn.
1812
- * Returns [] on any failure (parse error, too few valid items, runner throw), so
1813
- * the supervisor safely degrades a `split` verdict into a retry.
1814
- */
1815
- declare function makeLlmSubtaskGenerator(opts: SubtaskGeneratorOptions): (info: {
1816
- task: TaskNode;
1817
- error: string;
1818
- }) => Promise<SddSubtaskSpec[]>;
1819
-
1820
- type ConflictSide = 'incoming' | 'base';
1821
- /**
1822
- * Resolve every standard git conflict hunk in `text` by keeping `side`. Handles
1823
- * both 2-way (`<<<<<<< / ======= / >>>>>>>`) and diff3 (`||||||| base`) markers.
1824
- * Returns the rewritten text (markers removed).
1825
- */
1826
- declare function resolveConflictText(text: string, side: ConflictSide): string;
1827
- /** True when `text` still contains a git conflict marker line. */
1828
- declare function hasConflictMarkers(text: string): boolean;
1829
- /**
1830
- * Build a `conflictResolver` that keeps `side` of every hunk in each conflicted
1831
- * file. Returns false (abort → conservative fail) if any file can't be read,
1832
- * written, or still has markers after the rewrite.
1833
- */
1834
- declare function makePreferSideConflictResolver(side: ConflictSide): (info: {
1835
- task: TaskNode;
1836
- conflictFiles: string[];
1837
- cwd: string;
1838
- }) => Promise<boolean>;
1839
- interface LlmConflictResolverOptions {
1840
- /** Runs one self-contained, isolated LLM turn and resolves its final text. */
1841
- run: (prompt: string) => Promise<string>;
1842
- /**
1843
- * Reject a resolution that shrinks the file below this fraction of its original
1844
- * non-marker line count — a crude guard against the model dropping content.
1845
- * Default 0.5.
1846
- */
1847
- minRetainedFraction?: number;
1848
- }
1849
- /**
1850
- * Build an LLM-backed `conflictResolver`: for each conflicted file it asks the
1851
- * model (via one isolated `run` turn) to produce the fully resolved file and
1852
- * writes it back. Heavily guarded — returns false (→ conservative abort/retry)
1853
- * if the model leaves a marker, returns junk, or drops too much content. The
1854
- * WorktreeManager STILL rejects any surviving marker, and (when a `verifyTask`
1855
- * is configured) the run re-verifies the integrated base and reverts a
1856
- * regression — so a bad LLM merge can never silently stick. OFF by default.
1857
- */
1858
- declare function makeLlmConflictResolver(opts: LlmConflictResolverOptions): (info: {
1859
- task: TaskNode;
1860
- conflictFiles: string[];
1861
- cwd: string;
1862
- }) => Promise<boolean>;
1863
-
1864
- export { AISpecBuilder, type AISpecBuilderOptions, type AISpecPhase, type AISpecSession, AutoExecutor, type AutoExecutorOptions, type BottleneckTask, type CleanupStaleSddOptions, type CleanupStaleSddResult, type CollectedAnswer, type CommandVerifierOptions, type ConflictSide, type CriticalPathAnalysis, type DestroySddProjectOptions, type DestroySddProjectResult, type ExecutionSummary, type GeneratedTask, type LlmConflictResolverOptions, type RollbackFromDiskOptions, type RunResult, SPEC_TEMPLATES, type SddBoardColumn, type SddBoardEvent, type SddBoardFeedEntry, type SddBoardIndexEntry, SddBoardProjector, type SddBoardProjectorOptions, type SddBoardSnapshot, type SddBoardStatus, SddBoardStore, type SddBoardStoreOptions, type SddBoardTask, type SddDeadlockChain, type SddIngestResult, SddInterviewDriver, type SddInterviewDriverOptions, type SddInterviewSnapshot, type SddLifecycleOp, type SddLifecycleOptions, type SddLifecycleResult, SddParallelRun, type SddParallelRunOptions, type SddProgress, type SddRunControl, type SddRunHandle, SddRunRegistry, type SddSubtaskSpec, SddSupervisor, type SddSupervisorOptions, type SddSupervisorVerdict, SddTaskDecomposer, type SddTaskDecomposerOptions, type SddTaskDisplayStatus, type SpecDiff, SpecDrivenDev, type SpecDrivenDevOptions, type SpecIndexEntry, SpecParser, SpecStore, type SpecStoreOptions, type SpecVersion, SpecVersioning, type StartSddRunOptions, type SubtaskGeneratorOptions, type TaskBatch, type TaskExecutionContext, type TaskExecutionResult, TaskFlow, type TaskFlowEventMap, type TaskFlowEventName, type TaskFlowExecutionContext, type TaskFlowOptions, type TaskFlowPhase, TaskGenerator, type TaskGeneratorOptions, type TaskGraphIndexEntry, TaskGraphStore, type TaskGraphStoreOptions, type WaveResult, analyzeCriticalPath, applySddLifecycle, buildBoardSnapshot, buildBoardTasks, cleanupSddWorktrees, cleanupStaleSddWorktrees, cleanupStaleWorktrees, createAutoExecutor, destroySddProject, extractVerificationCommand, getTemplate, hasConflictMarkers, isExplanatoryText, listTemplates, makeCommandVerifier, makeLlmConflictResolver, makeLlmSubtaskGenerator, makePreferSideConflictResolver, renderProgress, renderSpecAnalysis, renderTaskGraph, renderTaskList, resolveConflictText, rollbackSddRunFromDisk, shortIdMap, startSddRun, templateToMarkdown };
1
+ export { SpecParser } from './spec-parser.js';
2
+ export { TaskGenerator, extractVerificationCommand, type TaskGeneratorOptions, type GeneratedTask, } from './task-generator.js';
3
+ export { TaskTracker, DefaultTaskStore, type TaskStore, type TaskTrackerOptions, type TaskTransition, type TaskTrackerChange, type TaskTrackerListener, } from '@wrongstack/core/tasking';
4
+ export { TaskFlow, SpecDrivenDev, type TaskFlowPhase, type TaskFlowOptions, type TaskFlowExecutionContext, type TaskFlowEventMap, type TaskFlowEventName, type SpecDrivenDevOptions, } from './task-flow.js';
5
+ export { SpecStore, type SpecStoreOptions, type SpecIndexEntry } from './spec-store.js';
6
+ export { TaskGraphStore, type TaskGraphStoreOptions, type TaskGraphIndexEntry } from './task-graph-store.js';
7
+ export { buildBoardTasks, buildBoardSnapshot, shortIdMap, type SddBoardSnapshot, type SddBoardTask, type SddBoardColumn, type SddBoardStatus, type SddTaskDisplayStatus, type SddDeadlockChain, type SddBoardFeedEntry, } from './board-types.js';
8
+ export { SddBoardStore, type SddBoardStoreOptions, type SddBoardIndexEntry, type SddBoardEvent, } from './sdd-board-store.js';
9
+ export { SddBoardProjector, type SddBoardProjectorOptions } from './sdd-board-projector.js';
10
+ export { SddRunRegistry, type SddRunControl } from './sdd-run-registry.js';
11
+ export { SddInterviewDriver, isExplanatoryText, type SddInterviewDriverOptions, type SddInterviewSnapshot, type SddIngestResult, } from './sdd-interview-driver.js';
12
+ export { startSddRun, type StartSddRunOptions, type SddRunHandle, } from './start-sdd-run.js';
13
+ export { cleanupSddWorktrees, cleanupStaleWorktrees, cleanupStaleSddWorktrees, rollbackSddRunFromDisk, destroySddProject, applySddLifecycle, type RollbackFromDiskOptions, type DestroySddProjectOptions, type DestroySddProjectResult, type CleanupStaleSddOptions, type CleanupStaleSddResult, type SddLifecycleOp, type SddLifecycleOptions, type SddLifecycleResult, } from './sdd-lifecycle.js';
14
+ export { AISpecBuilder, type AISpecBuilderOptions, type AISpecPhase, type AISpecSession, type CollectedAnswer, } from './spec-builder.js';
15
+ export { SPEC_TEMPLATES, getTemplate, listTemplates, templateToMarkdown, } from './spec-templates.js';
16
+ export { renderTaskGraph, renderProgress, renderTaskList, renderSpecAnalysis, } from './task-visualizer.js';
17
+ export { analyzeCriticalPath, type CriticalPathAnalysis, type BottleneckTask } from './critical-path.js';
18
+ export { SpecVersioning, type SpecVersion, type SpecDiff } from './spec-versioning.js';
19
+ export { AutoExecutor, createAutoExecutor, type AutoExecutorOptions, type TaskExecutionContext, type TaskExecutionResult, type ExecutionSummary, } from './auto-executor.js';
20
+ export { SddTaskDecomposer, type SddTaskDecomposerOptions, type TaskBatch, } from './sdd-task-decomposer.js';
21
+ export { SddParallelRun, type SddParallelRunOptions, type SddProgress, type WaveResult, type RunResult, type SddSubtaskSpec, type SddSupervisorVerdict, } from './sdd-parallel-run.js';
22
+ export { SddSupervisor, type SddSupervisorOptions } from './sdd-supervisor.js';
23
+ export { makeCommandVerifier, type CommandVerifierOptions } from './verify-task.js';
24
+ export { makeLlmSubtaskGenerator, type SubtaskGeneratorOptions } from './decompose-task.js';
25
+ export { makePreferSideConflictResolver, makeLlmConflictResolver, resolveConflictText, hasConflictMarkers, type ConflictSide, type LlmConflictResolverOptions, } from './conflict-resolver.js';
26
+ //# sourceMappingURL=index.d.ts.map