@tagma/sdk 0.6.12 → 0.7.1

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 (125) hide show
  1. package/README.md +56 -15
  2. package/dist/bootstrap.d.ts +6 -6
  3. package/dist/bootstrap.d.ts.map +1 -1
  4. package/dist/bootstrap.js +5 -6
  5. package/dist/bootstrap.js.map +1 -1
  6. package/dist/config.d.ts +8 -0
  7. package/dist/config.d.ts.map +1 -0
  8. package/dist/config.js +5 -0
  9. package/dist/config.js.map +1 -0
  10. package/dist/core/dataflow.d.ts +23 -0
  11. package/dist/core/dataflow.d.ts.map +1 -0
  12. package/dist/core/dataflow.js +99 -0
  13. package/dist/core/dataflow.js.map +1 -0
  14. package/dist/core/log-prune.d.ts +16 -0
  15. package/dist/core/log-prune.d.ts.map +1 -0
  16. package/dist/core/log-prune.js +34 -0
  17. package/dist/core/log-prune.js.map +1 -0
  18. package/dist/core/preflight.d.ts +13 -0
  19. package/dist/core/preflight.d.ts.map +1 -0
  20. package/dist/core/preflight.js +61 -0
  21. package/dist/core/preflight.js.map +1 -0
  22. package/dist/core/run-context.d.ts +52 -0
  23. package/dist/core/run-context.d.ts.map +1 -0
  24. package/dist/core/run-context.js +156 -0
  25. package/dist/core/run-context.js.map +1 -0
  26. package/dist/core/run-state.d.ts +25 -0
  27. package/dist/core/run-state.d.ts.map +1 -0
  28. package/dist/core/run-state.js +93 -0
  29. package/dist/core/run-state.js.map +1 -0
  30. package/dist/core/scheduler.d.ts +13 -0
  31. package/dist/core/scheduler.d.ts.map +1 -0
  32. package/dist/core/scheduler.js +35 -0
  33. package/dist/core/scheduler.js.map +1 -0
  34. package/dist/core/task-executor.d.ts +13 -0
  35. package/dist/core/task-executor.d.ts.map +1 -0
  36. package/dist/core/task-executor.js +623 -0
  37. package/dist/core/task-executor.js.map +1 -0
  38. package/dist/core/trigger-errors.d.ts +9 -0
  39. package/dist/core/trigger-errors.d.ts.map +1 -0
  40. package/dist/core/trigger-errors.js +15 -0
  41. package/dist/core/trigger-errors.js.map +1 -0
  42. package/dist/engine.d.ts +6 -14
  43. package/dist/engine.d.ts.map +1 -1
  44. package/dist/engine.js +68 -1035
  45. package/dist/engine.js.map +1 -1
  46. package/dist/index.d.ts +9 -0
  47. package/dist/index.d.ts.map +1 -0
  48. package/dist/index.js +6 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/pipeline-definition.d.ts +3 -0
  51. package/dist/pipeline-definition.d.ts.map +1 -0
  52. package/dist/pipeline-definition.js +4 -0
  53. package/dist/pipeline-definition.js.map +1 -0
  54. package/dist/pipeline-runner.d.ts +2 -1
  55. package/dist/pipeline-runner.d.ts.map +1 -1
  56. package/dist/pipeline-runner.js +2 -2
  57. package/dist/pipeline-runner.js.map +1 -1
  58. package/dist/plugins.d.ts +5 -0
  59. package/dist/plugins.d.ts.map +1 -0
  60. package/dist/plugins.js +3 -0
  61. package/dist/plugins.js.map +1 -0
  62. package/dist/ports.d.ts +4 -0
  63. package/dist/ports.d.ts.map +1 -1
  64. package/dist/ports.js +27 -4
  65. package/dist/ports.js.map +1 -1
  66. package/dist/registry.d.ts +3 -19
  67. package/dist/registry.d.ts.map +1 -1
  68. package/dist/registry.js +7 -35
  69. package/dist/registry.js.map +1 -1
  70. package/dist/tagma.d.ts +24 -0
  71. package/dist/tagma.d.ts.map +1 -0
  72. package/dist/tagma.js +23 -0
  73. package/dist/tagma.js.map +1 -0
  74. package/dist/utils-api.d.ts +2 -0
  75. package/dist/utils-api.d.ts.map +1 -0
  76. package/dist/utils-api.js +2 -0
  77. package/dist/utils-api.js.map +1 -0
  78. package/dist/validate-raw.d.ts +4 -4
  79. package/dist/validate-raw.js +91 -132
  80. package/dist/validate-raw.js.map +1 -1
  81. package/dist/yaml.d.ts +4 -0
  82. package/dist/yaml.d.ts.map +1 -0
  83. package/dist/yaml.js +3 -0
  84. package/dist/yaml.js.map +1 -0
  85. package/package.json +53 -8
  86. package/src/bootstrap.ts +6 -6
  87. package/src/config.ts +26 -0
  88. package/src/core/dataflow.test.ts +166 -0
  89. package/src/core/dataflow.ts +161 -0
  90. package/src/core/log-prune.test.ts +58 -0
  91. package/src/core/log-prune.ts +43 -0
  92. package/src/core/preflight.test.ts +49 -0
  93. package/src/core/preflight.ts +89 -0
  94. package/src/core/run-context.test.ts +244 -0
  95. package/src/core/run-context.ts +207 -0
  96. package/src/core/run-state.test.ts +98 -0
  97. package/src/core/run-state.ts +122 -0
  98. package/src/core/scheduler.test.ts +83 -0
  99. package/src/core/scheduler.ts +42 -0
  100. package/src/core/task-executor.ts +769 -0
  101. package/src/core/trigger-errors.ts +15 -0
  102. package/src/engine-ports-mixed.test.ts +68 -411
  103. package/src/engine-ports.test.ts +37 -341
  104. package/src/engine.ts +80 -1248
  105. package/src/index.ts +28 -0
  106. package/src/pipeline-definition.ts +5 -0
  107. package/src/pipeline-runner.test.ts +5 -9
  108. package/src/pipeline-runner.ts +3 -2
  109. package/src/plugin-registry.test.ts +7 -10
  110. package/src/plugins.ts +18 -0
  111. package/src/ports.test.ts +80 -0
  112. package/src/ports.ts +36 -4
  113. package/src/registry.ts +7 -49
  114. package/src/schema-ports.test.ts +41 -214
  115. package/src/tagma.test.ts +84 -0
  116. package/src/tagma.ts +47 -0
  117. package/src/utils-api.ts +8 -0
  118. package/src/validate-raw-ports.test.ts +80 -393
  119. package/src/validate-raw.ts +93 -137
  120. package/src/yaml.ts +11 -0
  121. package/dist/sdk.d.ts +0 -32
  122. package/dist/sdk.d.ts.map +0 -1
  123. package/dist/sdk.js +0 -41
  124. package/dist/sdk.js.map +0 -1
  125. package/src/sdk.ts +0 -151
