owenloop 0.5.7 → 0.5.9

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 (111) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +7 -8
  3. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  4. package/dist/packages/work/src/agent/capability-model.js +94 -91
  5. package/dist/packages/work/src/agent/loop.d.ts +55 -26
  6. package/dist/packages/work/src/agent/loop.js +144 -50
  7. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +206 -35
  11. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  12. package/dist/packages/work/src/exec/receipt.js +6 -6
  13. package/dist/packages/work/src/harness/child-env.js +4 -5
  14. package/dist/packages/work/src/harness/claude.js +100 -0
  15. package/dist/packages/work/src/harness/codex.js +3 -4
  16. package/dist/packages/work/src/harness/session-store.d.ts +63 -3
  17. package/dist/packages/work/src/harness/session-store.js +104 -9
  18. package/dist/packages/work/src/hub/client.d.ts +19 -4
  19. package/dist/packages/work/src/hub/client.js +7 -3
  20. package/dist/packages/work/src/hub/types.d.ts +87 -3
  21. package/dist/packages/work/src/main.js +1 -0
  22. package/dist/packages/work/src/roles/agent-run.js +46 -43
  23. package/dist/packages/work/src/roles/exec.js +2 -0
  24. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  25. package/dist/packages/work/src/roles/sessions.js +9 -2
  26. package/dist/packages/work/src/roles/settings.js +3 -1
  27. package/dist/packages/work/src/roles/shift.js +14 -2
  28. package/dist/packages/work/src/roles/util.d.ts +1 -0
  29. package/dist/packages/work/src/roles/util.js +10 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  31. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  32. package/dist/packages/work/src/settings/roster.d.ts +105 -0
  33. package/dist/packages/work/src/settings/roster.js +439 -0
  34. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  35. package/dist/packages/work/src/settings/serving.js +79 -0
  36. package/dist/packages/work/src/settings/settings.d.ts +25 -24
  37. package/dist/packages/work/src/settings/settings.js +29 -33
  38. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  39. package/dist/packages/work/src/shift/loop.js +299 -51
  40. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  41. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  42. package/dist/packages/work/src/shift/runtime.js +95 -13
  43. package/dist/packages/work/src/shift/server.js +2 -0
  44. package/dist/packages/work/src/shift/spawn.d.ts +18 -50
  45. package/dist/packages/work/src/shift/spawn.js +30 -65
  46. package/dist/packages/work/src/shift/state.d.ts +29 -2
  47. package/dist/packages/work/src/shift/state.js +45 -15
  48. package/dist/packages/work/src/usage.d.ts +1 -1
  49. package/dist/packages/work/src/usage.js +10 -5
  50. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  51. package/dist/packages/work/src/util/modifier-init.js +73 -0
  52. package/dist/src/bundle/tar.d.ts +9 -4
  53. package/dist/src/bundle/tar.js +9 -4
  54. package/dist/src/capabilities.d.ts +50 -0
  55. package/dist/src/capabilities.js +38 -0
  56. package/dist/src/cli.d.ts +15 -1
  57. package/dist/src/cli.js +1099 -32
  58. package/dist/src/config-dir.d.ts +14 -19
  59. package/dist/src/config-dir.js +16 -24
  60. package/dist/src/credentials.d.ts +1 -1
  61. package/dist/src/credentials.js +1 -1
  62. package/dist/src/crypto/index.d.ts +1 -1
  63. package/dist/src/crypto/index.js +1 -1
  64. package/dist/src/crypto/org-root.d.ts +30 -12
  65. package/dist/src/crypto/org-root.js +162 -14
  66. package/dist/src/crypto/records.d.ts +3 -0
  67. package/dist/src/crypto/records.js +8 -0
  68. package/dist/src/crypto/trust-roots.d.ts +2 -2
  69. package/dist/src/crypto/trust-roots.js +2 -2
  70. package/dist/src/defs.d.ts +6 -1
  71. package/dist/src/defs.js +203 -8
  72. package/dist/src/engine.d.ts +55 -6
  73. package/dist/src/engine.js +172 -22
  74. package/dist/src/global-config.d.ts +4 -7
  75. package/dist/src/global-config.js +4 -7
  76. package/dist/src/hub.d.ts +207 -5
  77. package/dist/src/hub.js +263 -3
  78. package/dist/src/index.d.ts +5 -5
  79. package/dist/src/index.js +3 -3
  80. package/dist/src/mcp/serve.d.ts +22 -0
  81. package/dist/src/mcp/serve.js +88 -8
  82. package/dist/src/model.d.ts +2 -0
  83. package/dist/src/model.js +32 -25
  84. package/dist/src/order-resolver.d.ts +1 -0
  85. package/dist/src/order-resolver.js +8 -1
  86. package/dist/src/schemas/index.d.ts +19 -0
  87. package/dist/src/schemas/order.v1.schema.json +13 -2
  88. package/dist/src/store/pre-commit-verifier.js +1 -1
  89. package/dist/src/store.d.ts +5 -0
  90. package/dist/src/store.js +43 -8
  91. package/dist/src/types.d.ts +64 -7
  92. package/dist/src/work-settings.d.ts +2 -4
  93. package/dist/src/work-settings.js +2 -4
  94. package/docs/agent-runner.md +2 -2
  95. package/docs/authoring.md +90 -2
  96. package/docs/bundles.md +29 -3
  97. package/docs/cli.md +456 -120
  98. package/docs/crypto.md +32 -16
  99. package/docs/design.md +70 -1
  100. package/docs/routing.md +762 -0
  101. package/docs/shift-logs.md +37 -10
  102. package/docs/wire-contracts.md +50 -7
  103. package/examples/workflows/delivery.yaml +31 -14
  104. package/examples/workflows/ship.yaml +10 -2
  105. package/package.json +1 -1
  106. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  107. package/plugins/claude-code/plugin/.mcp.json +1 -1
  108. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  109. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  110. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  111. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
