owenloop 0.5.4 → 0.5.6

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 (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/packages/work/src/agent/brief.d.ts +28 -4
  3. package/dist/packages/work/src/agent/brief.js +170 -2
  4. package/dist/packages/work/src/agent/loop.d.ts +10 -1
  5. package/dist/packages/work/src/agent/loop.js +60 -3
  6. package/dist/packages/work/src/agent/workdir.d.ts +22 -0
  7. package/dist/packages/work/src/agent/workdir.js +80 -0
  8. package/dist/packages/work/src/exec/loop.d.ts +13 -1
  9. package/dist/packages/work/src/exec/loop.js +31 -0
  10. package/dist/packages/work/src/harness/claude.d.ts +24 -0
  11. package/dist/packages/work/src/harness/claude.js +131 -23
  12. package/dist/packages/work/src/harness/contract.d.ts +25 -20
  13. package/dist/packages/work/src/harness/contract.js +25 -20
  14. package/dist/packages/work/src/harness/gatekeeper.d.ts +124 -0
  15. package/dist/packages/work/src/harness/gatekeeper.js +208 -0
  16. package/dist/packages/work/src/hold/mcp.d.ts +11 -2
  17. package/dist/packages/work/src/hold/mcp.js +69 -2
  18. package/dist/packages/work/src/hub/client.d.ts +8 -1
  19. package/dist/packages/work/src/hub/client.js +1 -0
  20. package/dist/packages/work/src/hub/types.d.ts +29 -0
  21. package/dist/packages/work/src/roles/agent-run.js +9 -1
  22. package/dist/packages/work/src/roles/exec.js +9 -0
  23. package/dist/packages/work/src/roles/shift.js +9 -1
  24. package/dist/packages/work/src/settings/settings.d.ts +20 -1
  25. package/dist/packages/work/src/settings/settings.js +23 -1
  26. package/dist/packages/work/src/shift/runtime.d.ts +7 -0
  27. package/dist/packages/work/src/shift/runtime.js +29 -4
  28. package/dist/packages/work/src/shift/spawn.d.ts +12 -2
  29. package/dist/packages/work/src/shift/spawn.js +16 -3
  30. package/dist/src/cli.js +54 -1
  31. package/dist/src/engine.d.ts +46 -1
  32. package/dist/src/engine.js +72 -0
  33. package/dist/src/index.d.ts +1 -1
  34. package/dist/src/index.js +1 -1
  35. package/dist/src/model.d.ts +29 -5
  36. package/dist/src/model.js +63 -14
  37. package/dist/src/types.d.ts +8 -2
  38. package/docs/agent-runner.md +17 -5
  39. package/docs/cli.md +34 -0
  40. package/package.json +1 -1
  41. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  42. package/plugins/claude-code/plugin/.mcp.json +1 -1
  43. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  44. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { randomUUID } from 'node:crypto';
10
10
  import { hostname } from 'node:os';
11
- import { basename, join } from 'node:path';
11
+ import { basename, join, resolve } from 'node:path';
12
12
  import { performance } from 'node:perf_hooks';
13
13
  import { createHubClient } from "../hub/client.js";
14
14
  import { resolveBearer } from "../credentials/resolve.js";
@@ -21,7 +21,7 @@ import { stampShiftEvent } from "./protocol.js";
21
21
  import { createDefaultSpawner } from "./spawn.js";
22
22
  import { resolveStateDir, ensureStateDir, reconcileInFlight } from "./state.js";
23
23
  import { reconcileActiveSessions, sessionsPath } from "../harness/session-store.js";
24
- import { resolveWorkRepo, resolveWorkRoot } from "../agent/workdir.js";
24
+ import { resolveAllowedWorkdirRoots, resolveWorkRepo, resolveWorkRoot, } from "../agent/workdir.js";
25
25
  import { installSignalHandlers } from "../roles/signals.js";
26
26
  import { createShiftDaemon } from "./server.js";
27
27
  import { createBundleIngestor, createStoreInstructionSource, globalStoreRoot, } from "../../../../src/store/index.js";
@@ -153,6 +153,7 @@ export function parseArgs(args) {
153
153
  case '--cache-dir':
154
154
  case '--log-dir':
155
155
  case '--log-max-age':
156
+ case '--work-root':
156
157
  case '--state-dir': {
157
158
  const r = takeValue(a, i);
158
159
  if ('error' in r)
@@ -202,6 +203,13 @@ export function parseArgs(args) {
202
203
  return { error: n.error };
203
204
  parsed.pollIntervalMs = n;
204
205
  }
206
+ else if (name === '--work-root') {
207
+ // ACCUMULATES rather than overwrites — one directory per occurrence
208
+ // is what makes a multi-project boundary expressible at all. A shift
209
+ // that may work in two projects needs two roots, and there is no
210
+ // separator that is safe inside a path on every platform.
211
+ (parsed.workRoots ??= []).push(r.value);
212
+ }
205
213
  break;
206
214
  }
207
215
  default:
@@ -214,7 +222,7 @@ function usage() {
214
222
  process.stderr.write('usage: owenloop work shift [--origin <url>] [--as <account>] [--name <n>] [--serve-crews a,b] [--cap <n>]\n' +
215
223
  ' [--workflow <id>] [--poll-interval <ms>] [--once]\n' +
216
224
  ' [--max-agents <n>] [--cache-dir <p>] [--state-dir <p>]\n' +
217
- ' [--log-dir <p>] [--log-max-age <ms>]\n');
225
+ ' [--log-dir <p>] [--log-max-age <ms>] [--work-root <dir>]...\n');
218
226
  }
219
227
  function errMsg(err) {
220
228
  return err instanceof Error ? err.message : String(err);
@@ -335,6 +343,23 @@ export async function runShiftRuntime(parsed, options = {}) {
335
343
  const maxConcurrentAgents = resolveMaxConcurrentAgents(parsed.maxAgents, settings.maxConcurrentAgents);
336
344
  const workRoot = resolveWorkRoot(env, settings.workRoot, cacheDir);
337
345
  const workRepo = resolveWorkRepo(env, settings.workRepo);
346
+ /**
347
+ * The operator's filesystem boundary, resolved once here so the loop receives
348
+ * an already-absolute list and does no precedence work of its own.
349
+ *
350
+ * Precedence is `--work-root` (repeatable) > `OWENLOOP_ALLOWED_WORKDIR_ROOTS`
351
+ * > `settings.allowedWorkdirRoots` > none. Each rung REPLACES the one below
352
+ * rather than adding to it: a narrowing control that could only ever widen
353
+ * would not be a safety control at all.
354
+ *
355
+ * Relative entries resolve against THIS process's cwd, which is where the
356
+ * operator typed the flag. `settings.allowedWorkdirRoots` cannot be relative
357
+ * — `validateSettings` rejects that at load, because a stored boundary that
358
+ * moves with the launch directory is the exact failure this key removes.
359
+ */
360
+ const allowedWorkdirRoots = parsed.workRoots !== undefined && parsed.workRoots.length > 0
361
+ ? parsed.workRoots.map((entry) => resolve(process.cwd(), entry))
362
+ : resolveAllowedWorkdirRoots(env, settings.allowedWorkdirRoots, process.cwd());
338
363
  const hub = createHubClient({ origin, getToken: async () => token });
339
364
  const now = () => Date.now();
340
365
  const monotonicNow = () => performance.now();
@@ -445,7 +470,7 @@ export async function runShiftRuntime(parsed, options = {}) {
445
470
  // output discarded exactly as it did before this change.
446
471
  logDirReady
447
472
  ? { dir: logDir, err: (line) => process.stderr.write(`${line}\n`) }
448
- : undefined);
473
+ : undefined, allowedWorkdirRoots);
449
474
  const pollIntervalMs = parsed.pollIntervalMs ?? DEFAULT_POLL_MS;
450
475
  const loop = createShiftLoop({
451
476
  hub,
@@ -164,13 +164,23 @@ export interface SpawnPlan {
164
164
  * step, registered default). The Shift command has no operator-facing harness
165
165
  * flag, so there is no legitimate CLI override for this seam to carry.
166
166
  *
167
+ * `allowedWorkdirRoots` (trailing, for the same reason) rides the child's spawn
168
+ * env as `OWENLOOP_ALLOWED_WORKDIR_ROOTS`, a `:`-separated list — the same
169
+ * "spawn env is the contract" shape as `OWENLOOP_ACCOUNT`, and for the same
170
+ * reason: neither `owenloop work exec` nor `owenloop work agent-run` has an
171
+ * operator-facing flag for it. It carries the roots the SHIFT resolved, so an
172
+ * operator's `owenloop shift start --work-root` reaches a detached child that
173
+ * would otherwise only see the settings file. Empty or omitted sets no variable
174
+ * at all, so the child falls through to its own settings-file resolution and
175
+ * the plan stays byte-identical to the pre-policy shape.
176
+ *
167
177
  * `logDir` (trailing, after `shiftId`, for the same reason) adds the worker's
168
178
  * log DESTINATION to the plan as `<logDir>/<run>.log`. The plan still carries
169
179
  * `stdio: ['ignore','ignore','ignore']`: opening the file is I/O, this function
170
180
  * is pure, and `createDefaultSpawner` substitutes the descriptors. Omitted ⇒ no
171
181
  * `logFile` key at all, and the plan is byte-identical to the pre-logging shape.
172
182
  */
173
- export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account: string, binPath: string, execPath?: string, shiftId?: string, logDir?: string): SpawnPlan;
183
+ export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account: string, binPath: string, execPath?: string, shiftId?: string, logDir?: string, allowedWorkdirRoots?: string[]): SpawnPlan;
174
184
  /**
175
185
  * The default detached spawner. Captures the resolved hub `origin`, the
176
186
  * resolved `account`, the packaged bin path, and the dispatching Shift's
@@ -179,4 +189,4 @@ export declare function buildSpawnPlan(spec: SpawnSpec, origin: string, account:
179
189
  * relying on `buildSpawnPlan`'s default) so `shiftId` — trailing after it
180
190
  * — can be supplied positionally.
181
191
  */
182
- export declare function createDefaultSpawner(origin: string, account: string, binPath?: string, shiftId?: string, onFailure?: WorkerFailureReporter, logging?: WorkerLogOptions): Spawner;
192
+ export declare function createDefaultSpawner(origin: string, account: string, binPath?: string, shiftId?: string, onFailure?: WorkerFailureReporter, logging?: WorkerLogOptions, allowedWorkdirRoots?: string[]): Spawner;
@@ -134,13 +134,23 @@ export function reportedHarnessId(spec, env) {
134
134
  * step, registered default). The Shift command has no operator-facing harness
135
135
  * flag, so there is no legitimate CLI override for this seam to carry.
136
136
  *
137
+ * `allowedWorkdirRoots` (trailing, for the same reason) rides the child's spawn
138
+ * env as `OWENLOOP_ALLOWED_WORKDIR_ROOTS`, a `:`-separated list — the same
139
+ * "spawn env is the contract" shape as `OWENLOOP_ACCOUNT`, and for the same
140
+ * reason: neither `owenloop work exec` nor `owenloop work agent-run` has an
141
+ * operator-facing flag for it. It carries the roots the SHIFT resolved, so an
142
+ * operator's `owenloop shift start --work-root` reaches a detached child that
143
+ * would otherwise only see the settings file. Empty or omitted sets no variable
144
+ * at all, so the child falls through to its own settings-file resolution and
145
+ * the plan stays byte-identical to the pre-policy shape.
146
+ *
137
147
  * `logDir` (trailing, after `shiftId`, for the same reason) adds the worker's
138
148
  * log DESTINATION to the plan as `<logDir>/<run>.log`. The plan still carries
139
149
  * `stdio: ['ignore','ignore','ignore']`: opening the file is I/O, this function
140
150
  * is pure, and `createDefaultSpawner` substitutes the descriptors. Omitted ⇒ no
141
151
  * `logFile` key at all, and the plan is byte-identical to the pre-logging shape.
142
152
  */
143
- export function buildSpawnPlan(spec, origin, account, binPath, execPath = process.execPath, shiftId, logDir) {
153
+ export function buildSpawnPlan(spec, origin, account, binPath, execPath = process.execPath, shiftId, logDir, allowedWorkdirRoots) {
144
154
  const role = spec.kind === 'agent-run' ? 'agent-run' : 'exec';
145
155
  return {
146
156
  command: execPath,
@@ -160,6 +170,9 @@ export function buildSpawnPlan(spec, origin, account, binPath, execPath = proces
160
170
  ...process.env,
161
171
  OWENLOOP_ACCOUNT: account,
162
172
  ...(spec.startGate !== undefined ? { OWENLOOP_START_GATE: spec.startGate } : {}),
173
+ ...(allowedWorkdirRoots !== undefined && allowedWorkdirRoots.length > 0
174
+ ? { OWENLOOP_ALLOWED_WORKDIR_ROOTS: allowedWorkdirRoots.join(':') }
175
+ : {}),
163
176
  },
164
177
  },
165
178
  ...(logDir !== undefined && logDir !== '' ? { logFile: runLogFile(logDir, spec.run) } : {}),
@@ -173,7 +186,7 @@ export function buildSpawnPlan(spec, origin, account, binPath, execPath = proces
173
186
  * relying on `buildSpawnPlan`'s default) so `shiftId` — trailing after it
174
187
  * — can be supplied positionally.
175
188
  */
176
- export function createDefaultSpawner(origin, account, binPath = resolveOwenloopBin(), shiftId, onFailure, logging) {
189
+ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopBin(), shiftId, onFailure, logging, allowedWorkdirRoots) {
177
190
  // ONE report per shift, not one per dispatch. Every condition that stops a
178
191
  // worker log from opening — a full disk, a read-only log directory, an
179
192
  // operator deleting it underneath a running shift — PERSISTS across the
@@ -189,7 +202,7 @@ export function createDefaultSpawner(origin, account, binPath = resolveOwenloopB
189
202
  logging?.err?.(line);
190
203
  };
191
204
  return (spec) => {
192
- const plan = buildSpawnPlan(spec, origin, account, binPath, process.execPath, shiftId, logging?.dir);
205
+ const plan = buildSpawnPlan(spec, origin, account, binPath, process.execPath, shiftId, logging?.dir, allowedWorkdirRoots);
193
206
  // Open the log ONCE and hand the SAME descriptor to slots 1 and 2. Opening
194
207
  // it twice would create two independent file offsets, and the two streams
195
208
  // would overwrite each other's bytes — silent corruption no unit test on the
package/dist/src/cli.js CHANGED
@@ -1171,7 +1171,9 @@ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pin
1171
1171
  reject <wf> <path> --by <author> --text <msg>
1172
1172
  retract <wf> <path> --by <author> --text <msg>
1173
1173
  skip <wf> <path> --by <author> --text <msg>
1174
- retry <wf> <path> [--by <author>] [--text <guidance>] clear a §6 stall
1174
+ retry <wf> <path> [--by <author>] [--text <guidance>] clear a §6 stall, or ANSWER an ask
1175
+ ask <wf> <path> <question> [--by <author>] hold an owed artifact on a question for a human
1176
+ inbox every held question across all instances, with its answer command
1175
1177
  heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run
1176
1178
  close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
1177
1179
  delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)
@@ -1254,6 +1256,8 @@ export const COMMAND_OPTIONS = new Map([
1254
1256
  ['retract', cmdOpts('by', 'text')],
1255
1257
  ['skip', cmdOpts('by', 'text')],
1256
1258
  ['retry', cmdOpts('by', 'text')],
1259
+ ['ask', cmdOpts('by', 'question')],
1260
+ ['inbox', cmdOpts()],
1257
1261
  ['close', cmdOpts('outcome', 'summary')],
1258
1262
  ['heartbeat', cmdOpts('now')],
1259
1263
  ['delete', cmdOpts('recursive')],
@@ -1874,6 +1878,55 @@ function dispatch(command, io, args) {
1874
1878
  print(io, { ok: true, action: 'retry', path });
1875
1879
  return 0;
1876
1880
  }
1881
+ case 'ask': {
1882
+ // The escalation verb: the producing step stops and asks a human about
1883
+ // the artifact IT owes. The answer is a plain `retry --text "<answer>"`
1884
+ // — deliberately no `answer` verb, because `retry` already appends a
1885
+ // structural reason, which is exactly what clears the hold and delivers
1886
+ // the text to the next attempt.
1887
+ const wf = need(args, 1, 'workflow');
1888
+ const path = need(args, 2, 'path');
1889
+ const question = need(args, 3, 'question');
1890
+ engine.ask(wf, path, last(args, 'by') ?? 'human', question);
1891
+ print(io, { ok: true, action: 'ask', path, question });
1892
+ return 0;
1893
+ }
1894
+ case 'inbox': {
1895
+ // THE OPERATOR SURFACE for `ask`. Without it the channel is write-only:
1896
+ // a step can raise a question and nothing ever displays it, which is
1897
+ // the exact failure this whole change exists to end. Reads the LOCAL db
1898
+ // across every instance (no workflow argument) because a person asking
1899
+ // "is anything waiting on me?" does not know which instance to name.
1900
+ //
1901
+ // Each row carries the ready-to-paste release command, because the
1902
+ // answer path (`retry --text`) is not guessable from the question.
1903
+ const rows = [];
1904
+ for (const w of store.listWorkflows()) {
1905
+ let st;
1906
+ try {
1907
+ st = engine.status(w.id);
1908
+ }
1909
+ catch {
1910
+ // An instance whose def no longer resolves cannot be asked about;
1911
+ // skip it rather than aborting the sweep (same stance as `--all`).
1912
+ continue;
1913
+ }
1914
+ for (const d of st.debts) {
1915
+ if (d.question === undefined)
1916
+ continue;
1917
+ rows.push({
1918
+ workflow: w.id,
1919
+ def: w.def,
1920
+ title: w.title ?? null,
1921
+ path: d.path,
1922
+ question: d.question,
1923
+ answer: `owenloop retry ${w.id} ${d.path} --text "<your answer>"`,
1924
+ });
1925
+ }
1926
+ }
1927
+ print(io, rows);
1928
+ return 0;
1929
+ }
1877
1930
  case 'close': {
1878
1931
  const wf = need(args, 1, 'workflow');
1879
1932
  const run = need(args, 2, 'run');
@@ -218,7 +218,7 @@ export type EngineEvent = {
218
218
  workflow: string;
219
219
  run?: string;
220
220
  path: string;
221
- action: 'green' | 'emit' | 'seal' | 'reject' | 'retract' | 'skip' | 'retry' | 'provide';
221
+ action: 'green' | 'emit' | 'seal' | 'reject' | 'retract' | 'skip' | 'retry' | 'provide' | 'ask';
222
222
  outcome?: CommitResult['outcome'] | EmitResult['outcome'];
223
223
  } | {
224
224
  type: 'closed';
@@ -777,12 +777,57 @@ export declare class Engine {
777
777
  retract(workflow: string, path: string, by: Author, text: string): void;
778
778
  /** A producer skips its own owed output on a dead branch (§16.1 routing). */
779
779
  skip(workflow: string, path: string, by: Author, text: string): void;
780
+ /**
781
+ * ESCALATION: a producing step stops and asks a human, instead of guessing.
782
+ *
783
+ * WHY THIS IS A SEPARATE VERB AND NOT A FLAVOUR OF `reject`. `reject` is a
784
+ * *verdict on a built version* — it refuses any artifact that is not `green`
785
+ * or `submitted` (see the guard in `reject()`), because bumping
786
+ * `judgmentRejects` on a never-built `owed` artifact would burn stall budget
787
+ * with zero build attempts and silently freeze the producer. `ask` targets
788
+ * exactly that state: the artifact the asking step still OWES and has decided
789
+ * it cannot honestly build. Different precondition, different counter policy,
790
+ * different author — so, a different method.
791
+ *
792
+ * WHAT IT CLOSES. Before this verb a step agent that could not proceed had two
793
+ * options, and both were observed damaging real runs:
794
+ * 1. Submit something it did not believe. The artifact greens and every
795
+ * downstream step builds on a fabrication.
796
+ * 2. End its turn without submitting. The task re-arms, a fresh worker
797
+ * starts from the same missing information, and the step retries until
798
+ * it hits the stall cap — burning budget to relearn the same blocker.
799
+ * Neither ever reaches a person. `ask` is the third option.
800
+ *
801
+ * MECHANICS. The artifact moves `owed` → `rejected` with a trailing reason of
802
+ * kind `'question'`. `isHeld` (model.ts) recognises that kind, so `frozen()`
803
+ * is true and the engine stops re-arming the producer — no retry storm. NO
804
+ * counter moves: `judgmentRejects` and `schemaRejects` are untouched, because
805
+ * a question is not a failed attempt and must not consume stall budget.
806
+ *
807
+ * THE ANSWER IS `retry`. There is deliberately no `answer` verb. A human runs
808
+ * `owenloop retry <workflow> <path> --text "<answer>"`, which appends a
809
+ * `'structural'` reason — clearing held-ness automatically, since `isHeld`
810
+ * reads only the LAST entry — re-arms the artifact to `owed`, and leaves the
811
+ * answer sitting on the reason thread that the next fresh worker reads in its
812
+ * order. Two ways into held, one way out.
813
+ *
814
+ * AUTHORITY. Not `assertAuthority`: that follows the CONSUME edge (who may
815
+ * invalidate someone else's work), and this is the opposite direction — the
816
+ * producer speaking about its own debt. So the rule is that `by` must be the
817
+ * artifact's own producer (or `human`/`engine`).
818
+ */
819
+ ask(workflow: string, path: string, by: Author, question: string): void;
780
820
  /**
781
821
  * Human stall-clearing lever (§6): reset an artifact's judgment-reject count
782
822
  * and re-arm it to `owed`, optionally appending a line of guiding context that
783
823
  * rides to the next producer on the order's `owes` thread. This is how a
784
824
  * stalled (capped-out) artifact gets unstuck and steered, rather than thrashing
785
825
  * forever or being abandoned. For a stuck collection member, `retract` instead.
826
+ *
827
+ * This is ALSO the answer path for `ask` above — `retry --text "<answer>"`
828
+ * appends a `'structural'` reason, which clears held-ness and delivers the
829
+ * answer to the next worker on the same thread. There is no separate
830
+ * `answer` verb by design.
786
831
  */
787
832
  retry(workflow: string, path: string, by?: Author, text?: string): void;
788
833
  /** Close a run (audit/budget) and release its lease so the task can re-arm. */
@@ -2096,12 +2096,84 @@ export class Engine {
2096
2096
  this.fire({ type: 'commit', workflow, path, action: 'skip' });
2097
2097
  this.fireSettled(workflow);
2098
2098
  }
2099
+ /**
2100
+ * ESCALATION: a producing step stops and asks a human, instead of guessing.
2101
+ *
2102
+ * WHY THIS IS A SEPARATE VERB AND NOT A FLAVOUR OF `reject`. `reject` is a
2103
+ * *verdict on a built version* — it refuses any artifact that is not `green`
2104
+ * or `submitted` (see the guard in `reject()`), because bumping
2105
+ * `judgmentRejects` on a never-built `owed` artifact would burn stall budget
2106
+ * with zero build attempts and silently freeze the producer. `ask` targets
2107
+ * exactly that state: the artifact the asking step still OWES and has decided
2108
+ * it cannot honestly build. Different precondition, different counter policy,
2109
+ * different author — so, a different method.
2110
+ *
2111
+ * WHAT IT CLOSES. Before this verb a step agent that could not proceed had two
2112
+ * options, and both were observed damaging real runs:
2113
+ * 1. Submit something it did not believe. The artifact greens and every
2114
+ * downstream step builds on a fabrication.
2115
+ * 2. End its turn without submitting. The task re-arms, a fresh worker
2116
+ * starts from the same missing information, and the step retries until
2117
+ * it hits the stall cap — burning budget to relearn the same blocker.
2118
+ * Neither ever reaches a person. `ask` is the third option.
2119
+ *
2120
+ * MECHANICS. The artifact moves `owed` → `rejected` with a trailing reason of
2121
+ * kind `'question'`. `isHeld` (model.ts) recognises that kind, so `frozen()`
2122
+ * is true and the engine stops re-arming the producer — no retry storm. NO
2123
+ * counter moves: `judgmentRejects` and `schemaRejects` are untouched, because
2124
+ * a question is not a failed attempt and must not consume stall budget.
2125
+ *
2126
+ * THE ANSWER IS `retry`. There is deliberately no `answer` verb. A human runs
2127
+ * `owenloop retry <workflow> <path> --text "<answer>"`, which appends a
2128
+ * `'structural'` reason — clearing held-ness automatically, since `isHeld`
2129
+ * reads only the LAST entry — re-arms the artifact to `owed`, and leaves the
2130
+ * answer sitting on the reason thread that the next fresh worker reads in its
2131
+ * order. Two ways into held, one way out.
2132
+ *
2133
+ * AUTHORITY. Not `assertAuthority`: that follows the CONSUME edge (who may
2134
+ * invalidate someone else's work), and this is the opposite direction — the
2135
+ * producer speaking about its own debt. So the rule is that `by` must be the
2136
+ * artifact's own producer (or `human`/`engine`).
2137
+ */
2138
+ ask(workflow, path, by, question) {
2139
+ const def = this.defFor(workflow);
2140
+ this.store.tx(() => {
2141
+ const art = this.store.getArtifact(workflow, path);
2142
+ if (!art)
2143
+ throw new Error(`cannot ask about unknown artifact: ${path}`);
2144
+ if (by !== 'human' && by !== 'engine' && art.producer !== by) {
2145
+ throw new Error(`${by} has no authority to ask about ${path} (it is produced by '${art.producer}'). ` +
2146
+ `\`ask\` is the producer speaking about its own debt; to send someone else's work back, use \`reject\`.`);
2147
+ }
2148
+ // A question is only meaningful about work not yet delivered. On a
2149
+ // `green`/`submitted` artifact the honest move is `reject` (there is a
2150
+ // version to have an opinion about); on `retracted`/`skipped` there is no
2151
+ // live debt left to answer.
2152
+ if (art.acceptance !== 'owed' && art.acceptance !== 'rejected') {
2153
+ throw new Error(`cannot ask about '${path}' in state '${art.acceptance}': ` +
2154
+ `\`ask\` records a blocker on work still owed (owed|rejected)`);
2155
+ }
2156
+ this.store.putArtifact({
2157
+ ...art,
2158
+ acceptance: 'rejected',
2159
+ reasons: [...art.reasons, reason('ask', 'question', by, question, art.version)],
2160
+ });
2161
+ this.settle(workflow, def);
2162
+ });
2163
+ this.fire({ type: 'commit', workflow, path, action: 'ask' });
2164
+ this.fireSettled(workflow);
2165
+ }
2099
2166
  /**
2100
2167
  * Human stall-clearing lever (§6): reset an artifact's judgment-reject count
2101
2168
  * and re-arm it to `owed`, optionally appending a line of guiding context that
2102
2169
  * rides to the next producer on the order's `owes` thread. This is how a
2103
2170
  * stalled (capped-out) artifact gets unstuck and steered, rather than thrashing
2104
2171
  * forever or being abandoned. For a stuck collection member, `retract` instead.
2172
+ *
2173
+ * This is ALSO the answer path for `ask` above — `retry --text "<answer>"`
2174
+ * appends a `'structural'` reason, which clears held-ness and delivers the
2175
+ * answer to the next worker on the same thread. There is no separate
2176
+ * `answer` verb by design.
2105
2177
  */
2106
2178
  retry(workflow, path, by = 'human', text = 'retry: stall cleared') {
2107
2179
  const def = this.defFor(workflow);
@@ -35,7 +35,7 @@ export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefP
35
35
  export type { PolicyFloorGap, PolicyFloorMergeResult, PolicyFloorVerdict, VerifyPolicyFloorInput, VerifyPolicyFloorOptions, } from './crypto/index.ts';
36
36
  export { ORIGIN_SOURCE_RANK, OriginRulesError, evaluateOriginRule, matchOriginRule, parseOriginRules, } from './crypto/index.ts';
37
37
  export type { OriginPolicy, OriginRuleEvaluation, OriginRuleMatch, OriginRuleValue, OriginRules, } from './crypto/index.ts';
38
- export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
38
+ export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isHeld, isStalled, modelCheck, openQuestion, workflowStatus, } from './model.ts';
39
39
  export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
40
40
  export { parseConsume, parseProduce, } from './paths.ts';
41
41
  export { assertValidSchema, summarizeIssues, validateValue } from './schema.ts';
package/dist/src/index.js CHANGED
@@ -30,7 +30,7 @@ export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelo
30
30
  export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefPolicyMinimum, mergePolicyFloorWithLocal, originRulesMinimum, policyFloorGaps, stricterDefPolicy, verifyPolicyFloorRecord, } from "./crypto/index.js";
31
31
  // ---- WP-E2a origin execution policy ----
32
32
  export { ORIGIN_SOURCE_RANK, OriginRulesError, evaluateOriginRule, matchOriginRule, parseOriginRules, } from "./crypto/index.js";
33
- export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
33
+ export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isHeld, isStalled, modelCheck, openQuestion, workflowStatus, } from "./model.js";
34
34
  export { parseConsume, parseProduce, } from "./paths.js";
35
35
  export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
36
36
  export { enrollmentGrantSchema, orderSchema, originSchema, policyFloorSchema, publicationSchema, RECORD_SCHEMAS, revocationSchema, SCHEMA_BY_PAYLOAD_TYPE, submissionSchema, WIRE_SCHEMAS, } from "./schemas/index.js";
@@ -128,12 +128,28 @@ export declare function isStalled(a: ArtifactData | undefined, cap: number): boo
128
128
  */
129
129
  export declare function isSchemaStalled(a: ArtifactData | undefined, cap: number): boolean;
130
130
  /**
131
- * True if the artifact is held (non-idempotent escalate) — rejected-and-held,
132
- * producer not auto-eligible to re-fire. Detected by the last reasons entry
133
- * having kind='invalidated-irreversible'. A retry call appends a 'structural'
134
- * entry, which clears the held condition automatically.
131
+ * True if the artifact is held — rejected-and-held, producer not auto-eligible
132
+ * to re-fire. Detected by the last reasons entry having a holding kind. A retry
133
+ * call appends a 'structural' entry, which clears the held condition
134
+ * automatically, so `retry --text '<answer>'` is the release for both kinds.
135
+ *
136
+ * TWO WAYS IN, ONE WAY OUT.
137
+ * - `invalidated-irreversible`: the engine held it because an input moved under
138
+ * a non-idempotent producer.
139
+ * - `question`: the producing STEP held it, via `Engine.ask`, because it could
140
+ * not proceed honestly and needs a human. Without this second kind an agent
141
+ * has no way to stop: its only alternatives are to submit something it does
142
+ * not believe (which greens and silently poisons every downstream step) or to
143
+ * end its turn without submitting (which re-arms the step into a retry storm
144
+ * whose every worker fails identically). Both were observed in production.
135
145
  */
136
146
  export declare function isHeld(a: ArtifactData | undefined): boolean;
147
+ /**
148
+ * The open question on a held artifact, if it is held by `ask`. Returns the
149
+ * question text so an operator-facing read can print WHAT is being asked
150
+ * instead of only that something is stuck — the whole point of the channel.
151
+ */
152
+ export declare function openQuestion(a: ArtifactData | undefined): string | undefined;
137
153
  /**
138
154
  * §7 escalation trigger: has this artifact been judgment-rejected at least
139
155
  * `after` times in the CURRENT rejection episode?
@@ -293,10 +309,18 @@ export interface WorkflowStatus {
293
309
  debts: Array<{
294
310
  path: string;
295
311
  acceptance: Acceptance;
296
- kind: 'judgment' | 'structural' | 'validation' | 'unbuilt' | 'invalidated-irreversible';
312
+ kind: 'judgment' | 'structural' | 'validation' | 'unbuilt' | 'invalidated-irreversible' | 'question';
297
313
  /** §6/§18/held: rejected past its producer's cap, or held — the engine won't re-arm it */
298
314
  stalled: boolean;
299
315
  reason?: string;
316
+ /**
317
+ * The open question, when `kind === 'question'` — the producing step called
318
+ * `Engine.ask` and stopped waiting on a human. Same string as `reason`,
319
+ * surfaced under its own name so an operator-facing reader can filter for
320
+ * "what is waiting on ME" without pattern-matching a kind. Absent on every
321
+ * other debt shape.
322
+ */
323
+ question?: string;
300
324
  /**
301
325
  * Consecutive trailing `failed` runs for this debt's producer (crash-step
302
326
  * signal). Enriched by `engine.status()` from the run log — `workflowStatus`
package/dist/src/model.js CHANGED
@@ -110,16 +110,39 @@ export function isStalled(a, cap) {
110
110
  export function isSchemaStalled(a, cap) {
111
111
  return !!a && cap > 0 && a.acceptance === 'rejected' && a.schemaRejects >= cap;
112
112
  }
113
+ /** Reason kinds that hold an artifact: the producer is not auto-eligible to re-fire. */
114
+ const HOLDING_KINDS = new Set(['invalidated-irreversible', 'question']);
113
115
  /**
114
- * True if the artifact is held (non-idempotent escalate) — rejected-and-held,
115
- * producer not auto-eligible to re-fire. Detected by the last reasons entry
116
- * having kind='invalidated-irreversible'. A retry call appends a 'structural'
117
- * entry, which clears the held condition automatically.
116
+ * True if the artifact is held — rejected-and-held, producer not auto-eligible
117
+ * to re-fire. Detected by the last reasons entry having a holding kind. A retry
118
+ * call appends a 'structural' entry, which clears the held condition
119
+ * automatically, so `retry --text '<answer>'` is the release for both kinds.
120
+ *
121
+ * TWO WAYS IN, ONE WAY OUT.
122
+ * - `invalidated-irreversible`: the engine held it because an input moved under
123
+ * a non-idempotent producer.
124
+ * - `question`: the producing STEP held it, via `Engine.ask`, because it could
125
+ * not proceed honestly and needs a human. Without this second kind an agent
126
+ * has no way to stop: its only alternatives are to submit something it does
127
+ * not believe (which greens and silently poisons every downstream step) or to
128
+ * end its turn without submitting (which re-arms the step into a retry storm
129
+ * whose every worker fails identically). Both were observed in production.
118
130
  */
119
131
  export function isHeld(a) {
120
132
  if (!a || a.acceptance !== 'rejected')
121
133
  return false;
122
- return a.reasons.length > 0 && a.reasons[a.reasons.length - 1].kind === 'invalidated-irreversible';
134
+ return a.reasons.length > 0 && HOLDING_KINDS.has(a.reasons[a.reasons.length - 1].kind);
135
+ }
136
+ /**
137
+ * The open question on a held artifact, if it is held by `ask`. Returns the
138
+ * question text so an operator-facing read can print WHAT is being asked
139
+ * instead of only that something is stuck — the whole point of the channel.
140
+ */
141
+ export function openQuestion(a) {
142
+ if (!a || a.acceptance !== 'rejected' || a.reasons.length === 0)
143
+ return undefined;
144
+ const last = a.reasons[a.reasons.length - 1];
145
+ return last.kind === 'question' ? last.text : undefined;
123
146
  }
124
147
  /**
125
148
  * §7 escalation trigger: has this artifact been judgment-rejected at least
@@ -962,18 +985,34 @@ export function workflowStatus(def, arts) {
962
985
  ? 'validation'
963
986
  : last.kind === 'invalidated-irreversible'
964
987
  ? 'invalidated-irreversible'
965
- : 'structural'
988
+ : last.kind === 'question'
989
+ ? 'question'
990
+ : 'structural'
966
991
  : 'unbuilt';
967
992
  const prod = stepByName(def, a.producer);
968
993
  const producePat = prod && produceOwning(prod, a.path);
969
994
  // Held artifacts (isHeld) surface as stalled: true — they require human intervention.
970
- const stalled = !!prod &&
971
- (isStalled(a, effectiveMaxAttempts(prod, producePat)) ||
972
- isSchemaStalled(a, effectiveMaxSchemaFailures(prod, producePat)) ||
973
- isHeld(a));
995
+ //
996
+ // `isHeld` is deliberately OUTSIDE the `prod &&` guard that the two counter
997
+ // caps sit inside. Those caps are read off a producer STEP, so they are
998
+ // meaningless without one — but held-ness is read off the artifact's own
999
+ // reason thread and is just as real for a `producer: human` input. Keeping
1000
+ // it inside the guard meant a human-produced artifact could never be
1001
+ // reported stalled no matter how many times it was rejected, so a run
1002
+ // waiting on a PERSON was indistinguishable from any other owed row. That
1003
+ // is the single thing an operator most needs told.
1004
+ const stalled = isHeld(a) ||
1005
+ (!!prod &&
1006
+ (isStalled(a, effectiveMaxAttempts(prod, producePat)) ||
1007
+ isSchemaStalled(a, effectiveMaxSchemaFailures(prod, producePat))));
974
1008
  const entry = { path: a.path, acceptance: a.acceptance, kind, stalled };
975
1009
  if (last)
976
1010
  entry.reason = last.text;
1011
+ // The question text is already in `reason`, but a caller filtering for
1012
+ // "what is waiting on me" should not have to infer it from a kind string.
1013
+ const q = openQuestion(a);
1014
+ if (q !== undefined)
1015
+ entry.question = q;
977
1016
  debts.push(entry);
978
1017
  }
979
1018
  debts.sort((x, y) => x.path.localeCompare(y.path));
@@ -1173,15 +1212,25 @@ export function buildTrace(def, artifacts, runs) {
1173
1212
  if (e.action === 'retry')
1174
1213
  totalRetries++;
1175
1214
  }
1176
- // Check stall: need the producer step's caps
1215
+ // Check stall. Two independent sources, and they are checked separately
1216
+ // on purpose:
1217
+ // 1. The two counter caps — read off the PRODUCER STEP, so they can only
1218
+ // be evaluated when there is a producer step to read them off.
1219
+ // 2. Held-ness — read off the artifact's own reason thread, so it is
1220
+ // just as true for a `producer: human` input. Checking it inside the
1221
+ // `if (producerStep)` block (as this did until 2026-08-15) meant an
1222
+ // artifact a PERSON owes could never appear in `stalledArtifacts`,
1223
+ // which is exactly the row a trace reader is looking for.
1224
+ let stalled = isHeld(art);
1177
1225
  const producerStep = def.steps.find((l) => l.name === art.producer);
1178
- if (producerStep) {
1226
+ if (!stalled && producerStep) {
1179
1227
  const producePat = produceOwning(producerStep, art.path);
1180
1228
  const stallJ = isStalled(art, effectiveMaxAttempts(producerStep, producePat));
1181
1229
  const stallS = isSchemaStalled(art, effectiveMaxSchemaFailures(producerStep, producePat));
1182
- if (stallJ || stallS)
1183
- stalledArtifacts.push(art.path);
1230
+ stalled = stallJ || stallS;
1184
1231
  }
1232
+ if (stalled)
1233
+ stalledArtifacts.push(art.path);
1185
1234
  const bio = {
1186
1235
  path: art.path,
1187
1236
  producer: art.producer,
@@ -31,9 +31,15 @@ export type Author = 'engine' | 'human' | string;
31
31
  * - `invalidated-irreversible`: the artifact was rejected-and-held because its inputs
32
32
  * moved and its producer step declared `effect: { idempotent: false, onInvalidate: 'escalate' }`.
33
33
  * The producer is NOT auto-eligible to re-fire; a human must intervene (retry / fix upstream).
34
+ * - `question`: the producing step ASKED a human and stopped, via `Engine.ask`.
35
+ * Holds exactly like `invalidated-irreversible` — the producer is not auto-eligible,
36
+ * so the step does not spin re-answering its own unanswered question — but it is a
37
+ * separate kind because the CAUSE is different and the audit trail should say so:
38
+ * nothing moved upstream, an agent decided it could not proceed honestly.
39
+ * Counts toward NO stall budget. A question is not a failed attempt.
34
40
  */
35
- export type RejectKind = 'judgment' | 'structural' | 'validation' | 'invalidated-irreversible' | 'exclusive';
36
- export type ReasonAction = 'reject' | 'retract' | 'skip' | 'reopen' | 'retry' | 'born-rejected' | 'schema-reject' | 'pinned';
41
+ export type RejectKind = 'judgment' | 'structural' | 'validation' | 'invalidated-irreversible' | 'question' | 'exclusive';
42
+ export type ReasonAction = 'reject' | 'retract' | 'skip' | 'reopen' | 'retry' | 'ask' | 'born-rejected' | 'schema-reject' | 'pinned';
37
43
  /** A JSON Schema, as authored in a definition: an object, or a boolean (allow/deny all). */
38
44
  export type JsonSchema = Record<string, unknown> | boolean;
39
45
  /** One entry in an artifact's append-only reason thread (design §4). */