@@ -0,0 +1,769 @@
1
+ import { resolve } from 'path';
2
+ import type {
3
+ CompletionPlugin,
4
+ DriverContext,
5
+ DriverPlugin,
6
+ MiddlewareContext,
7
+ MiddlewarePlugin,
8
+ PromptDocument,
9
+ TaskConfig,
10
+ TaskResult,
11
+ TaskStatus,
12
+ TriggerPlugin,
13
+ } from '../types';
14
+ import type { PluginRegistry } from '../registry';
15
+ import { runCommand, runSpawn } from '../runner';
16
+ import { parseDuration, nowISO } from '../utils';
17
+ import {
18
+ promptDocumentFromString,
19
+ serializePromptDocument,
20
+ prependContext,
21
+ renderInputsBlock,
22
+ renderOutputSchemaBlock,
23
+ } from '../prompt-doc';
24
+ import { resolveTaskBindingInputs, resolveTaskInputs, substituteInputs } from '../ports';
25
+ import { executeHook, buildTaskContext } from '../hooks';
26
+ import { clip, tailLines, type Logger } from '../logger';
27
+ import type { ApprovalGateway } from '../approval';
28
+ import type { RunContext } from './run-context';
29
+ import { extractSuccessfulOutputs, inferEffectivePorts } from './dataflow';
30
+ import { TriggerBlockedError, TriggerTimeoutError } from './trigger-errors';
31
+
32
+ const MAX_NORMALIZED_BYTES = 1_000_000;
33
+
34
+ function isPromptTaskConfig(task: {
35
+ readonly prompt?: string;
36
+ readonly command?: string;
37
+ }): task is { readonly prompt: string; readonly command?: undefined } {
38
+ return task.prompt !== undefined && task.command === undefined;
39
+ }
40
+
41
+ function isCommandTaskConfig(task: {
42
+ readonly command?: string;
43
+ readonly prompt?: string;
44
+ }): task is { readonly command: string; readonly prompt?: undefined } {
45
+ return task.command !== undefined && task.prompt === undefined;
46
+ }
47
+
48
+ export interface ExecuteTaskOptions {
49
+ readonly taskId: string;
50
+ readonly ctx: RunContext;
51
+ readonly registry: PluginRegistry;
52
+ readonly log: Logger;
53
+ readonly approvalGateway: ApprovalGateway;
54
+ }
55
+
56
+ export async function executeTask(options: ExecuteTaskOptions): Promise<void> {
57
+ const { taskId, ctx, registry, log, approvalGateway } = options;
58
+ const dag = ctx.dag;
59
+ const config = ctx.config;
60
+ const workDir = ctx.workDir;
61
+ const pipelineInfo = ctx.pipelineInfo;
62
+ const state = ctx.states.get(taskId)!;
63
+ const node = dag.nodes.get(taskId)!;
64
+ const task = node.task;
65
+ const track = node.track;
66
+
67
+ log.section(`Task ${taskId}`, taskId);
68
+ log.debug(
69
+ `[task:${taskId}]`,
70
+ `type=${isPromptTaskConfig(task) ? 'ai' : 'cmd'} track=${track.id} deps=[${node.dependsOn.join(', ') || '(root)'}]`,
71
+ );
72
+
73
+ // 1. Check dependencies
74
+ for (const depId of node.dependsOn) {
75
+ const result = ctx.isDependencySatisfied(depId);
76
+ if (result === 'skip') {
77
+ const depStatus = ctx.states.get(depId)?.status ?? 'unknown';
78
+ log.debug(`[task:${taskId}]`, `skipped (upstream "${depId}" status=${depStatus})`);
79
+ state.finishedAt = nowISO();
80
+ ctx.setTaskStatus(taskId, 'skipped');
81
+ return;
82
+ }
83
+ if (result === 'unsatisfied') return; // still waiting
84
+ }
85
+
86
+ // 2. Check trigger
87
+ if (task.trigger) {
88
+ log.debug(
89
+ `[task:${taskId}]`,
90
+ `trigger wait: type=${task.trigger.type} ${JSON.stringify(task.trigger)}`,
91
+ );
92
+ try {
93
+ const triggerPlugin = registry.getHandler<TriggerPlugin>('triggers', task.trigger.type);
94
+ // R6: race the plugin's watch() against the pipeline's abort signal
95
+ // AND the task-level timeout. Third-party triggers may forget to
96
+ // wire up ctx.signal — without the abort race, an aborted pipeline
97
+ // would hang forever waiting for the plugin's watch promise to
98
+ // resolve. And without the timeout race, a buggy watch() that never
99
+ // settles would ignore the user's `task.timeout` (which the spawn
100
+ // path at step 4 already honours) — a task could wedge the whole
101
+ // pipeline until pipeline-level timeout fires (or forever, if none
102
+ // is set). Honouring task.timeout here makes the two stages
103
+ // symmetric. The cleanup paths in finally never run on the orphaned
104
+ // plugin promise (it's allowed to leak a watcher; the pipeline is
105
+ // being torn down anyway).
106
+ const triggerTimeoutMs = task.timeout ? parseDuration(task.timeout) : 0;
107
+ await new Promise<unknown>((resolve, reject) => {
108
+ let settled = false;
109
+ let timer: ReturnType<typeof setTimeout> | null = null;
110
+ const onAbort = () => {
111
+ if (settled) return;
112
+ settled = true;
113
+ if (timer !== null) clearTimeout(timer);
114
+ reject(new Error('Pipeline aborted'));
115
+ };
116
+ if (ctx.abortController.signal.aborted) {
117
+ onAbort();
118
+ return;
119
+ }
120
+ ctx.abortController.signal.addEventListener('abort', onAbort, { once: true });
121
+ if (triggerTimeoutMs > 0) {
122
+ timer = setTimeout(() => {
123
+ if (settled) return;
124
+ settled = true;
125
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
126
+ reject(
127
+ new TriggerTimeoutError(
128
+ `Trigger "${task.trigger!.type}" did not settle within ${task.timeout} (task-level timeout)`,
129
+ ),
130
+ );
131
+ }, triggerTimeoutMs);
132
+ }
133
+ triggerPlugin
134
+ .watch(task.trigger as Record<string, unknown>, {
135
+ taskId: node.taskId,
136
+ trackId: track.id,
137
+ workDir: task.cwd ?? workDir,
138
+ signal: ctx.abortController.signal,
139
+ approvalGateway,
140
+ })
141
+ .then(
142
+ (v) => {
143
+ if (settled) return;
144
+ settled = true;
145
+ if (timer !== null) clearTimeout(timer);
146
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
147
+ resolve(v);
148
+ },
149
+ (e) => {
150
+ if (settled) return;
151
+ settled = true;
152
+ if (timer !== null) clearTimeout(timer);
153
+ ctx.abortController.signal.removeEventListener('abort', onAbort);
154
+ reject(e);
155
+ },
156
+ );
157
+ });
158
+ log.debug(`[task:${taskId}]`, `trigger fired`);
159
+ } catch (err: unknown) {
160
+ // If pipeline was aborted while we were still waiting for the trigger,
161
+ // this task never entered running state → skipped, not timeout.
162
+ state.finishedAt = nowISO();
163
+ if (ctx.abortReason !== null) {
164
+ ctx.setTaskStatus(taskId, 'skipped');
165
+ } else if (err instanceof TriggerBlockedError) {
166
+ ctx.setTaskStatus(taskId, 'blocked'); // user/policy rejection
167
+ } else if (err instanceof TriggerTimeoutError) {
168
+ ctx.setTaskStatus(taskId, 'timeout'); // genuine trigger wait timeout
169
+ } else {
170
+ // A7 fallback: also check message strings for backward-compat with
171
+ // third-party trigger plugins that don't throw typed errors yet.
172
+ const msg = err instanceof Error ? err.message : String(err);
173
+ if (msg.includes('rejected') || msg.includes('denied')) {
174
+ ctx.setTaskStatus(taskId, 'blocked');
175
+ } else if (msg.includes('timeout')) {
176
+ ctx.setTaskStatus(taskId, 'timeout');
177
+ } else {
178
+ ctx.setTaskStatus(taskId, 'failed'); // plugin error, watcher crash, etc.
179
+ }
180
+ }
181
+ try {
182
+ await ctx.fireHook(taskId, 'task_failure');
183
+ } catch (hookErr) {
184
+ log.error(
185
+ `[task:${taskId}]`,
186
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
187
+ );
188
+ }
189
+ return;
190
+ }
191
+ }
192
+
193
+ // 3. task_start hook (gate)
194
+ const hookResult = await executeHook(
195
+ config.hooks,
196
+ 'task_start',
197
+ buildTaskContext(
198
+ 'task_start',
199
+ pipelineInfo,
200
+ ctx.trackInfoOf(taskId),
201
+ ctx.buildTaskInfoObj(taskId),
202
+ ),
203
+ workDir,
204
+ ctx.abortController.signal,
205
+ );
206
+ if (hookResult.exitCode !== 0 || config.hooks?.task_start) {
207
+ log.debug(
208
+ `[task:${taskId}]`,
209
+ `task_start hook exit=${hookResult.exitCode} allowed=${hookResult.allowed}`,
210
+ );
211
+ }
212
+ if (!hookResult.allowed) {
213
+ state.finishedAt = nowISO();
214
+ ctx.setTaskStatus(taskId, 'blocked');
215
+ try {
216
+ await ctx.fireHook(taskId, 'task_failure');
217
+ } catch (hookErr) {
218
+ log.error(
219
+ `[task:${taskId}]`,
220
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
221
+ );
222
+ }
223
+ return;
224
+ }
225
+
226
+ // 3.5. Resolve port inputs from upstream outputs. This is the last
227
+ // gate before execution: missing-required inputs block the task
228
+ // without ever spawning a process, so the caller sees a clear
229
+ // "blocked: missing input X" rather than a cryptic runtime error
230
+ // from a command that expanded a placeholder to the empty string.
231
+ // Resolution runs even for tasks that declare no ports — the call
232
+ // is cheap and returns `{kind: 'ready', inputs: {}}` in that case,
233
+ // which downstream code handles uniformly.
234
+ //
235
+ // Prompt Tasks have no declared ports — their I/O contract is
236
+ // inferred from direct-neighbor Command Tasks (see ports.ts:
237
+ // `inferPromptPorts`). We synthesize a `TaskPorts` object and
238
+ // feed it into the same resolve/substitute/render/extract
239
+ // pipeline the Command path uses. Collisions that a Prompt can't
240
+ // disambiguate (same input name on two upstreams, incompatible
241
+ // downstream output types) block the task with a clear message.
242
+ const effectivePortsResult = inferEffectivePorts(ctx, taskId);
243
+
244
+ if (effectivePortsResult.kind === 'blocked') {
245
+ log.error(
246
+ `[task:${taskId}]`,
247
+ `blocked — prompt port inference failed:\n${effectivePortsResult.reason}`,
248
+ );
249
+ state.result = {
250
+ exitCode: -1,
251
+ stdout: '',
252
+ stderr: `[engine] prompt port inference failed:\n${effectivePortsResult.reason}`,
253
+ stdoutPath: null,
254
+ stderrPath: null,
255
+ durationMs: 0,
256
+ sessionId: null,
257
+ normalizedOutput: null,
258
+ failureKind: 'spawn_error',
259
+ outputs: null,
260
+ };
261
+ state.finishedAt = nowISO();
262
+ ctx.setTaskStatus(taskId, 'blocked');
263
+ try {
264
+ await ctx.fireHook(taskId, 'task_failure');
265
+ } catch (hookErr) {
266
+ log.error(
267
+ `[task:${taskId}]`,
268
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
269
+ );
270
+ }
271
+ if (ctx.getOnFailure(taskId) === 'stop_all') ctx.applyStopAll();
272
+ return;
273
+ }
274
+ const isPromptTask = effectivePortsResult.isPromptTask;
275
+ const effectivePorts = effectivePortsResult.effectivePorts;
276
+
277
+ const bindingResolution = resolveTaskBindingInputs(task, ctx.bindingDataMap, node.dependsOn);
278
+ if (bindingResolution.kind === 'blocked') {
279
+ log.error(
280
+ `[task:${taskId}]`,
281
+ `blocked — cannot resolve task input bindings:\n${bindingResolution.reason}`,
282
+ );
283
+ state.result = {
284
+ exitCode: -1,
285
+ stdout: '',
286
+ stderr: `[engine] task input binding resolution failed:\n${bindingResolution.reason}`,
287
+ stdoutPath: null,
288
+ stderrPath: null,
289
+ durationMs: 0,
290
+ sessionId: null,
291
+ normalizedOutput: null,
292
+ failureKind: 'spawn_error',
293
+ outputs: null,
294
+ };
295
+ state.finishedAt = nowISO();
296
+ ctx.setTaskStatus(taskId, 'blocked');
297
+ try {
298
+ await ctx.fireHook(taskId, 'task_failure');
299
+ } catch (hookErr) {
300
+ log.error(
301
+ `[task:${taskId}]`,
302
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
303
+ );
304
+ }
305
+ if (ctx.getOnFailure(taskId) === 'stop_all') ctx.applyStopAll();
306
+ return;
307
+ }
308
+ if (bindingResolution.missingOptional.length > 0) {
309
+ log.debug(
310
+ `[task:${taskId}]`,
311
+ `optional input bindings unresolved (empty in placeholders): ${bindingResolution.missingOptional.join(', ')}`,
312
+ );
313
+ }
314
+
315
+ let inferredPromptInputs: Readonly<Record<string, unknown>> = {};
316
+ if (isPromptTask && effectivePorts?.inputs && effectivePorts.inputs.length > 0) {
317
+ const inputResolution = resolveTaskInputs(
318
+ { ...task, ports: effectivePorts },
319
+ ctx.outputValuesMap,
320
+ node.dependsOn,
321
+ );
322
+ if (inputResolution.kind === 'blocked') {
323
+ log.error(
324
+ `[task:${taskId}]`,
325
+ `blocked — cannot resolve inferred prompt inputs:\n${inputResolution.reason}`,
326
+ );
327
+ state.result = {
328
+ exitCode: -1,
329
+ stdout: '',
330
+ stderr: `[engine] inferred prompt input resolution failed:\n${inputResolution.reason}`,
331
+ stdoutPath: null,
332
+ stderrPath: null,
333
+ durationMs: 0,
334
+ sessionId: null,
335
+ normalizedOutput: null,
336
+ failureKind: 'spawn_error',
337
+ outputs: null,
338
+ };
339
+ state.finishedAt = nowISO();
340
+ ctx.setTaskStatus(taskId, 'blocked');
341
+ try {
342
+ await ctx.fireHook(taskId, 'task_failure');
343
+ } catch (hookErr) {
344
+ log.error(
345
+ `[task:${taskId}]`,
346
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
347
+ );
348
+ }
349
+ if (ctx.getOnFailure(taskId) === 'stop_all') ctx.applyStopAll();
350
+ return;
351
+ }
352
+ inferredPromptInputs = inputResolution.inputs;
353
+ }
354
+
355
+ const resolvedInputs = { ...inferredPromptInputs, ...bindingResolution.inputs };
356
+ ctx.resolvedInputsMap.set(taskId, resolvedInputs);
357
+ if (effectivePorts?.inputs && effectivePorts.inputs.length > 0) {
358
+ log.debug(
359
+ `[task:${taskId}]`,
360
+ `resolved inputs: ${JSON.stringify(resolvedInputs)}` +
361
+ (isPromptTask ? ' (inferred from upstream Commands)' : ''),
362
+ );
363
+ }
364
+
365
+ // 4. Mark running — set startedAt before emitting so subscribers see a
366
+ // complete task_update (startedAt non-null) on the status transition.
367
+ state.startedAt = nowISO();
368
+ ctx.setTaskStatus(taskId, 'running');
369
+ log.info(
370
+ `[task:${taskId}]`,
371
+ isCommandTaskConfig(task) ? `running: ${task.command}` : `running (driver task)`,
372
+ );
373
+
374
+ // File-only: resolved config for this task
375
+ const resolvedDriver = task.driver ?? track.driver ?? config.driver ?? 'opencode';
376
+ const resolvedModel = task.model ?? track.model ?? config.model ?? '(default)';
377
+ const resolvedPerms = task.permissions ?? track.permissions ?? '(default)';
378
+ const resolvedCwd = task.cwd ?? track.cwd ?? workDir;
379
+ log.debug(
380
+ `[task:${taskId}]`,
381
+ `resolved: driver=${resolvedDriver} model=${resolvedModel} cwd=${resolvedCwd}`,
382
+ );
383
+ log.debug(`[task:${taskId}]`, `permissions: ${JSON.stringify(resolvedPerms)}`);
384
+ if (task.continue_from) {
385
+ log.debug(`[task:${taskId}]`, `continue_from: "${task.continue_from}"`);
386
+ }
387
+ if (task.timeout) {
388
+ log.debug(`[task:${taskId}]`, `timeout: ${task.timeout}`);
389
+ }
390
+
391
+ try {
392
+ let result: TaskResult;
393
+ const timeoutMs = task.timeout ? parseDuration(task.timeout) : undefined;
394
+
395
+ // Stream child stdout/stderr directly to disk in the logger's run dir
396
+ // and keep only a bounded tail in the returned TaskResult. Filenames
397
+ // mirror the existing `.stderr` naming — dots in task ids are replaced
398
+ // so hierarchical ids (e.g. `track1.task2`) map cleanly to a flat dir.
399
+ const fsSafeTaskId = taskId.replace(/\./g, '_');
400
+ const stdoutPath = resolve(log.dir, `${fsSafeTaskId}.stdout`);
401
+ const stderrPath = resolve(log.dir, `${fsSafeTaskId}.stderr`);
402
+ const runOpts = {
403
+ timeoutMs,
404
+ signal: ctx.abortController.signal,
405
+ stdoutPath,
406
+ stderrPath,
407
+ };
408
+
409
+ if (isCommandTaskConfig(task)) {
410
+ // Substitute `{{inputs.X}}` placeholders into the command
411
+ // string. Tasks with no declared inputs always produce the same
412
+ // string back (no placeholders to match). Unresolved references
413
+ // render empty — validate-raw flags undeclared references as
414
+ // errors, so the only way to land here with an unresolved is an
415
+ // optional input that had no upstream producer and no default,
416
+ // which we surface in the log.
417
+ const { text: expandedCommand, unresolved } = substituteInputs(task.command, resolvedInputs);
418
+ if (unresolved.length > 0) {
419
+ log.debug(
420
+ `[task:${taskId}]`,
421
+ `command placeholders rendered empty: ${unresolved.join(', ')}`,
422
+ );
423
+ }
424
+ log.debug(`[task:${taskId}]`, `command: ${expandedCommand}`);
425
+ result = await runCommand(expandedCommand, task.cwd ?? workDir, runOpts);
426
+ } else {
427
+ // AI task: apply middleware chain against a structured PromptDocument.
428
+ const driverName = task.driver ?? track.driver ?? config.driver ?? 'opencode';
429
+ const driver = registry.getHandler<DriverPlugin>('drivers', driverName);
430
+
431
+ // Substitute placeholders in the user-authored prompt before
432
+ // wrapping into a PromptDocument so middlewares see the
433
+ // already-resolved task text.
434
+ const { text: expandedPrompt, unresolved } = substituteInputs(task.prompt!, resolvedInputs);
435
+ if (unresolved.length > 0) {
436
+ log.debug(
437
+ `[task:${taskId}]`,
438
+ `prompt placeholders rendered empty: ${unresolved.join(', ')}`,
439
+ );
440
+ }
441
+ const originalLen = expandedPrompt.length;
442
+ let doc: PromptDocument = promptDocumentFromString(expandedPrompt);
443
+ // Prepend port-related context blocks so the model sees them
444
+ // before any middleware-added retrieval / memory blocks. Order
445
+ // matters: [Output Format] first (sets the deliverable), then
446
+ // [Inputs] (the concrete data to operate on). Empty blocks are
447
+ // filtered out — tasks without ports get no extra blocks at all.
448
+ const outputFormatBlock = renderOutputSchemaBlock(effectivePorts?.outputs);
449
+ if (outputFormatBlock) {
450
+ doc = prependContext(doc, outputFormatBlock);
451
+ }
452
+ const inputsBlock = renderInputsBlock(effectivePorts?.inputs, resolvedInputs);
453
+ if (inputsBlock) {
454
+ doc = prependContext(doc, inputsBlock);
455
+ }
456
+ const mws = task.middlewares !== undefined ? task.middlewares : track.middlewares;
457
+ if (mws && mws.length > 0) {
458
+ log.debug(`[task:${taskId}]`, `middleware chain: ${mws.map((m) => m.type).join(' → ')}`);
459
+ const mwCtx: MiddlewareContext = {
460
+ task,
461
+ track,
462
+ workDir: task.cwd ?? workDir,
463
+ };
464
+ for (const mwConfig of mws) {
465
+ const mwPlugin = registry.getHandler<MiddlewarePlugin>('middlewares', mwConfig.type);
466
+ const beforeBlocks = doc.contexts.length;
467
+ const beforeLen = serializePromptDocument(doc).length;
468
+
469
+ // Prefer the structured API. Fall back to the legacy
470
+ // `enhance(string) → string` path so v0.x plugins keep
471
+ // working — that fallback loses context structure (the
472
+ // middleware's output becomes the new task body) but never
473
+ // silently drops content.
474
+ if (typeof mwPlugin.enhanceDoc === 'function') {
475
+ const next = await mwPlugin.enhanceDoc(doc, mwConfig as Record<string, unknown>, mwCtx);
476
+ if (
477
+ !next ||
478
+ typeof next !== 'object' ||
479
+ !Array.isArray((next as PromptDocument).contexts) ||
480
+ typeof (next as PromptDocument).task !== 'string'
481
+ ) {
482
+ throw new Error(
483
+ `middleware "${mwConfig.type}".enhanceDoc() returned a malformed PromptDocument`,
484
+ );
485
+ }
486
+ doc = next as PromptDocument;
487
+ } else if (typeof mwPlugin.enhance === 'function') {
488
+ const asString = serializePromptDocument(doc);
489
+ const next = await mwPlugin.enhance(
490
+ asString,
491
+ mwConfig as Record<string, unknown>,
492
+ mwCtx,
493
+ );
494
+ // R3: a middleware that returns undefined / null / a non-string
495
+ // would silently corrupt the prompt. Fail loud.
496
+ if (typeof next !== 'string') {
497
+ throw new Error(
498
+ `middleware "${mwConfig.type}".enhance() returned ${next === null ? 'null' : typeof next}, expected string`,
499
+ );
500
+ }
501
+ // Legacy fallback: collapse the returned string into a
502
+ // fresh doc. Earlier structure is folded into the string
503
+ // (serializePromptDocument just ran), so bytes the driver
504
+ // sees match the old string pipeline.
505
+ doc = { contexts: [], task: next };
506
+ } else {
507
+ throw new Error(
508
+ `middleware "${mwConfig.type}" provides neither enhanceDoc nor enhance`,
509
+ );
510
+ }
511
+ const afterLen = serializePromptDocument(doc).length;
512
+ const addedBlocks = doc.contexts.length - beforeBlocks;
513
+ log.debug(
514
+ `[task:${taskId}]`,
515
+ ` ${mwConfig.type}: ${beforeLen} → ${afterLen} chars` +
516
+ (addedBlocks > 0
517
+ ? ` (+${addedBlocks} context block${addedBlocks > 1 ? 's' : ''})`
518
+ : ''),
519
+ );
520
+ }
521
+ }
522
+ const prompt = serializePromptDocument(doc);
523
+ log.debug(
524
+ `[task:${taskId}]`,
525
+ `prompt: ${originalLen} chars (final: ${prompt.length} chars, ${doc.contexts.length} block${doc.contexts.length === 1 ? '' : 's'})`,
526
+ );
527
+ log.quiet(`--- prompt (final) ---\n${clip(prompt)}\n--- end prompt ---`, taskId);
528
+
529
+ // H1: hand the driver a continue_from that has already been
530
+ // qualified by dag.ts. Without this, drivers like codex/opencode/
531
+ // claude-code look up maps directly with
532
+ // the user's raw (possibly bare) string, which races whenever two
533
+ // tracks share a task name. dag.ts has the only authoritative
534
+ // resolver, so we use its precomputed answer here.
535
+ // Drivers key sessionMap/normalizedMap by fully-qualified id. buildDag
536
+ // guarantees `resolvedContinueFrom` is set for every task that has a
537
+ // `continue_from`, so if we see the bare form here something upstream
538
+ // is broken — fail loud instead of silently miskeying the lookup.
539
+ if (task.continue_from && !node.resolvedContinueFrom) {
540
+ throw new Error(
541
+ `Internal: task "${taskId}" has continue_from "${task.continue_from}" ` +
542
+ `but no resolvedContinueFrom. buildDag should have qualified it.`,
543
+ );
544
+ }
545
+ const enrichedTask: TaskConfig = {
546
+ ...task,
547
+ prompt,
548
+ continue_from: node.resolvedContinueFrom,
549
+ };
550
+ const driverCtx: DriverContext = {
551
+ sessionMap: ctx.sessionMap,
552
+ normalizedMap: ctx.normalizedMap,
553
+ workDir: task.cwd ?? workDir,
554
+ // Structured view for drivers that want fine-grained control
555
+ // over serialization (e.g. inserting [Previous Output] between
556
+ // contexts and task). Drivers that read task.prompt see the
557
+ // default serialization and need no changes.
558
+ promptDoc: doc,
559
+ // Resolved input values keyed by input name. Typed bindings have
560
+ // already been coerced when a binding declares `type`.
561
+ inputs: resolvedInputs,
562
+ };
563
+ const spec = await driver.buildCommand(enrichedTask, track, driverCtx);
564
+ log.debug(`[task:${taskId}]`, `driver=${driverName}`);
565
+ log.debug(`[task:${taskId}]`, `spawn args: ${JSON.stringify(spec.args)}`);
566
+ if (spec.cwd) log.debug(`[task:${taskId}]`, `spawn cwd: ${spec.cwd}`);
567
+ if (spec.env)
568
+ log.debug(`[task:${taskId}]`, `spawn env overrides: ${Object.keys(spec.env).join(', ')}`);
569
+ if (spec.stdin) log.debug(`[task:${taskId}]`, `spawn stdin: ${spec.stdin.length} chars`);
570
+ result = await runSpawn(spec, driver, runOpts);
571
+ }
572
+
573
+ // 6. Determine terminal status (without emitting yet — result must be complete first)
574
+ // H2: branch on failureKind so spawn errors no longer masquerade as
575
+ // timeouts. Old runners that don't set failureKind still work — we
576
+ // fall back to the historical `exitCode === -1 → timeout` heuristic so
577
+ // pre-existing third-party drivers don't regress.
578
+ let terminalStatus: TaskStatus;
579
+ const kind = result.failureKind;
580
+ if (kind === 'timeout') {
581
+ terminalStatus = 'timeout';
582
+ } else if (kind === 'spawn_error') {
583
+ terminalStatus = 'failed';
584
+ } else if (kind === undefined && result.exitCode === -1) {
585
+ // Legacy path: pre-H2 driver returned -1 with no kind. Treat as
586
+ // timeout for backward compatibility (the previous behaviour).
587
+ terminalStatus = 'timeout';
588
+ } else if (result.exitCode !== 0) {
589
+ terminalStatus = 'failed';
590
+ } else if (task.completion) {
591
+ const plugin = registry.getHandler<CompletionPlugin>('completions', task.completion.type);
592
+ const completionCtx = { workDir: task.cwd ?? workDir, signal: ctx.abortController.signal };
593
+ const passed = await plugin.check(
594
+ task.completion as Record<string, unknown>,
595
+ result,
596
+ completionCtx,
597
+ );
598
+ // R4: strict boolean check. Truthy strings/numbers used to be coerced
599
+ // to success — a check returning "ok" would let a failing task pass.
600
+ if (typeof passed !== 'boolean') {
601
+ throw new Error(
602
+ `completion "${task.completion.type}".check() returned ${passed === null ? 'null' : typeof passed}, expected boolean`,
603
+ );
604
+ }
605
+ terminalStatus = passed ? 'success' : 'failed';
606
+ } else {
607
+ terminalStatus = 'success';
608
+ }
609
+
610
+ // Extract declared outputs from the task's output stream. Only
611
+ // meaningful on success — a failed task's output is whatever the
612
+ // child happened to emit before exiting, and downstream tasks
613
+ // shouldn't receive partial data.
614
+ let extractedOutputs: Readonly<Record<string, unknown>> | null = null;
615
+ if (terminalStatus === 'success') {
616
+ const outputExtraction = extractSuccessfulOutputs({
617
+ task,
618
+ effectivePorts,
619
+ result,
620
+ });
621
+ extractedOutputs = outputExtraction.outputs;
622
+ if (task.outputs && Object.keys(task.outputs).length > 0) {
623
+ log.debug(
624
+ `[task:${taskId}]`,
625
+ `extracted binding outputs: ${JSON.stringify(extractedOutputs ?? {})}`,
626
+ );
627
+ if (outputExtraction.bindingDiagnostic) {
628
+ log.debug(`[task:${taskId}]`, outputExtraction.bindingDiagnostic);
629
+ const note = `\n[engine] ${outputExtraction.bindingDiagnostic}`;
630
+ result = { ...result, stderr: result.stderr + note };
631
+ }
632
+ }
633
+
634
+ if (effectivePorts?.outputs && effectivePorts.outputs.length > 0) {
635
+ log.debug(
636
+ `[task:${taskId}]`,
637
+ `extracted outputs: ${JSON.stringify(extractedOutputs ?? {})}` +
638
+ (isPromptTask ? ' (inferred from downstream Commands)' : ''),
639
+ );
640
+ if (outputExtraction.portDiagnostic) {
641
+ log.error(`[task:${taskId}]`, outputExtraction.portDiagnostic);
642
+ const note = `\n[engine] ${outputExtraction.portDiagnostic}`;
643
+ result = { ...result, stderr: result.stderr + note };
644
+ }
645
+ }
646
+ }
647
+ // Attach outputs to the result (null when task has no declared
648
+ // outputs or extraction failed entirely). Consumers of TaskResult
649
+ // — hooks, wire events, test assertions — all go through this
650
+ // one field rather than re-running extraction.
651
+ result = { ...result, outputs: extractedOutputs };
652
+ if (extractedOutputs !== null) {
653
+ ctx.outputValuesMap.set(taskId, extractedOutputs);
654
+ }
655
+ ctx.bindingDataMap.set(taskId, {
656
+ outputs: extractedOutputs,
657
+ stdout: result.stdout,
658
+ stderr: result.stderr,
659
+ normalizedOutput: result.normalizedOutput,
660
+ exitCode: result.exitCode,
661
+ });
662
+
663
+ // Store normalized text separately (in-memory) for continue_from handoff.
664
+ // R15: clip oversized values so a runaway parseResult can't accumulate
665
+ // hundreds of MB across tasks.
666
+ if (result.normalizedOutput !== null) {
667
+ const clipped =
668
+ result.normalizedOutput.length > MAX_NORMALIZED_BYTES
669
+ ? result.normalizedOutput.slice(0, MAX_NORMALIZED_BYTES) +
670
+ `\n[…clipped at ${MAX_NORMALIZED_BYTES} bytes]`
671
+ : result.normalizedOutput;
672
+ ctx.normalizedMap.set(taskId, clipped);
673
+ }
674
+
675
+ // Note: stderr is already persisted by runner.ts as it streams; the
676
+ // old "write full string after the fact" block is gone — that's what
677
+ // the streaming rewrite fixed (unbounded in-memory buffering).
678
+
679
+ if (result.sessionId) {
680
+ // H1: qualified-only key.
681
+ ctx.sessionMap.set(taskId, result.sessionId);
682
+ }
683
+
684
+ // Set result and finishedAt before emitting terminal status so listeners see complete state
685
+ state.result = result;
686
+ state.finishedAt = nowISO();
687
+ ctx.setTaskStatus(taskId, terminalStatus);
688
+
689
+ // Log task outcome with relevant details
690
+ const durSec = (result.durationMs / 1000).toFixed(1);
691
+ if (terminalStatus === 'success') {
692
+ log.info(`[task:${taskId}]`, `success (${durSec}s)`);
693
+ } else {
694
+ log.error(
695
+ `[task:${taskId}]`,
696
+ `${terminalStatus} exit=${result.exitCode} duration=${durSec}s`,
697
+ );
698
+ if (result.stderr) {
699
+ const tail = tailLines(result.stderr, 10);
700
+ log.error(`[task:${taskId}]`, `stderr tail:\n${tail}`);
701
+ }
702
+ }
703
+
704
+ // File-only: byte counts (prefer full totals from the runner over the
705
+ // bounded tail length so oversized outputs show their real size) +
706
+ // paths to the on-disk full copies.
707
+ const stdoutSize = result.stdoutBytes ?? result.stdout.length;
708
+ const stderrSize = result.stderrBytes ?? result.stderr.length;
709
+ log.debug(`[task:${taskId}]`, `stdout: ${stdoutSize} bytes, stderr: ${stderrSize} bytes`);
710
+ if (result.sessionId) {
711
+ log.debug(`[task:${taskId}]`, `sessionId: ${result.sessionId}`);
712
+ }
713
+ if (result.stdoutPath) {
714
+ log.debug(`[task:${taskId}]`, `wrote stdout: ${result.stdoutPath}`);
715
+ }
716
+ if (result.stderrPath) {
717
+ log.debug(`[task:${taskId}]`, `wrote stderr: ${result.stderrPath}`);
718
+ }
719
+ if (result.stdout) {
720
+ log.quiet(`--- stdout (${taskId}) ---\n${clip(result.stdout)}\n--- end stdout ---`, taskId);
721
+ }
722
+ if (result.stderr) {
723
+ log.quiet(`--- stderr (${taskId}) ---\n${clip(result.stderr)}\n--- end stderr ---`, taskId);
724
+ }
725
+ if (task.completion) {
726
+ log.debug(
727
+ `[task:${taskId}]`,
728
+ `completion check: type=${task.completion.type} result=${terminalStatus}`,
729
+ );
730
+ }
731
+ } catch (err: unknown) {
732
+ const errMsg = err instanceof Error ? (err.stack ?? err.message) : String(err);
733
+ log.error(`[task:${taskId}]`, `failed before execution: ${errMsg}`);
734
+ state.result = {
735
+ exitCode: -1,
736
+ stdout: '',
737
+ stderr: errMsg,
738
+ stdoutPath: null,
739
+ stderrPath: null,
740
+ stdoutBytes: 0,
741
+ stderrBytes: errMsg.length,
742
+ durationMs: 0,
743
+ sessionId: null,
744
+ normalizedOutput: null,
745
+ // H2: Engine-level pre-execution errors (driver throw, middleware
746
+ // throw, getHandler 404) classify as spawn_error — the process never
747
+ // ran, so calling them "timeout" was actively misleading.
748
+ failureKind: 'spawn_error',
749
+ };
750
+ state.finishedAt = nowISO();
751
+ ctx.setTaskStatus(taskId, 'failed');
752
+ }
753
+
754
+ // 7. Fire hooks
755
+ const finalStatus: TaskStatus = state.status;
756
+ try {
757
+ await ctx.fireHook(taskId, finalStatus === 'success' ? 'task_success' : 'task_failure');
758
+ } catch (hookErr) {
759
+ log.error(
760
+ `[task:${taskId}]`,
761
+ `hook execution failed: ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`,
762
+ );
763
+ }
764
+
765
+ // 8. Handle stop_all for failure states
766
+ if (finalStatus !== 'success' && ctx.getOnFailure(taskId) === 'stop_all') {
767
+ ctx.applyStopAll();
768
+ }
769
+ }