@@ -19,13 +19,12 @@
19
19
  * misroute, and no child process is started.
20
20
  * 3. RUN + RACE — the runner shells the command out while the lease loop runs.
21
21
  * Whichever settles first wins (plan decision 9):
22
- * - an ordinary command settles (any exit code, or a machinery error) ⇒
23
- * build a receipt. A payload reject is delivered FIRST (the hub refuses
24
- * a reject once the claim has closed, and the last owed submit is what
25
- * closes it); then `submit` the receipt to every owed path, unless that
26
- * reject closed the run, in which case the owed paths stay debts. Exit 0
27
- * means the receipt/reject delivery won; the receipt's exit code still
28
- * carries the command result.
22
+ * - an ordinary command settles ⇒ build a receipt. A payload reject is
23
+ * delivered FIRST (the hub refuses a reject once the claim has closed,
24
+ * and the last owed submit is what closes it). A successful command
25
+ * submits that receipt to every owed path; a failed command raises an
26
+ * operator question with the receipt as diagnostic context and submits
27
+ * nothing.
29
28
  * - a judge command exits 0 ⇒ submit its receipt; a non-zero exit ⇒ send
30
29
  * `reject` for `order.judge` without a receipt; signal or machinery
31
30
  * failure ⇒ no verdict, leave the claim for the reap path.
@@ -72,6 +71,48 @@ export const CONSUMES_INLINE_MAX_BYTES = 65_536;
72
71
  function errMsg(e) {
73
72
  return e instanceof Error ? e.message : String(e);
74
73
  }
74
+ /**
75
+ * The one predicate that decides both how child output is logged and whether
76
+ * its receipt may be submitted.
77
+ *
78
+ * runner.ts reports a signalled child with `exitCode: null`, so a separate
79
+ * signal check is unnecessary.
80
+ */
81
+ function commandSucceeded(result) {
82
+ return result.exitCode === 0 && result.error === undefined;
83
+ }
84
+ /** How a command failed, as an English predicate. */
85
+ function describeCommandFailure(result) {
86
+ if (result.error !== undefined)
87
+ return `could not be run (${result.error})`;
88
+ if (result.signal !== undefined)
89
+ return `was killed by ${result.signal}`;
90
+ return `exited ${result.exitCode}`;
91
+ }
92
+ /**
93
+ * Append the child's captured output to a payload reject reason when it gives
94
+ * the consumer diagnosis that the script's one-line reason cannot.
95
+ *
96
+ * A reject consumer receives only this text. The same `outputTail` already
97
+ * reaches the worker log through `relayChildOutput` and the receipt through
98
+ * `receipt.ts`, but a step that consumes a rejected artifact sees neither:
99
+ * a delivery builder otherwise learns only that local checks failed. Matching
100
+ * `relayChildOutput`'s trailing-newline trim makes the log and reject carry
101
+ * identical bytes, while the label prevents the child's words from being
102
+ * mistaken for the script's reason.
103
+ *
104
+ * Scripts normally print their `##owenloop:payload##` directive to stdout, so
105
+ * that marker remains in the tail just as it does in `relayChildOutput`.
106
+ * Stripping it here would duplicate the runner's bounded marker scanner. The
107
+ * runner caps the tail at 4 KiB, and a large final payload can crowd out its
108
+ * diagnostics; that pre-existing limit belongs in the runner, not this relay.
109
+ */
110
+ function withCommandOutput(text, outputTail) {
111
+ const tail = outputTail.replace(/\n+$/, '');
112
+ if (tail === '')
113
+ return text;
114
+ return `${text}\n\n--- command output (last ${Buffer.byteLength(tail, 'utf8')} bytes) ---\n${tail}`;
115
+ }
75
116
  /**
76
117
  * Put the order's consumed inputs on `childEnv`, and return the temp DIRECTORY
77
118
  * holding the overflow file — or `undefined` when the payload went inline.
@@ -141,6 +182,42 @@ function deliverConsumes(childEnv, consumes) {
141
182
  throw e;
142
183
  }
143
184
  }
185
+ /**
186
+ * Deliver the owed-artifact reason threads to a command child. The same
187
+ * inline-or-file collision rule as consumes applies: a nested command must
188
+ * never inherit stale feedback from its parent order.
189
+ */
190
+ function deliverFeedback(childEnv, feedback) {
191
+ if (feedback === undefined) {
192
+ delete childEnv['OWENLOOP_FEEDBACK'];
193
+ delete childEnv['OWENLOOP_FEEDBACK_FILE'];
194
+ return undefined;
195
+ }
196
+ let json;
197
+ try {
198
+ json = JSON.stringify(feedback);
199
+ }
200
+ catch (e) {
201
+ throw new Error(`cannot serialize the order's feedback for OWENLOOP_FEEDBACK: ${errMsg(e)}`);
202
+ }
203
+ if (Buffer.byteLength(json, 'utf8') <= CONSUMES_INLINE_MAX_BYTES) {
204
+ childEnv['OWENLOOP_FEEDBACK'] = json;
205
+ delete childEnv['OWENLOOP_FEEDBACK_FILE'];
206
+ return undefined;
207
+ }
208
+ const dir = mkdtempSync(join(tmpdir(), 'owenloop-consumes-'));
209
+ try {
210
+ const file = join(dir, 'feedback.json');
211
+ writeFileSync(file, json, { encoding: 'utf8', mode: 0o600 });
212
+ childEnv['OWENLOOP_FEEDBACK_FILE'] = file;
213
+ delete childEnv['OWENLOOP_FEEDBACK'];
214
+ return dir;
215
+ }
216
+ catch (e) {
217
+ removeConsumesDir(dir);
218
+ throw e;
219
+ }
220
+ }
144
221
  /** Best-effort removal of an overflow directory; a cleanup failure never fails a step. */
