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
@@ -84,10 +84,12 @@ function isNonEmptyString(v) {
84
84
  * The non-empty-string fields `isSessionRecord` requires, in the order it checks
85
85
  * them. Declared once and kept stable so a record failing several checks always
86
86
  * reports the SAME field, which keeps the skip message deterministic.
87
- * `status` is not here — its check is a membership test, not a string test — and
88
- * is applied after these, preserving the original check order.
87
+ *
88
+ * `token` is NOT here — see `firstInvalidSessionRecordField`. `status` is not
89
+ * here either: its check is a membership test, not a string test, and is applied
90
+ * after these, preserving the original check order.
89
91
  */
90
- const SESSION_RECORD_STRING_FIELDS = ['workflow', 'run', 'step', 'harness', 'token'];
92
+ const SESSION_RECORD_STRING_FIELDS = ['workflow', 'run', 'step', 'harness'];
91
93
  /**
92
94
  * Name of the first field of `v` that fails the `SessionRecord` schema, or
93
95
  * `null` when the record is valid. `'<root>'` means `v` is not a plain object at
@@ -97,9 +99,43 @@ const SESSION_RECORD_STRING_FIELDS = ['workflow', 'run', 'step', 'harness', 'tok
97
99
  * in terms of this function, so the accept/reject decision and the reported
98
100
  * field name can never drift apart.
99
101
  *
100
- * Checks exactly the fields whose absence would make the record unusable for a
101
- * resume: the three key fields plus the harness and token it exists to carry,
102
- * and a `status` inside the four literals. Everything else is carried verbatim.
102
+ * Checks exactly the fields whose absence would make the record unusable: the
103
+ * three key fields, the harness that says which vendor the row belongs to, a
104
+ * `token` that is a string, and a `status` inside the four literals. Everything
105
+ * else is carried verbatim.
106
+ *
107
+ * ── WHY AN EMPTY `token` IS VALID, THOUGH IT ONCE WAS NOT ────────────────────
108
+ *
109
+ * `token` must be a STRING, but it may be EMPTY. The writer produces an empty
110
+ * one deliberately: `agent/loop.ts` appends a record before the harness emits
111
+ * its `started` event, so that a harness which dies on launch still leaves proof
112
+ * the attempt existed and died. Its own comment says so. Requiring the token to
113
+ * be non-empty here threw exactly those records away — the reader discarded the
114
+ * evidence the writer went out of its way to leave.
115
+ *
116
+ * The cost was not only the lost rows. Every such line was reported on stdout as
117
+ * `field "token" failed schema check`, once per reading process. On this machine
118
+ * that was ~94 lines printed by each of three shifts on every boot: ~280 warning
119
+ * lines about records that were behaving exactly as designed, drowning the
120
+ * warnings that meant something.
121
+ *
122
+ * Nothing downstream is harmed by admitting them, because every consumer already
123
+ * expected the empty case and guarded for it BEFORE this change:
124
+ * - `agent/loop.ts` requires `prev.token !== ''` to resume, with a comment
125
+ * naming this exact case ("the record predates its `started` event").
126
+ * - `roles/sessions.ts` renders no resume command for one.
127
+ * - `shouldRetireSession` reads `pid`/owner/`status` and never the token.
128
+ *
129
+ * The guard in the loop is in fact PROOF of the intent: it is unreachable code
130
+ * unless records with an empty token can be read back.
131
+ *
132
+ * ── WHY `key` IS CHECKED ONLY WHEN PRESENT ───────────────────────────────────
133
+ *
134
+ * `key` was added after rows already existed, so ABSENT is legal and means "this
135
+ * row predates the field". PRESENT-BUT-NOT-A-STRING is not legal: it would be a
136
+ * row nobody wrote, and `latestForTask` would silently mis-key it. `''` is a
137
+ * perfectly good key — it is what an unfanned step carries — so emptiness is
138
+ * never the test here.
103
139
  */
104
140
  function firstInvalidSessionRecordField(v) {
105
141
  if (typeof v !== 'object' || v === null || Array.isArray(v))
@@ -109,6 +145,13 @@ function firstInvalidSessionRecordField(v) {
109
145
  if (!isNonEmptyString(r[field]))
110
146
  return field;
111
147
  }
148
+ // Checked after `harness` and before `status`, which is where it sat when it
149
+ // was a non-empty check, so a record failing several fields still reports the
150
+ // same one it always did.
151
+ if (typeof r['token'] !== 'string')
152
+ return 'token';
153
+ if (r['key'] !== undefined && typeof r['key'] !== 'string')
154
+ return 'key';
112
155
  if (typeof r['status'] !== 'string' || !STATUSES.has(r['status']))
113
156
  return 'status';
114
157
  return null;
@@ -286,6 +329,11 @@ export function readSessions(file, opts = {}) {
286
329
  // debugging after a file-integrity problem that did not exist. The second
287
330
  // pass runs only on this failure branch, so valid records pay nothing.
288
331
  // The field NAME only, never its value — `token` is credential-shaped.
332
+ //
333
+ // Those empty-`token` records are no longer invalid at all — the schema
334
+ // admits them now (see `firstInvalidSessionRecordField`). Reaching this
335
+ // branch therefore means something genuinely wrong with the record, which
336
+ // is what makes the line worth printing.
289
337
  const badField = firstInvalidSessionRecordField(parsed) ?? '<unknown>';
290
338
  warn(`owenloop work sessions: skipping invalid record at ${file}:${i + 1}: field "${badField}" failed schema check`);
291
339
  continue;
@@ -295,9 +343,19 @@ export function readSessions(file, opts = {}) {
295
343
  return out;
296
344
  }
297
345
  /**
298
- * The newest record for `(workflow, run, step)`, or `null` when the file is
299
- * missing or holds no match. Scans forward and keeps the LAST match (last-wins).
300
- * Side-effect-free — it never writes, never compacts, and never throws.
346
+ * The newest record for `(workflow, run, step)` — that is, for ONE FIRING of one
347
+ * step — or `null` when the file is missing or holds no match. Scans forward and
348
+ * keeps the LAST match (last-wins). Side-effect-free: it never writes, never
349
+ * compacts, and never throws.
350
+ *
351
+ * ── THIS IS THE PER-FIRING LOOKUP. IT CANNOT FIND A PREVIOUS FIRING. ─────────
352
+ *
353
+ * The hub mints a fresh `run` id every time it claims a step. Two firings of the
354
+ * same step therefore NEVER share a `run`, so this function can only ever return
355
+ * a record written during the very firing that is asking. Use it for questions
356
+ * that really are about one firing — "did THIS firing already take a work dir?",
357
+ * "which sessions belong to the run I am tearing down?" — and never to ask "has
358
+ * this step run before?". That second question is `latestForTask`.
301
359
  */
302
360
  export function latestFor(file, workflow, run, step) {
303
361
  const want = keyOf(workflow, run, step);
@@ -308,6 +366,43 @@ export function latestFor(file, workflow, run, step) {
308
366
  }
309
367
  return best;
310
368
  }
369
+ /** Identity of an engine TASK. Same JSON-array encoding as `keyOf`, and for the
370
+ * same reason: no combination of field values can collide into one key. */
371
+ function taskKeyOf(task) {
372
+ return JSON.stringify([task.workflow, task.step, task.key]);
373
+ }
374
+ /**
375
+ * The newest record for an engine TASK — the last session recorded for this
376
+ * step at this key, no matter which firing wrote it — or `null` when there is
377
+ * none. Last-wins, side-effect-free, same as `latestFor`.
378
+ *
379
+ * ── WHY THIS EXISTS ALONGSIDE `latestFor` ────────────────────────────────────
380
+ *
381
+ * `latestFor` keys on `run`, which the hub re-mints per firing, so it answers
382
+ * "what happened during THIS firing?". Resume needs the opposite question: "did
383
+ * a previous firing of this same step leave a session I can re-enter?" Only
384
+ * `(workflow, step, key)` survives long enough to answer that.
385
+ *
386
+ * ── WHY A ROW WITHOUT `key` NEVER MATCHES ────────────────────────────────────
387
+ *
388
+ * Rows written before `key` existed carry no task identity at all. Guessing one
389
+ * — treating absent as `''`, say — would attribute an unfanned row and a fanned
390
+ * row to the same task and hand a worker someone else's session. Skipping them
391
+ * costs only a cold start on the first firing after upgrade, which is the safe
392
+ * direction to be wrong in. The test is `=== undefined`, because `''` is a real
393
+ * key that must match.
394
+ */
395
+ export function latestForTask(file, task) {
396
+ const want = taskKeyOf(task);
397
+ let best = null;
398
+ for (const rec of readSessions(file)) {
399
+ if (rec.key === undefined)
400
+ continue;
401
+ if (taskKeyOf({ workflow: rec.workflow, step: rec.step, key: rec.key }) === want)
402
+ best = rec;
403
+ }
404
+ return best;
405
+ }
311
406
  /** The lock shared by append and compaction for one session log. */
312
407
  function writerLockPath(file) {
313
408
  return `${file}.lock`;
@@ -1,4 +1,4 @@
1
- import type { AnswerApprovalRequest, AnswerApprovalResponse, AskRequest, AskResponse, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, ReportResolutionRequest, ReportResolutionResponse, SubmitRequest, SubmitResponse, WakeResponse, WhatsNextRequest, WhatsNextResponse, WhoamiResponse } from './types.ts';
1
+ import type { AnswerApprovalRequest, AnswerApprovalResponse, AskRequest, AskResponse, GetRostersResponse, ListHarnessModelsResponse, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, RetryArtifactRequest, RetryArtifactResponse, ReportResolutionRequest, ReportResolutionResponse, SubmitRequest, SubmitResponse, WakeResponse, WhatsNextRequest, WhatsNextResponse, WhoamiResponse } from './types.ts';
2
2
  export interface HubClientOptions {
3
3
  /** Hub origin, e.g. `https://hub.owenloop.dev` (no trailing slash needed). */
4
4
  origin: string;
@@ -8,7 +8,7 @@ export interface HubClientOptions {
8
8
  fetchImpl?: typeof fetch;
9
9
  }
10
10
  export interface HubClient {
11
- whatsNext(req?: WhatsNextRequest): Promise<WhatsNextResponse>;
11
+ whatsNext(req: WhatsNextRequest): Promise<WhatsNextResponse>;
12
12
  getOrder(req: GetOrderRequest): Promise<GetOrderResponse>;
13
13
  heartbeat(req: HeartbeatRequest): Promise<HeartbeatResponse>;
14
14
  release(req: ReleaseRequest): Promise<ReleaseResponse>;
@@ -18,9 +18,20 @@ export interface HubClient {
18
18
  * ESCALATION: the worker stops and asks a human about an artifact it OWES.
19
19
  * Distinct from `reject`, which is a verdict on somebody else's delivered
20
20
  * work. Holds the artifact (no counter moves) until a human answers with
21
- * `owenloop retry <workflow> <path> --text "<answer>"`.
21
+ * `owenloop retry <workflow> <path> --text "<answer>"`, or with
22
+ * `retryArtifact` on this client.
22
23
  */
23
24
  ask(req: AskRequest): Promise<AskResponse>;
25
+ /**
26
+ * The HUMAN half of the escalation channel and the answer to `ask` above:
27
+ * re-arm a stalled or rejected artifact to `owed`, resetting its reject
28
+ * counters. `text` rides to the next producer on the artifact's reason
29
+ * thread. Omit `text` for a bare stall-clear — the engine supplies its own
30
+ * default, so do NOT default it here. Human-only by hub RBAC; an agent
31
+ * token is refused. Optional on this interface for the same reason
32
+ * `getRosters` is: it was added after the existing HubClient fakes.
33
+ */
34
+ retryArtifact?(req: RetryArtifactRequest): Promise<RetryArtifactResponse>;
24
35
  /**
25
36
  * TOOL APPROVAL — raise AND poll, one idempotent call. The worker is mid-flight
26
37
  * and needs yes/no on ONE tool call; unlike `ask`, the session stays alive, the
@@ -39,7 +50,11 @@ export interface HubClient {
39
50
  * re-dispatch no-ops rather than overwriting the first (pre-spend) record.
40
51
  */
41
52
  reportResolution(req: ReportResolutionRequest): Promise<ReportResolutionResponse>;
42
- whoami(): Promise<WhoamiResponse>;
53
+ whoami(signal?: AbortSignal): Promise<WhoamiResponse>;
54
+ /** Read the org's roster cascade using this caller's scoped identity. */
55
+ getRosters?(signal?: AbortSignal): Promise<GetRostersResponse>;
56
+ /** Read the hub's known harness/model registry. */
57
+ listHarnessModels?(): Promise<ListHarnessModelsResponse>;
43
58
  /** B5 cheap wake pre-check; `cursor` rides the query string only when set. */
44
59
  wake(cursor?: number): Promise<WakeResponse>;
45
60
  /** B4 Shift presence register/refresh. */
@@ -67,27 +67,31 @@ export function createHubClient(opts) {
67
67
  });
68
68
  return parse(res);
69
69
  }
70
- async function get(verb, query) {
70
+ async function get(verb, query, signal) {
71
71
  const url = query !== undefined && query !== '' ? `${base}/api/${verb}?${query}` : `${base}/api/${verb}`;
72
72
  const res = await fetchImpl(url, {
73
73
  method: 'GET',
74
74
  headers: await authHeaders(),
75
+ ...(signal === undefined ? {} : { signal }),
75
76
  });
76
77
  return parse(res);
77
78
  }
78
79
  return {
79
- whatsNext: (req = {}) => post('whats_next', req),
80
+ whatsNext: (req) => post('whats_next', req),
80
81
  getOrder: (req) => post('get_order', req),
81
82
  heartbeat: (req) => post('heartbeat', req),
82
83
  release: (req) => post('release', req),
83
84
  submit: (req) => post('submit', req),
84
85
  reject: (req) => post('reject', req),
85
86
  ask: (req) => post('ask', req),
87
+ retryArtifact: (req) => post('retry_artifact', req),
86
88
  requestApproval: (req) => post('request_approval', req),
87
89
  answerApproval: (req) => post('answer_approval', req),
88
90
  listPendingApprovals: () => post('list_pending_approvals', {}),
89
91
  reportResolution: (req) => post('report_resolution', req),
90
- whoami: () => get('whoami'),
92
+ whoami: (signal) => get('whoami', undefined, signal),
93
+ getRosters: (signal) => get('rosters', undefined, signal),
94
+ listHarnessModels: () => get('harness_models'),
91
95
  // Cursor is an opaque non-negative integer; omit it entirely to bootstrap
92
96
  // (the hub treats missing/invalid as a `changed: true` first sweep).
93
97
  wake: (cursor) => get('wake', typeof cursor === 'number' ? `cursor=${encodeURIComponent(String(cursor))}` : undefined),
@@ -11,6 +11,12 @@ export interface WhatsNextRequest {
11
11
  workflow?: string;
12
12
  /** Server-side filter for which serve crews this caller will accept. */
13
13
  serve_crews?: string[];
14
+ /**
15
+ * Capability keys in this shift's effective merged rosters. Keys are raw:
16
+ * bare names and exact compounds may be mixed; the hub applies bare-name
17
+ * matching. An empty array legitimately means the shift serves nothing.
18
+ */
19
+ serve_capabilities: string[];
14
20
  }
15
21
  /**
16
22
  * One work order from a per-workflow `whats_next` sweep. `run` is the order
@@ -26,6 +32,14 @@ export interface WorkOrder {
26
32
  key?: string;
27
33
  index?: number;
28
34
  defDigest?: string;
35
+ /** The composed capabilities the hub offered this order under. */
36
+ capabilities?: string[];
37
+ /**
38
+ * THE CREWS THE HUB MATCHED for this order's capabilities, in match order.
39
+ * Hub → worker; this is not `serve_crews`, which travels worker → hub to
40
+ * narrow the orders a shift wants.
41
+ */
42
+ crews?: string[];
29
43
  /** Authoritative worker lane on modern whats_next responses. */
30
44
  worker?: string;
31
45
  consumedFingerprint?: Record<string, number>;
@@ -112,6 +126,12 @@ export interface WakeResponse extends HubResponse {
112
126
  export interface PresencePingRequest {
113
127
  name: string;
114
128
  serve_crews?: string[];
129
+ /**
130
+ * Capability keys in this shift's effective merged rosters. Keys are raw:
131
+ * bare names and exact compounds may be mixed; the hub applies bare-name
132
+ * matching. An empty array legitimately means the shift serves nothing.
133
+ */
134
+ serve_capabilities: string[];
115
135
  shift_id?: string;
116
136
  started_at?: number;
117
137
  /** Epoch-millisecond timestamp of the last accepted local shift attendance. */
@@ -185,13 +205,31 @@ export interface OrderPacket {
185
205
  /**
186
206
  * THE COMPOSED CAPABILITIES this order was offered under, in the step's
187
207
  * authored order — `['build:deep']` for a `build` step on a `deep` run. This
188
- * is the key into the shift's `capabilityModels` map (see
189
- * `src/agent/capability-model.ts`), and therefore what decides which model and
190
- * effort run. Absent from a pre-modifier hub, which is why the worker treats
208
+ * is the key into the shift's merged crew roster (see
209
+ * `src/agent/capability-model.ts`), and therefore what decides which
210
+ * harness, model, and effort run. Absent from a pre-modifier hub, which is why the worker treats
191
211
  * an empty list as "nothing to resolve against" and refuses rather than
192
212
  * guessing.
193
213
  */
194
214
  capabilities?: string[];
215
+ /**
216
+ * THE CREWS THE HUB MATCHED for this order's capabilities, in match order.
217
+ *
218
+ * Hub → worker. This is the hub's answer to "whose roster decides the model
219
+ * for this order", computed at offer time from `capability_routes`. The
220
+ * worker resolves each named crew's merged roster IN THIS ORDER and takes the
221
+ * first crew that carries a row for one of `capabilities`.
222
+ *
223
+ * NOT `serve_crews`. `serve_crews` travels the other way — worker → hub,
224
+ * on `whats_next`/`presence_ping` — and narrows WHICH ORDERS THIS SHIFT
225
+ * WANTS. This field narrows WHICH ROSTER DECIDES an order the shift already
226
+ * has.
227
+ *
228
+ * Optional on the wire because a hub that predates the stamp sends nothing.
229
+ * It is NOT optional in effect: a worker built from this commit REFUSES every
230
+ * capability-bearing order that arrives without it. There is no fallback.
231
+ */
232
+ crews?: string[];
195
233
  /** The run's routing modifier (`deep`), as the caller asked for at start_run. */
196
234
  modifier?: string;
197
235
  /**
@@ -261,6 +299,7 @@ export interface ReasonEntry {
261
299
  by: string;
262
300
  text: string;
263
301
  fromVersion?: number;
302
+ requested?: string;
264
303
  }
265
304
  export interface GetOrderResponse extends HubResponse {
266
305
  workflow: string;
@@ -384,6 +423,22 @@ export interface RejectResponse extends HubResponse {
384
423
  ok: boolean;
385
424
  closed?: boolean;
386
425
  }
426
+ /**
427
+ * The HUMAN stall-clearing lever and answer path for ask. Re-arms a stalled or
428
+ * rejected artifact to owed, resetting its reject counters. text rides to the
429
+ * next producer on the artifact's reason thread; omit it for a bare
430
+ * stall-clear so the engine supplies its own default.
431
+ */
432
+ export interface RetryArtifactRequest {
433
+ workflow: string;
434
+ path: string;
435
+ text?: string;
436
+ }
437
+ /** The retry-artifact verb's flattened response envelope. */
438
+ export interface RetryArtifactResponse extends HubResponse {
439
+ ok: boolean;
440
+ closed?: boolean;
441
+ }
387
442
  /**
388
443
  * ESCALATION: the claiming worker cannot honestly build what it owes and stops
389
444
  * to ask a person. `path` is one of the order's OWED paths — unlike `reject`,
@@ -510,6 +565,35 @@ export interface WhoamiResponse extends HubResponse {
510
565
  authMethod: 'token' | 'oauth' | 'session' | 'debug';
511
566
  email?: string;
512
567
  }
568
+ /** One model choice in an org-owned roster row. */
569
+ export interface RosterCandidateWire {
570
+ harness: string;
571
+ model: string;
572
+ effort: string;
573
+ }
574
+ /** The agent-readable org roster cascade. */
575
+ export interface GetRostersResponse extends HubResponse {
576
+ global: Record<string, RosterCandidateWire[]>;
577
+ crews: Array<{
578
+ crewId: string;
579
+ crewName: string | null;
580
+ roster: Record<string, RosterCandidateWire[]>;
581
+ }>;
582
+ }
583
+ /** The hub's current harness/model registry, for roster administration. */
584
+ export interface ListHarnessModelsResponse extends HubResponse {
585
+ harnesses: Array<{
586
+ harness: string;
587
+ displayName: string;
588
+ }>;
589
+ models: Array<{
590
+ harness: string;
591
+ model: string;
592
+ efforts: string[];
593
+ updatedAt: number;
594
+ updatedBy: string;
595
+ }>;
596
+ }
513
597
  /**
514
598
  * Thrown for any non-2xx hub response. `code` is the hub's `error` slug
515
599
  * (e.g. `bad_request`) when the body parsed as the hub's `{ error, message }`
@@ -27,6 +27,7 @@ const ROLES = {
27
27
  join: () => import("./roles/join.js"),
28
28
  sessions: () => import("./roles/sessions.js"),
29
29
  approvals: () => import("./roles/approvals.js"),
30
+ util: () => import("./roles/util.js"),
30
31
  };
31
32
  export async function mainAsync(argv) {
32
33
  const [first, ...rest] = argv;
@@ -86,16 +86,17 @@ import "../harnesses.js";
86
86
  // ─────────────────────────────────────────────────────────────────────────────
87
87
  import { hostname } from 'node:os';
88
88
  import { resolveCacheDir } from "../bundle/cache.js";
89
- import { createAgentRunLoop } from "../agent/loop.js";
89
+ import { createAgentRunLoop, } from "../agent/loop.js";
90
90
  import { createDefaultStoreInstructionResolver } from "../exec/instructions.js";
91
91
  import { createConsumedVerifier } from "../consumed-verifier.js";
92
92
  import { createHubClient } from "../hub/client.js";
93
93
  import { resolveBearer } from "../credentials/resolve.js";
94
94
  import { loadSettings } from "../settings/settings.js";
95
+ import { effectiveRosterLayers, mergeRosterLayers } from "../settings/roster.js";
95
96
  import { adapterFor, defaultHarnessId, registeredHarnessIds } from "../harness/registry.js";
96
97
  import { parseHarnessCarrier } from "../bundle/fetch.js";
97
98
  import { normalizeStepPermissions, validateHarnessOptions } from "../harness/permissions.js";
98
- import { appendSession, latestFor, sessionsPath } from "../harness/session-store.js";
99
+ import { appendSession, latestForTask, sessionsPath, } from "../harness/session-store.js";
99
100
  import { ensureWorkDir, resolveAllowedWorkdirRoots, resolveWorkRepo, resolveWorkRoot, } from "../agent/workdir.js";
100
101
  import { resolveShiftId, resolveTarget } from "./hold.js";
101
102
  import { installSignalHandlers } from "./signals.js";
@@ -154,8 +155,6 @@ export function parseArgs(args) {
154
155
  else if (name === '--shift')
155
156
  parsed.shift = r.value;
156
157
  else if (name === '--harness') {
157
- if (r.value.trim() === '')
158
- return { error: '--harness must be a non-empty harness id' };
159
158
  parsed.harness = r.value;
160
159
  }
161
160
  else {
@@ -199,6 +198,8 @@ export function exitCodeFor(outcome) {
199
198
  case 'no-template':
200
199
  case 'no-harness':
201
200
  case 'incompatible-harness-policy':
201
+ case 'unstamped-order':
202
+ case 'unresolvable-crew':
202
203
  case 'unresolvable-capability':
203
204
  case 'unverified-consumed':
204
205
  case 'session-store-failed':
@@ -220,8 +221,8 @@ export function exitCodeFor(outcome) {
220
221
  * adapter at all. What it still buys is the ability for a drill to register a
221
222
  * FAKE adapter inside a real spawned child without the child reaching for a
222
223
  * real CLI. Production leaves the variable unset and this is a no-op. Drills
223
- * that use it also pin `OWENLOOP_HARNESS=fake`, because the statically
224
- * imported real adapters now occupy the front of the registry and would
224
+ * that use it select a fake adapter through a roster candidate, because the
225
+ * statically imported real adapters occupy the front of the registry and would
225
226
  * otherwise win the `defaultHarnessId()` tie-break. A failed import is
226
227
  * reported and then ignored — resolution proceeds and fails honestly with
227
228
  * `'no-harness'` if nothing ended up registered.
@@ -265,12 +266,6 @@ export async function run(args, deps = {}) {
265
266
  err(`owenloop work agent-run: ${errMsg(e)}`);
266
267
  return 1;
267
268
  }
268
- // Passed through verbatim. `loadSettings` already validated every row (shape,
269
- // effort on the ladder, effort accepted by a known model), so there is nothing
270
- // left to normalize here — and nothing to default: an absent map means the
271
- // loop refuses capability-bearing orders, which is the intended answer for a
272
- // shift that never declared what serves what.
273
- const capabilityModels = settings.capabilityModels;
274
269
  const origin = parsed.origin ?? settings.hubOrigin;
275
270
  if (origin === undefined || origin.trim() === '') {
276
271
  err('owenloop work agent-run: no hub origin — pass --origin <url> or set hubOrigin in settings');
@@ -325,6 +320,20 @@ export async function run(args, deps = {}) {
325
320
  'Authenticate the account instead: `owenloop login --hub <origin> --as agent:<account>`.');
326
321
  }
327
322
  const account = workerEnv['OWENLOOP_ACCOUNT'] ?? 'default';
323
+ // The crews the HUB STAMPED on the order decide which rosters apply, so this
324
+ // runs per order inside the loop — the stamp does not exist at process start.
325
+ const resolveCrewRosters = (crews) => {
326
+ const rosters = [];
327
+ for (const crew of crews) {
328
+ try {
329
+ rosters.push(mergeRosterLayers(effectiveRosterLayers(env, crew, { origin, account })));
330
+ }
331
+ catch (e) {
332
+ return { ok: false, crew, detail: errMsg(e) };
333
+ }
334
+ }
335
+ return { ok: true, rosters };
336
+ };
328
337
  let hub = deps.hub;
329
338
  if (hub === undefined) {
330
339
  const bearer = await resolveBearer({ origin, account, env: workerEnv });
@@ -346,36 +355,22 @@ export async function run(args, deps = {}) {
346
355
  ...(shiftId !== undefined ? { shiftId } : {}),
347
356
  };
348
357
  /**
349
- * Adapter id precedence: `--harness` > `OWENLOOP_HARNESS` > the step def's
350
- * `harness` field > the first registered adapter. Every rank is a plain
351
- * string comparison — nothing here knows what any id MEANS.
358
+ * The winning roster candidate is deliberately above the debug --harness
359
+ * flag: it extends the existing rule that resolved routing wins over a
360
+ * step's authored model and effort. Every rank is a plain string comparison.
352
361
  */
353
- const envHarness = env['OWENLOOP_HARNESS'];
354
- const resolveAdapter = (stepHarness) => {
355
- let id;
356
- if (parsed.harness !== undefined) {
357
- id = parsed.harness;
358
- }
359
- else if (envHarness !== undefined) {
360
- // Definition and default selection are lower precedence. An explicit empty
361
- // environment override is invalid; it must not silently fall through.
362
- if (envHarness.trim() === '') {
363
- return {
364
- id: '<empty OWENLOOP_HARNESS>',
365
- registered: registeredHarnessIds(),
366
- };
367
- }
368
- id = envHarness;
369
- }
370
- else {
371
- id =
372
- (stepHarness !== undefined && stepHarness !== '' ? stepHarness : undefined) ??
373
- defaultHarnessId() ??
374
- '';
375
- }
362
+ const resolveAdapter = (chosenHarness, stepHarness) => {
363
+ const id = chosenHarness ??
364
+ parsed.harness ??
365
+ (stepHarness !== undefined && stepHarness !== '' ? stepHarness : undefined) ??
366
+ defaultHarnessId() ??
367
+ '';
376
368
  const adapter = id !== '' ? adapterFor(id) : undefined;
377
369
  return {
378
- id: id !== '' ? id : '<none>',
370
+ // Keep an explicit blank `--harness` visible to the refusal instead of
371
+ // silently treating it as an absent override and selecting the default.
372
+ // A roster candidate still outranks it at the line above.
373
+ id: id !== '' || parsed.harness !== undefined ? id : '<none>',
379
374
  ...(adapter !== undefined ? { adapter } : {}),
380
375
  registered: registeredHarnessIds(),
381
376
  };
@@ -509,16 +504,24 @@ export async function run(args, deps = {}) {
509
504
  allowedWorkdirRoots: resolveAllowedWorkdirRoots(env, settings.allowedWorkdirRoots, process.cwd()),
510
505
  loadStep,
511
506
  resolveAdapter,
512
- ...(capabilityModels !== undefined ? { capabilityModels } : {}),
507
+ resolveCrewRosters,
508
+ // Phase-1 availability means registry membership. A real binary or
509
+ // credential probe requires new HarnessAdapter contract surface.
510
+ harnessAvailable: (id) => adapterFor(id) !== undefined,
513
511
  consumedVerifier,
514
512
  appendSession: writeSession,
515
- nextAttempt: (workflow, run, step) => {
516
- const prev = latestFor(sessionsFile, workflow, run, step);
513
+ // Both readers key on the engine TASK — `(workflow, step, key)` — and not on
514
+ // `(workflow, run, step)`. The hub mints a fresh run id every time it claims
515
+ // a step, so a run-keyed lookup can only ever see records written by the
516
+ // firing that is asking: `nextAttempt` returned 1 forever and `latestSession`
517
+ // returned null forever, which made the whole resume path unreachable.
518
+ nextAttempt: (task) => {
519
+ const prev = latestForTask(sessionsFile, task);
517
520
  return prev === null ? 1 : prev.attempt + 1;
518
521
  },
519
522
  // PHASE 4: the same reader `nextAttempt` uses, handed to the loop whole so
520
523
  // it can decide resume vs cold replay. Reads only; the loop is what writes.
521
- latestSession: (workflow, run, step) => latestFor(sessionsFile, workflow, run, step),
524
+ latestSession: (task) => latestForTask(sessionsFile, task),
522
525
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
523
526
  now: () => Date.now(),
524
527
  out,
@@ -130,6 +130,8 @@ export function exitCodeFor(outcome) {
130
130
  case 'hub-unreachable':
131
131
  case 'submit-rejected':
132
132
  case 'submit-failed':
133
+ case 'command-failed':
134
+ case 'ask-failed':
133
135
  case 'judge-no-verdict':
134
136
  case 'reject-failed':
135
137
  case 'stopped':
@@ -47,8 +47,9 @@ export declare function formatAge(ms: number): string;
47
47
  /**
48
48
  * The resume command for one record, or `undefined` when there is none.
49
49
  *
50
- * Three separate reasons there may be none, all rendered the same way in the
51
- * table because the operator's next move is identical in each: the record names
50
+ * Four separate reasons there may be none, all rendered the same way in the
51
+ * table because the operator's next move is identical in each: the record
52
+ * carries no session token, so there is nothing to resume INTO; the record names
52
53
  * a harness this build does not register (an old row after an adapter was
53
54
  * removed); the adapter registers but implements no interactive resume; or the
54
55
  * adapter threw. The throw is caught rather than propagated because this is a
@@ -98,14 +98,21 @@ function shellQuote(s) {
98
98
  /**
99
99
  * The resume command for one record, or `undefined` when there is none.
100
100
  *
101
- * Three separate reasons there may be none, all rendered the same way in the
102
- * table because the operator's next move is identical in each: the record names
101
+ * Four separate reasons there may be none, all rendered the same way in the
102
+ * table because the operator's next move is identical in each: the record
103
+ * carries no session token, so there is nothing to resume INTO; the record names
103
104
  * a harness this build does not register (an old row after an adapter was
104
105
  * removed); the adapter registers but implements no interactive resume; or the
105
106
  * adapter threw. The throw is caught rather than propagated because this is a
106
107
  * LISTING — one bad row must not take down the other rows with it.
107
108
  */
108
109
  export function resumeCommandFor(rec) {
110
+ // An empty token is a real, readable record: the worker writes one before the
111
+ // harness emits `started`, so a launch that died still leaves proof it existed.
112
+ // Handing that empty string to `resumeCommand` would print a command that
113
+ // cannot work, which is worse than printing nothing.
114
+ if (rec.token === '')
115
+ return undefined;
109
116
  const adapter = adapterFor(rec.harness);
110
117
  if (adapter?.resumeCommand === undefined)
111
118
  return undefined;
@@ -16,13 +16,15 @@ import { inspectSettings, KNOWN_SETTINGS_KEYS } from "../settings/settings.js";
16
16
  /**
17
17
  * Built-in defaults shown for knobs absent from the file (else `unset`).
18
18
  *
19
- * `capabilityModels` is deliberately absent: it HAS no built-in default. A shift
19
+ * `roster` is deliberately absent: it HAS no built-in default. A shift
20
20
  * with no row for an order's capability refuses that order rather than falling
21
21
  * back to some default model, so printing a default here would describe
22
22
  * behaviour that does not exist.
23
23
  */
24
24
  const DEFAULT_NOTE = {
25
25
  dispatchCap: '3',
26
+ execReserve: '1',
27
+ localQueueHoldMs: '0',
26
28
  commandRouting: 'shift',
27
29
  defPolicy: 'warn',
28
30
  };