145
222
  function removeConsumesDir(dir) {
146
223
  if (dir === undefined)
@@ -251,10 +328,15 @@ export function createExecLoop(opts) {
251
328
  * Deliver a PAYLOAD reject before the owed submits, and say whether this
252
329
  * worker is finished.
253
330
  *
331
+ * Its text is the script's reason plus a labeled child-output tail. That
332
+ * tail makes a reject actionable for a consumer that never sees the receipt,
333
+ * where the runner's output would otherwise be the only diagnosis.
334
+ *
254
335
  * The distinction from `issueReject` is the third outcome. A judge reject is
255
336
  * always the end of the run; a payload reject may leave the claim open, and
256
- * when it does the owed receipts still have to land. So this returns either a
257
- * terminal `ExecOutcome` or the sentinel `'continue'`.
337
+ * when it does the caller decides whether the command result may deliver
338
+ * owed receipts. So this returns either a terminal `ExecOutcome` or the
339
+ * sentinel `'continue'`.
258
340
  *
259
341
  * refused / threw → terminal. `issueReject` has already logged it and
260
342
  * settled the lease. Nothing is submitted: a reject that
@@ -265,17 +347,19 @@ export function createExecLoop(opts) {
265
347
  * the owed paths stay debts for the next firing.
266
348
  * landed, still open → `'continue'`. The rejected path was not consumed
267
349
  * here, so the claim and the consume fingerprint are
268
- * both intact and every owed submit proceeds normally.
350
+ * both intact. A successful command may submit its
351
+ * owed receipts; a failed command escalates instead.
269
352
  *
270
353
  * `closed` is read from the hub's own response rather than re-derived from the
271
354
  * order, because the consumed-input test lives in the hub
272
355
  * (`reject-artifact.ts` checks `runRow.fingerprint`, which is what the engine
273
356
  * recorded at claim time — not what the def declares the step consumes).
274
357
  */
275
- async function relayPayloadReject(path, text, owed) {
358
+ async function relayPayloadReject(path, text, outputTail, owed) {
359
+ const body = withCommandOutput(text, outputTail);
276
360
  let res;
277
361
  try {
278
- res = await hub.reject({ workflow, run: runId, path, text });
362
+ res = await hub.reject({ workflow, run: runId, path, text: body });
279
363
  }
280
364
  catch (e) {
281
365
  opts.err(`owenloop work exec: reject of ${path} failed: ${errMsg(e)}`);
@@ -298,12 +382,12 @@ export function createExecLoop(opts) {
298
382
  await leasePromise;
299
383
  return 'rejected';
300
384
  }
301
- opts.out(`owenloop work exec: rejected ${path} (not consumed by this firing) — submitting owed receipts`);
385
+ opts.out(`owenloop work exec: rejected ${path} (not consumed by this firing) — claim remains open`);
302
386
  return 'continue';
303
387
  }
304
388
  /**
305
- * Relay the child's own output to this process's stderr when the command did
306
- * not succeed.
389
+ * Relay the child's own output unconditionally: to this process's stdout
390
+ * when the command succeeds, and stderr otherwise.
307
391
  *
308
392
  * ## Why this exists
309
393
  *
@@ -322,29 +406,103 @@ export function createExecLoop(opts) {
322
406
  * schema-rejected — with no trace of what the child said. Reproducing the
323
407
  * script by hand outside the engine was the only way to see its stderr.
324
408
  *
325
- * `outputTail` is already capped at 4 KiB by the runner, so this cannot flood
326
- * a log. Each line is prefixed so the child's words are never mistaken for
327
- * exec's own.
328
- */
409
+ * The success half matters because a non-judge command can defer with exit 0
410
+ * and no payload. Failed commands now escalate through `ask`, but
411
+ * `merge-gate` still uses that exit-0 deferral on its `cadence: 2m`
412
+ * re-offer. Before this relay, every deferral produced three identical log
413
+ * lines and no reason; the measured 40-minute case is recorded in
414
+ * `src/config-dir.ts:19-26`.
415
+ *
416
+ * Silence is printed rather than skipped because "this gate printed nothing"
417
+ * is itself the diagnosis, and an absent line is indistinguishable from the
418
+ * bug this relay fixes.
419
+ *
420
+ * `outputTail` is capped at 4 KiB by the runner (`runner.ts:40`), and a
421
+ * delivery run has roughly eleven command steps, so the worst case is about
422
+ * 44 KiB per run. That cap is why no volume knob exists: a knob would let a
423
+ * machine silently reintroduce this exact bug. Each line is prefixed so the
424
+ * child's words are never mistaken for exec's own.
425
+ */
329
426
  function relayChildOutput(result, step) {
330
- if (result.exitCode === 0 && result.error === undefined)
331
- return;
332
- const how = result.error !== undefined
333
- ? `could not be run (${result.error})`
334
- : result.signal !== undefined
335
- ? `was killed by ${result.signal}`
336
- : `exited ${result.exitCode}`;
337
- opts.err(`owenloop work exec: the command for step '${step}' ${how}; its last output follows`);
427
+ const succeeded = commandSucceeded(result);
428
+ // TWO CHANNELS ON PURPOSE, and this is not tidiness to be refactored away.
429
+ // `opts.err` is the channel a reader treats as trouble; routing a green
430
+ // step's routine output there would make every successful step look like a
431
+ // problem. A successful command's output is a RECORD, a failed one's is a
432
+ // DIAGNOSIS. Do not unify them.
433
+ const write = succeeded ? opts.out : opts.err;
434
+ if (succeeded) {
435
+ write(`owenloop work exec: the command for step '${step}' succeeded; its output follows`);
436
+ }
437
+ else {
438
+ write(`owenloop work exec: the command for step '${step}' ${describeCommandFailure(result)}; its last output follows`);
439
+ }
338
440
  const tail = result.outputTail.replace(/\n+$/, '');
339
441
  if (tail === '') {
340
- opts.err(' (the command produced no output)');
442
+ write(' (the command produced no output)');
341
443
  return;
342
444
  }
343
445
  for (const line of tail.split('\n'))
344
- opts.err(` | ${line}`);
446
+ write(` | ${line}`);
345
447
  }
346
- /** Build the receipt and submit it to every owed path. */
347
- async function submitReceipt(result, order, resolvedCommand) {
448
+ /** The operator-facing failure text shown by `owenloop inbox`. */
449
+ function failureQuestion(receipt, path, resolvedCommand) {
450
+ const head = `the command for step '${receipt.step}' ${describeCommandFailure(receipt)}, ` +
451
+ `so '${path}' was not produced and no receipt was submitted.\n` +
452
+ `command: ${resolvedCommand}\n` +
453
+ `exit code: ${receipt.exitCode ?? 'none'}` +
454
+ (receipt.signal !== undefined ? `, signal: ${receipt.signal}` : '') +
455
+ (receipt.error !== undefined ? `, error: ${receipt.error}` : '') +
456
+ `\noutput: ${receipt.stdoutBytes} stdout byte(s), ${receipt.stderrBytes} stderr byte(s), ` +
457
+ `hash ${receipt.outputHash}`;
458
+ return withCommandOutput(head, receipt.outputTail);
459
+ }
460
+ /**
461
+ * A failed command does not green anything. Raise a question on its own owed
462
+ * path and retain the receipt as diagnostic context instead.
463
+ */
464
+ async function escalateCommandFailure(receipt, order, resolvedCommand) {
465
+ // run() returns misroute when order.owes is empty, so this index is safe.
466
+ const path = order.owes[0].path;
467
+ const how = describeCommandFailure(receipt);
468
+ opts.err(`owenloop work exec: the command for step '${order.step}' ${how} — ` +
469
+ `no receipt will be submitted; escalating on ${path}`);
470
+ // ask closes the run, so one firing can raise only one question. The
471
+ // remaining owed paths stay debts for the next firing.
472
+ if (order.owes.length > 1) {
473
+ const rest = order.owes.slice(1).map((owe) => owe.path).join(', ');
474
+ opts.err(`owenloop work exec: ${order.owes.length - 1} other owed path(s) were not escalated ` +
475
+ `because ask closes the run: ${rest}`);
476
+ }
477
+ let res;
478
+ try {
479
+ res = await hub.ask({
480
+ workflow,
481
+ run: runId,
482
+ path,
483
+ question: failureQuestion(receipt, path, resolvedCommand),
484
+ context: JSON.stringify(receipt),
485
+ });
486
+ }
487
+ catch (e) {
488
+ opts.err(`owenloop work exec: ask on ${path} failed: ${errMsg(e)}`);
489
+ lease.stop('ask-failed');
490
+ await leasePromise;
491
+ return 'ask-failed';
492
+ }
493
+ if (res.ok !== true) {
494
+ opts.err(`owenloop work exec: ask on ${path} was refused: ${res.text}`);
495
+ lease.stop('ask-failed', res.closed === true ? { release: false } : undefined);
496
+ await leasePromise;
497
+ return 'ask-failed';
498
+ }
499
+ opts.out(`owenloop work exec: asked ${path} — the artifact is held for a human and nothing was greened`);
500
+ lease.stop('command-failed', res.closed === true ? { release: false } : undefined);
501
+ await leasePromise;
502
+ return 'command-failed';
503
+ }
504
+ /** Build the command receipt, then deliver, reject, or escalate it. */
505
+ async function deliverCommandResult(result, order, resolvedCommand) {
348
506
  if (signalled) {
349
507
  // The operator killed the work and the command settled before the lease
350
508
  // (the release HTTP round-trip is slower than a TERM'd child dying), so
@@ -428,15 +586,18 @@ export function createExecLoop(opts) {
428
586
  //
429
587
  // `closed: false` — the rejected path was NOT consumed by this firing, so
430
588
  // the claim is still open and the fingerprint has not moved. Fall through
431
- // and submit every owed path exactly as before.
589
+ // to the command-result gate: a success submits every owed path, while a
590
+ // failure escalates through ask and submits nothing.
432
591
  //
433
592
  // A REFUSED reject now submits nothing. That is the point: previously the
434
593
  // receipt had already landed and greened a path whose gate had failed.
435
594
  if (order.judge === undefined && parsedPayload.reject !== undefined) {
436
- const rejected = await relayPayloadReject(parsedPayload.reject.path, parsedPayload.reject.text, order.owes.length);
595
+ const rejected = await relayPayloadReject(parsedPayload.reject.path, parsedPayload.reject.text, result.outputTail, order.owes.length);
437
596
  if (rejected !== 'continue')
438
597
  return rejected;
439
598
  }
599
+ if (!commandSucceeded(result))
600
+ return escalateCommandFailure(receipt, order, resolvedCommand);
440
601
  for (const owe of order.owes) {
441
602
  let res;
442
603
  try {
@@ -572,6 +733,7 @@ export function createExecLoop(opts) {
572
733
  // no receipt — but it is not a guarantee to build on. Do not add work here
573
734
  // that assumes the child is gone.
574
735
  let consumesDir;
736
+ let feedbackDir;
575
737
  try {
576
738
  let cmd;
577
739
  try {
@@ -596,6 +758,14 @@ export function createExecLoop(opts) {
596
758
  childEnv['OWENLOOP_WORKFLOW'] = workflow;
597
759
  childEnv['OWENLOOP_RUN'] = runId;
598
760
  consumesDir = deliverConsumes(childEnv, order.consumes);
761
+ const feedback = order.owes
762
+ .filter((owe) => owe.reasons.length > 0)
763
+ .map((owe) => ({ path: owe.path, reasons: owe.reasons }));
764
+ feedbackDir = deliverFeedback(childEnv, feedback.length > 0 ? feedback : undefined);
765
+ if (order.modifier === undefined)
766
+ delete childEnv['OWENLOOP_MODIFIER'];
767
+ else
768
+ childEnv['OWENLOOP_MODIFIER'] = order.modifier;
599
769
  // The order carries no workdir when the step declared neither `workdir:`
600
770
  // nor `workdirFrom:` (the hub resolves `workdirFrom` and ships the
601
771
  // result, so an absent field IS that signal). Substituting the shift's
@@ -633,7 +803,7 @@ export function createExecLoop(opts) {
633
803
  cmd = runner.start(resolvedCommand, startOptions);
634
804
  }
635
805
  catch (e) {
636
- return submitReceipt(machineryFailure(e), order, resolvedCommand);
806
+ return deliverCommandResult(machineryFailure(e), order, resolvedCommand);
637
807
  }
638
808
  running = cmd;
639
809
  opts.out(`owenloop work exec: running ${workflow}/${runId} (step '${order.step}')`);
@@ -650,10 +820,11 @@ export function createExecLoop(opts) {
650
820
  opts.err(`owenloop work exec: lease ${outcome.o} while the command ran — killed the command, no receipt submitted`);
651
821
  return mapLeaseDuringRun(outcome.o);
652
822
  }
653
- return submitReceipt(outcome.r, order, resolvedCommand);
823
+ return deliverCommandResult(outcome.r, order, resolvedCommand);
654
824
  }
655
825
  finally {
656
826
  removeConsumesDir(consumesDir);
827
+ removeConsumesDir(feedbackDir);
657
828
  }
658
829
  }
659
830
  function stop(reason) {
@@ -1,14 +1,14 @@
1
1
  /**
2
- * The command receipt (C5, plan decision 8) — the audit record exec submits for
3
- * an ordinary command order, and for a judge order that exits 0. The hub `submit`
4
- * verb has no failure channel, so a non-zero `exitCode` (or `exitCode: null` +
5
- * `error` for machinery failure) carries the command result. A non-zero judge
6
- * exit uses `reject` instead of a receipt, and signal-killed work submits neither.
7
- * Pure construction so it is trivially asserted in tests.
2
+ * The command receipt (C5, plan decision 8) — the artifact value exec submits
3
+ * only for a successful ordinary command and for a judge that exits 0. Because
4
+ * the hub `submit` verb has no failure channel, a failed ordinary command puts
5
+ * this same receipt in `hub.ask`'s diagnostic context and submits nothing. A
6
+ * non-zero judge exit uses `reject` instead, and signal-killed work submits
7
+ * neither. Pure construction so it is trivially asserted in tests.
8
8
  */
9
9
  import { type ParsedPayload } from './payload.ts';
10
10
  import type { CommandResult } from './runner.ts';
11
- /** The submitted artifact value for a command order. */
11
+ /** A command's artifact value on success, or failure diagnostics in `hub.ask` context. */
12
12
  export interface CommandReceipt {
13
13
  kind: 'command-receipt';
14
14
  command: string;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * The command receipt (C5, plan decision 8) — the audit record exec submits for
3
- * an ordinary command order, and for a judge order that exits 0. The hub `submit`
4
- * verb has no failure channel, so a non-zero `exitCode` (or `exitCode: null` +
5
- * `error` for machinery failure) carries the command result. A non-zero judge
6
- * exit uses `reject` instead of a receipt, and signal-killed work submits neither.
7
- * Pure construction so it is trivially asserted in tests.
2
+ * The command receipt (C5, plan decision 8) — the artifact value exec submits
3
+ * only for a successful ordinary command and for a judge that exits 0. Because
4
+ * the hub `submit` verb has no failure channel, a failed ordinary command puts
5
+ * this same receipt in `hub.ask`'s diagnostic context and submits nothing. A
6
+ * non-zero judge exit uses `reject` instead, and signal-killed work submits
7
+ * neither. Pure construction so it is trivially asserted in tests.
8
8
  */
9
9
  import { parsePayloadLine } from "./payload.js";
10
10
  /** Fold a raw `CommandResult` and its order context into the submitted receipt. */
@@ -110,11 +110,10 @@ export const ADMITTED_OWENLOOP_KEYS = new Set([
110
110
  'OWENLOOP_SESSION',
111
111
  // `owenloopConfigDir` — src/config-dir.ts. Scopes owenloop's OWN config
112
112
  // directory (`settings.json`, `credentials.json`, `allowed_signers`) without
113
- // touching `XDG_CONFIG_HOME`, which the rest of the operator's toolchain also
114
- // reads. A path, not credential material — but the credential FILE backend
115
- // resolves under it (`readStoredCredential` → `configDir` → src/hub.ts), so a
116
- // mount that does not see this variable falls back to `XDG_CONFIG_HOME` and
117
- // reads a DIFFERENT credential store than the shift that spawned it.
113
+ // touching the rest of the operator's toolchain. A path, not credential
114
+ // material — but the credential file backend resolves under it
115
+ // (`readStoredCredential` → `configDir` → src/hub.ts), so a mount that does
116
+ // not see this variable reads a different credential store than its shift.
118
117
  'OWENLOOP_CONFIG_DIR',
119
118
  ]);
120
119
  /** The namespace this filter governs. Nothing outside it is ever touched. */
@@ -713,6 +713,93 @@ const DEFAULT_START_DEPENDENCIES = {
713
713
  * process that started the session — which is exactly why `stop` is documented
714
714
  * as a no-op on a token this process did not start. */
715
715
  const SESSIONS = new Map();
716
+ /** Trim a progress line to something a log can hold. Mirrors the codex adapter's
717
+ * convention deliberately — the two adapters' logs are read side by side, so
718
+ * they truncate the same way. Kept local because this adapter must stay in one
719
+ * allowlisted file. */
720
+ const PROGRESS_TEXT_CAP = 2_000;
721
+ function cap(text) {
722
+ return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
723
+ }
724
+ /** Mark messages produced inside a Task-tool subagent. A flat log cannot
725
+ * otherwise tell a subagent's work from the main agent's. */
726
+ function origin(parentToolUseId) {
727
+ return parentToolUseId === null ? '' : `[subagent ${parentToolUseId}] `;
728
+ }
729
+ /** Flatten a tool_result body to loggable text. Non-text parts are named, not
730
+ * rendered — an image block has no useful string form. */
731
+ function toolResultText(content) {
732
+ if (content === undefined)
733
+ return '(no content)';
734
+ if (typeof content === 'string')
735
+ return content;
736
+ return content.map((part) => (part.type === 'text' ? part.text : `(${part.type})`)).join('\n');
737
+ }
738
+ /** One progress line per content block of an assistant message.
739
+ *
740
+ * TOOL INPUTS ARE NEVER LOGGED. A `tool_use` block's `input` can hold a Bash
741
+ * command line carrying a secret. Only `name` and `id` are emitted — the same
742
+ * two fields the codex adapter reveals for `item/started mcpToolCall`. */
743
+ function emitAssistant(message, onEvent) {
744
+ const from = origin(message.parent_tool_use_id);
745
+ if (message.error !== undefined) {
746
+ onEvent({ kind: 'progress', text: `${from}assistant error: ${message.error}` });
747
+ }
748
+ for (const block of message.message.content) {
749
+ switch (block.type) {
750
+ case 'text':
751
+ onEvent({ kind: 'progress', text: cap(`${from}assistant: ${block.text}`) });
752
+ break;
753
+ case 'thinking':
754
+ onEvent({ kind: 'progress', text: cap(`${from}thinking: ${block.thinking}`) });
755
+ break;
756
+ case 'redacted_thinking':
757
+ onEvent({ kind: 'progress', text: `${from}thinking: (redacted)` });
758
+ break;
759
+ case 'tool_use':
760
+ case 'mcp_tool_use':
761
+ onEvent({ kind: 'progress', text: `${from}tool_use ${block.name} ${block.id}` });
762
+ break;
763
+ default:
764
+ // Server-tool results, container uploads, compaction markers and any
765
+ // block the vendor adds later. Naming the type keeps the line useful
766
+ // without guessing at a shape this version does not define.
767
+ onEvent({ kind: 'progress', text: `${from}${block.type} block` });
768
+ }
769
+ }
770
+ }
771
+ /** One progress line per content block of a user message — which on this path
772
+ * means tool results coming back, plus any synthetic user text.
773
+ *
774
+ * Tool RESULTS are logged (capped); tool INPUTS are not. A result is what the
775
+ * tool produced, and the codex adapter already logs the equivalent command
776
+ * output. */
777
+ function emitUser(message, onEvent) {
778
+ const from = origin(message.parent_tool_use_id);
779
+ const content = message.message.content;
780
+ if (typeof content === 'string') {
781
+ onEvent({ kind: 'progress', text: cap(`${from}user: ${content}`) });
782
+ return;
783
+ }
784
+ for (const block of content) {
785
+ switch (block.type) {
786
+ case 'text':
787
+ onEvent({ kind: 'progress', text: cap(`${from}user: ${block.text}`) });
788
+ break;
789
+ case 'tool_result': {
790
+ const flag = block.is_error === true ? ' (error)' : '';
791
+ const body = toolResultText(block.content);
792
+ onEvent({
793
+ kind: 'progress',
794
+ text: cap(`${from}tool_result ${block.tool_use_id}${flag}: ${body}`),
795
+ });
796
+ break;
797
+ }
798
+ default:
799
+ onEvent({ kind: 'progress', text: `${from}${block.type} block` });
800
+ }
801
+ }
802
+ }
716
803
  /**
717
804
  * Drive the SDK message stream to TURN END and map it onto `AgentEvent`s.
718
805
  *
@@ -766,8 +853,21 @@ export async function consumeTurn(q, onEvent, onInit, expectedSessionId) {
766
853
  onEvent({ kind: 'turn_ended' });
767
854
  return { sessionId, sawResult: true };
768
855
  }
856
+ else if (message.type === 'assistant') {
857
+ emitAssistant(message, onEvent);
858
+ }
859
+ else if (message.type === 'user') {
860
+ emitUser(message, onEvent);
861
+ }
769
862
  // `needs_input` is NEVER emitted: this SDK path has no blocking-question
770
863
  // channel that maps to it, and the contract has no reply channel by design.
864
+ // `stream_event` is deliberately NOT mapped. The SDK only emits it when
865
+ // `Options.includePartialMessages` is set, and `buildClaudeOptions` never
866
+ // sets it — so the branch would be unreachable today, and if it ever
867
+ // became reachable it would duplicate the text the `assistant` message
868
+ // already carries. Unrecognized types stay silent by design: the vendor
869
+ // adds message kinds between releases, and a mapping that threw on one
870
+ // would turn a routine CLI upgrade into a failed order.
771
871
  }
772
872
  return { sessionId, sawResult: false };
773
873
  }
@@ -266,10 +266,9 @@ function isPlainMap(v) {
266
266
  const MOUNT_ENV_KEEP = ['HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME'];
267
267
  /**
268
268
  * `OWENLOOP_CONFIG_DIR` rides the `OWENLOOP_*` allowlist below rather than this
269
- * list, but it belongs to the same job: without it a mount whose parent scoped
270
- * owenloop's config with `OWENLOOP_CONFIG_DIR` would fall back to
271
- * `XDG_CONFIG_HOME` and read a DIFFERENT settings file than the shift that
272
- * spawned it.
269
+ * list, but it belongs to the same job: without it a mount whose parent uses an
270
+ * explicit configuration root would instead use its inherited HOME-rooted
271
+ * settings directory.
273
272
  */
274
273
  /**
275
274
  * The environment for the owenloop mount, forwarded from THIS process.
@@ -11,6 +11,22 @@ export interface SessionRecord {
11
11
  * contract lists it and Phase 6's `owenloop work sessions` display prints it.
12
12
  * ALWAYS build it with `orderId()` so the two can never drift. */
13
13
  order: string;
14
+ /**
15
+ * `OrderPacket.key` — the fan-out key of the engine task this firing served.
16
+ *
17
+ * WHY IT IS HERE, AND WHY IT IS OPTIONAL. `run` identifies ONE FIRING and is
18
+ * minted fresh every time the engine claims the step, so `(workflow, run,
19
+ * step)` can never name the same work twice. `(workflow, step, key)` is the
20
+ * engine's own task identity — the `UNIQUE (workflow, step, key)` on its
21
+ * `task` table — and is the only triple here that survives a re-offer. See
22
+ * `latestForTask`.
23
+ *
24
+ * OPTIONAL because every row written before this field existed lacks it. Such
25
+ * a row is never attributed to a task (`latestForTask` skips it) rather than
26
+ * being guessed at. `''` is a REAL key — an unfanned step — so the absence
27
+ * must be tested as `undefined`, never as falsy.
28
+ */
29
+ key?: string;
14
30
  attempt: number;
15
31
  /** Adapter id (`HarnessSessionRef.harness`). */
16
32
  harness: string;
@@ -86,11 +102,55 @@ export declare function orderId(workflow: string, run: string): string;
86
102
  */
87
103
  export declare function readSessions(file: string, opts?: SessionStoreOptions): SessionRecord[];
88
104
  /**
89
- * The newest record for `(workflow, run, step)`, or `null` when the file is
90
- * missing or holds no match. Scans forward and keeps the LAST match (last-wins).
91
- * Side-effect-free — it never writes, never compacts, and never throws.
105
+ * The newest record for `(workflow, run, step)` — that is, for ONE FIRING of one
106
+ * step — or `null` when the file is missing or holds no match. Scans forward and
107
+ * keeps the LAST match (last-wins). Side-effect-free: it never writes, never
108
+ * compacts, and never throws.
109
+ *
110
+ * ── THIS IS THE PER-FIRING LOOKUP. IT CANNOT FIND A PREVIOUS FIRING. ─────────
111
+ *
112
+ * The hub mints a fresh `run` id every time it claims a step. Two firings of the
113
+ * same step therefore NEVER share a `run`, so this function can only ever return
114
+ * a record written during the very firing that is asking. Use it for questions
115
+ * that really are about one firing — "did THIS firing already take a work dir?",
116
+ * "which sessions belong to the run I am tearing down?" — and never to ask "has
117
+ * this step run before?". That second question is `latestForTask`.
92
118
  */
93
119
  export declare function latestFor(file: string, workflow: string, run: string, step: string): SessionRecord | null;
120
+ /**
121
+ * The engine's own identity for a unit of work: one STEP of one WORKFLOW at one
122
+ * fan-out KEY. The hub enforces `UNIQUE (workflow, step, key)` on its task table,
123
+ * which is what makes this triple stable across re-offers where `run` is not.
124
+ */
125
+ export interface SessionTaskRef {
126
+ workflow: string;
127
+ step: string;
128
+ /** `OrderPacket.key`. `''` for a step that does not fan out — a real value,
129
+ * not a missing one. */
130
+ key: string;
131
+ }
132
+ /**
133
+ * The newest record for an engine TASK — the last session recorded for this
134
+ * step at this key, no matter which firing wrote it — or `null` when there is
135
+ * none. Last-wins, side-effect-free, same as `latestFor`.
136
+ *
137
+ * ── WHY THIS EXISTS ALONGSIDE `latestFor` ────────────────────────────────────
138
+ *
139
+ * `latestFor` keys on `run`, which the hub re-mints per firing, so it answers
140
+ * "what happened during THIS firing?". Resume needs the opposite question: "did
141
+ * a previous firing of this same step leave a session I can re-enter?" Only
142
+ * `(workflow, step, key)` survives long enough to answer that.
143
+ *
144
+ * ── WHY A ROW WITHOUT `key` NEVER MATCHES ────────────────────────────────────
145
+ *
146
+ * Rows written before `key` existed carry no task identity at all. Guessing one
147
+ * — treating absent as `''`, say — would attribute an unfanned row and a fanned
148
+ * row to the same task and hand a worker someone else's session. Skipping them
149
+ * costs only a cold start on the first firing after upgrade, which is the safe
150
+ * direction to be wrong in. The test is `=== undefined`, because `''` is a real
151
+ * key that must match.
152
+ */
153
+ export declare function latestForTask(file: string, task: SessionTaskRef): SessionRecord | null;
94
154
  /**
95
155
  * Rewrite `file` with only the last record per `(workflow, run, step)`,
96
156
  * preserving FIRST-SEEN key order, via temp file + rename. Corrupt lines are