owenloop 0.5.5 → 0.5.7

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 (45) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/packages/work/src/agent/approvals.d.ts +53 -0
  3. package/dist/packages/work/src/agent/approvals.js +132 -0
  4. package/dist/packages/work/src/agent/brief.d.ts +40 -4
  5. package/dist/packages/work/src/agent/brief.js +165 -2
  6. package/dist/packages/work/src/agent/loop.d.ts +4 -0
  7. package/dist/packages/work/src/agent/loop.js +68 -3
  8. package/dist/packages/work/src/harness/claude.d.ts +28 -0
  9. package/dist/packages/work/src/harness/claude.js +193 -22
  10. package/dist/packages/work/src/harness/codex.d.ts +37 -1
  11. package/dist/packages/work/src/harness/codex.js +133 -14
  12. package/dist/packages/work/src/harness/contract.d.ts +79 -21
  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/harness/session-store.d.ts +65 -15
  17. package/dist/packages/work/src/harness/session-store.js +53 -51
  18. package/dist/packages/work/src/hub/client.d.ts +13 -1
  19. package/dist/packages/work/src/hub/client.js +3 -0
  20. package/dist/packages/work/src/hub/types.d.ts +101 -0
  21. package/dist/packages/work/src/main.js +1 -0
  22. package/dist/packages/work/src/roles/agent-run.js +4 -0
  23. package/dist/packages/work/src/roles/approvals.d.ts +76 -0
  24. package/dist/packages/work/src/roles/approvals.js +231 -0
  25. package/dist/packages/work/src/shift/loop.d.ts +2 -0
  26. package/dist/packages/work/src/shift/loop.js +2 -0
  27. package/dist/packages/work/src/shift/runtime.js +23 -7
  28. package/dist/packages/work/src/shift/spawn.d.ts +4 -0
  29. package/dist/packages/work/src/shift/spawn.js +6 -0
  30. package/dist/packages/work/src/usage.d.ts +1 -1
  31. package/dist/packages/work/src/usage.js +5 -0
  32. package/dist/src/crypto/records.d.ts +2 -0
  33. package/dist/src/crypto/records.js +13 -0
  34. package/dist/src/engine.js +5 -1
  35. package/dist/src/model.d.ts +37 -1
  36. package/dist/src/model.js +47 -1
  37. package/dist/src/schemas/index.d.ts +11 -0
  38. package/dist/src/schemas/order.v1.schema.json +9 -0
  39. package/dist/src/types.d.ts +34 -0
  40. package/docs/agent-runner.md +17 -5
  41. package/package.json +1 -1
  42. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  43. package/plugins/claude-code/plugin/.mcp.json +1 -1
  44. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  45. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -1,4 +1,4 @@
1
- import type { AskRequest, AskResponse, 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, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, 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;
@@ -21,6 +21,18 @@ export interface HubClient {
21
21
  * `owenloop retry <workflow> <path> --text "<answer>"`.
22
22
  */
23
23
  ask(req: AskRequest): Promise<AskResponse>;
24
+ /**
25
+ * TOOL APPROVAL — raise AND poll, one idempotent call. The worker is mid-flight
26
+ * and needs yes/no on ONE tool call; unlike `ask`, the session stays alive, the
27
+ * run does not close, and the answer comes back to the very same blocked call.
28
+ * Repeating the call with the same `tool_use_id` re-reads the existing row.
29
+ */
30
+ requestApproval(req: RequestApprovalRequest): Promise<RequestApprovalResponse>;
31
+ /** The HUMAN half — the operator CLI, never a worker. An agent token is
32
+ * refused this verb by the hub's RBAC, deliberately. */
33
+ answerApproval(req: AnswerApprovalRequest): Promise<AnswerApprovalResponse>;
34
+ /** Every approval a worker is currently blocked on, org-wide. */
35
+ listPendingApprovals(): Promise<ListPendingApprovalsResponse>;
24
36
  /**
25
37
  * Plan §6: record what this shift resolved the order's compound capability to,
26
38
  * BEFORE the harness launches. Idempotent on the hub by order id, so a
@@ -83,6 +83,9 @@ export function createHubClient(opts) {
83
83
  submit: (req) => post('submit', req),
84
84
  reject: (req) => post('reject', req),
85
85
  ask: (req) => post('ask', req),
86
+ requestApproval: (req) => post('request_approval', req),
87
+ answerApproval: (req) => post('answer_approval', req),
88
+ listPendingApprovals: () => post('list_pending_approvals', {}),
86
89
  reportResolution: (req) => post('report_resolution', req),
87
90
  whoami: () => get('whoami'),
88
91
  // Cursor is an opaque non-negative integer; omit it entirely to bootstrap
@@ -231,6 +231,23 @@ export interface OrderPacket {
231
231
  judgmentRejects: number;
232
232
  schemaRejects: number;
233
233
  reasons: ReasonEntry[];
234
+ /**
235
+ * The JSON Schema the engine will enforce on this output at commit time,
236
+ * projected off the owning produce entry by a schema-aware hub. Absent
237
+ * when the produce declares none (the common case — any JSON is accepted),
238
+ * and absent from every hub too old to project the field at all. Those two
239
+ * cases are indistinguishable here on purpose: both mean "this worker was
240
+ * told no shape", and the brief says nothing either way rather than
241
+ * claiming an output is unconstrained when it may not be.
242
+ */
243
+ schema?: unknown;
244
+ /**
245
+ * What `schema` governs — `'value'` for the submitted value itself
246
+ * (singleton produce, or one element of a map produce), `'member'` for
247
+ * each member emitted into a collection rather than the seal value the
248
+ * path names. Projected together with `schema` and meaningless without it.
249
+ */
250
+ schemaAppliesTo?: 'value' | 'member';
234
251
  /** Target-protocol reason-thread proof; the deployed hub may omit it. */
235
252
  proof?: string;
236
253
  }>;
@@ -396,6 +413,90 @@ export interface AskResponse extends HubResponse {
396
413
  ok: boolean;
397
414
  closed?: boolean;
398
415
  }
416
+ /**
417
+ * The DETERMINISTIC TOOL-APPROVAL gate — the fine-grained sibling of `ask`, and
418
+ * deliberately not the same mechanism.
419
+ *
420
+ * `ask` is a worker declaring it cannot honestly build what it OWES: it freezes
421
+ * the artifact, CLOSES the run, and its answer reaches a FRESH worker. This is a
422
+ * worker mid-flight needing yes/no on ONE tool call: the session is alive and
423
+ * stays alive, the run does not close, no attempt is burnt, and the answer comes
424
+ * back to the very same blocked call.
425
+ *
426
+ * ONE VERB SERVES BOTH RAISE AND POLL. `toolUseId` is the harness's own id for
427
+ * the blocked call, so a repeat of this request is unambiguously the same
428
+ * question rather than a new one — the hub re-reads the existing row instead of
429
+ * opening a second. A worker therefore raises and polls with identical calls and
430
+ * never has to track whether it already asked.
431
+ *
432
+ * `step` is ABSENT for the same reason it is absent on `ask` and `reject`: the
433
+ * hub derives it from the claiming run's row, so a worker cannot raise an
434
+ * approval stamped to another step.
435
+ */
436
+ export interface RequestApprovalRequest {
437
+ workflow: string;
438
+ run: string;
439
+ /** The harness's id for the blocked call. The approval's identity, with `run`. */
440
+ tool_use_id: string;
441
+ /** The tool the harness was about to invoke, e.g. `Bash`. */
442
+ tool_name: string;
443
+ /** The call's arguments. A non-string is JSON-stringified by the hub edge. */
444
+ tool_input: unknown;
445
+ /** Why the gatekeeper would not allow this on its own — written for a person. */
446
+ reason: string;
447
+ /** The harness's own one-line rendering of the prompt, when it supplies one. */
448
+ title?: string;
449
+ }
450
+ /** `pending` is the only state a worker waits on. An unrecognized stored state
451
+ * reads as `expired` hub-side, never `pending`. */
452
+ export type ApprovalState = 'pending' | 'approved' | 'denied' | 'expired';
453
+ /** One approval as the hub reports it. */
454
+ export interface ApprovalView {
455
+ workflow: string;
456
+ run: string;
457
+ toolUseId: string;
458
+ /** Derived hub-side from the claiming run — never what the caller said. */
459
+ step: string;
460
+ toolName: string;
461
+ reason: string;
462
+ title: string;
463
+ state: ApprovalState;
464
+ requestedAt: number;
465
+ decidedAt: number | null;
466
+ decidedBy: string | null;
467
+ note: string | null;
468
+ }
469
+ /**
470
+ * `ok: false` with `reason: 'not-held'` means the claim this approval belonged
471
+ * to is gone — the worker's lease ended while it waited. That is a REFUSAL, not
472
+ * a denial: nothing was written, and there is no longer anyone the answer could
473
+ * come back to.
474
+ */
475
+ export interface RequestApprovalResponse extends HubResponse {
476
+ ok: boolean;
477
+ reason?: string;
478
+ approval?: ApprovalView;
479
+ }
480
+ /** The human half. Not called by a worker — an agent token is deliberately
481
+ * refused this verb, because an agent that could answer its own approval could
482
+ * approve every call it was just refused. */
483
+ export interface AnswerApprovalRequest {
484
+ workflow: string;
485
+ run: string;
486
+ tool_use_id: string;
487
+ decision: 'approve' | 'deny';
488
+ note?: string;
489
+ }
490
+ export interface AnswerApprovalResponse extends HubResponse {
491
+ ok: boolean;
492
+ reason?: string;
493
+ approval?: ApprovalView;
494
+ }
495
+ /** Only approvals whose worker is STILL holding its lease — a question nobody
496
+ * is waiting on is not shown, because answering it would do nothing. */
497
+ export interface ListPendingApprovalsResponse extends HubResponse {
498
+ approvals: ApprovalView[];
499
+ }
399
500
  export interface WhoamiResponse extends HubResponse {
400
501
  orgId: string;
401
502
  orgName: string;
@@ -26,6 +26,7 @@ const ROLES = {
26
26
  release: () => import("./roles/release.js"),
27
27
  join: () => import("./roles/join.js"),
28
28
  sessions: () => import("./roles/sessions.js"),
29
+ approvals: () => import("./roles/approvals.js"),
29
30
  };
30
31
  export async function mainAsync(argv) {
31
32
  const [first, ...rest] = argv;
@@ -338,6 +338,8 @@ export async function run(args, deps = {}) {
338
338
  const client = hub;
339
339
  await loadHarnessModule(env['OWENLOOP_HARNESS_MODULE'], err);
340
340
  const shiftId = resolveShiftId(parsed.shift, env);
341
+ const shiftName = env['OWENLOOP_SHIFT_NAME'];
342
+ const shiftOwner = env['OWENLOOP_SHIFT_OWNER'];
341
343
  const holder = {
342
344
  kind: 'exec',
343
345
  id: deps.holderId ?? `${hostname()}:${process.pid}`,
@@ -495,6 +497,8 @@ export async function run(args, deps = {}) {
495
497
  origin,
496
498
  account,
497
499
  ...(shiftId !== undefined ? { shiftId } : {}),
500
+ ...(shiftName !== undefined && shiftName !== '' ? { shiftName } : {}),
501
+ ...(shiftOwner !== undefined && shiftOwner !== '' ? { shiftOwner } : {}),
498
502
  cwd: workCwd,
499
503
  // Machine policy, resolved from the SAME two sources the shift resolves it
500
504
  // from: `OWENLOOP_ALLOWED_WORKDIR_ROOTS` (which `owenloop shift start`
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `owenloop work approvals` — THE OPERATOR SURFACE for the tool-approval gate.
3
+ *
4
+ * WHY THIS EXISTS AT ALL. Without it the channel is write-only: a worker blocks
5
+ * on a person, the hub records the question, and nothing on any human's machine
6
+ * ever displays it. That is the exact failure this whole feature was built to
7
+ * end, so the reader half ships in the same change as the writer half rather
8
+ * than in a follow-up.
9
+ *
10
+ * WHAT AN APPROVAL IS, AND WHAT IT IS NOT. Three human-in-the-loop mechanisms
11
+ * exist and they are not interchangeable:
12
+ *
13
+ * - a pending GATE is an input nobody has provided yet; answered with
14
+ * `owenloop provide`.
15
+ * - an `ask` is a worker saying it cannot honestly build what it OWES. The
16
+ * step ends, the run closes `no_work`, and the answer reaches a FRESH
17
+ * worker later; answered with `owenloop retry --text`.
18
+ * - an APPROVAL — this file — is a worker that is STILL RUNNING and blocked
19
+ * mid-flight on one tool call. Its session is alive and stays alive, the run
20
+ * does not close, and the answer goes back to that very call.
21
+ *
22
+ * The practical consequence for whoever is reading this list: an approval is the
23
+ * only one of the three where somebody is waiting RIGHT NOW. Every one shown
24
+ * here has a worker parked on it.
25
+ *
26
+ * WHY THERE IS A DEADLINE ON THE WORKER SIDE AND NOT HERE. The waiting process
27
+ * gives up after its own window and treats the non-answer as a denial, so an
28
+ * unanswered approval costs the run one honest `ask` rather than a hang. This
29
+ * command therefore cannot promise that an answer will land — it can only
30
+ * deliver one while the worker is still listening. Answering promptly is the
31
+ * whole point of the list.
32
+ *
33
+ * COMMANDS
34
+ * owenloop work approvals [--json] every approval a worker is blocked on
35
+ * owenloop work approvals approve <wf>/<run> <tool-use-id> [--note <text>]
36
+ * owenloop work approvals deny <wf>/<run> <tool-use-id> [--note <text>]
37
+ *
38
+ * The decision is a positional VERB rather than an `--approve` flag, because a
39
+ * flag that grants a dangerous command is one typo away from being omitted, and
40
+ * an omitted flag has to mean something. A verb cannot be omitted.
41
+ *
42
+ * Origin and bearer resolve exactly as in `release`: `--origin` → settings
43
+ * `hubOrigin`, and the `agent:<account>` credential slot for `OWENLOOP_ACCOUNT`
44
+ * (default `default`). The hub refuses `answer_approval` to an agent token by
45
+ * design — this verb is for a person's key.
46
+ *
47
+ * Exit codes: 0 on success (including an empty list) · 1 on a hub/network error
48
+ * · 2 on a usage error.
49
+ */
50
+ import { type HubClient } from '../hub/client.ts';
51
+ type Action = 'list' | 'approve' | 'deny';
52
+ interface ParsedArgs {
53
+ action: Action;
54
+ order?: string;
55
+ toolUseId?: string;
56
+ note?: string;
57
+ origin?: string;
58
+ json?: boolean;
59
+ error?: string;
60
+ }
61
+ /** Parse the subcommand and its flags, in both `--flag value` and `--flag=value` forms. */
62
+ export declare function parseArgs(args: string[]): ParsedArgs;
63
+ /** Split `<workflow>/<run>`. A run id is opaque, so only the FIRST slash splits. */
64
+ export declare function splitOrder(order: string): {
65
+ workflow: string;
66
+ run: string;
67
+ } | undefined;
68
+ export interface RunDeps {
69
+ hub?: HubClient;
70
+ out?: (line: string) => void;
71
+ err?: (line: string) => void;
72
+ env?: Record<string, string | undefined>;
73
+ now?: () => number;
74
+ }
75
+ export declare function run(args: string[], deps?: RunDeps): Promise<number>;
76
+ export {};
@@ -0,0 +1,231 @@
1
+ /**
2
+ * `owenloop work approvals` — THE OPERATOR SURFACE for the tool-approval gate.
3
+ *
4
+ * WHY THIS EXISTS AT ALL. Without it the channel is write-only: a worker blocks
5
+ * on a person, the hub records the question, and nothing on any human's machine
6
+ * ever displays it. That is the exact failure this whole feature was built to
7
+ * end, so the reader half ships in the same change as the writer half rather
8
+ * than in a follow-up.
9
+ *
10
+ * WHAT AN APPROVAL IS, AND WHAT IT IS NOT. Three human-in-the-loop mechanisms
11
+ * exist and they are not interchangeable:
12
+ *
13
+ * - a pending GATE is an input nobody has provided yet; answered with
14
+ * `owenloop provide`.
15
+ * - an `ask` is a worker saying it cannot honestly build what it OWES. The
16
+ * step ends, the run closes `no_work`, and the answer reaches a FRESH
17
+ * worker later; answered with `owenloop retry --text`.
18
+ * - an APPROVAL — this file — is a worker that is STILL RUNNING and blocked
19
+ * mid-flight on one tool call. Its session is alive and stays alive, the run
20
+ * does not close, and the answer goes back to that very call.
21
+ *
22
+ * The practical consequence for whoever is reading this list: an approval is the
23
+ * only one of the three where somebody is waiting RIGHT NOW. Every one shown
24
+ * here has a worker parked on it.
25
+ *
26
+ * WHY THERE IS A DEADLINE ON THE WORKER SIDE AND NOT HERE. The waiting process
27
+ * gives up after its own window and treats the non-answer as a denial, so an
28
+ * unanswered approval costs the run one honest `ask` rather than a hang. This
29
+ * command therefore cannot promise that an answer will land — it can only
30
+ * deliver one while the worker is still listening. Answering promptly is the
31
+ * whole point of the list.
32
+ *
33
+ * COMMANDS
34
+ * owenloop work approvals [--json] every approval a worker is blocked on
35
+ * owenloop work approvals approve <wf>/<run> <tool-use-id> [--note <text>]
36
+ * owenloop work approvals deny <wf>/<run> <tool-use-id> [--note <text>]
37
+ *
38
+ * The decision is a positional VERB rather than an `--approve` flag, because a
39
+ * flag that grants a dangerous command is one typo away from being omitted, and
40
+ * an omitted flag has to mean something. A verb cannot be omitted.
41
+ *
42
+ * Origin and bearer resolve exactly as in `release`: `--origin` → settings
43
+ * `hubOrigin`, and the `agent:<account>` credential slot for `OWENLOOP_ACCOUNT`
44
+ * (default `default`). The hub refuses `answer_approval` to an agent token by
45
+ * design — this verb is for a person's key.
46
+ *
47
+ * Exit codes: 0 on success (including an empty list) · 1 on a hub/network error
48
+ * · 2 on a usage error.
49
+ */
50
+ import { createHubClient } from "../hub/client.js";
51
+ import { resolveBearer } from "../credentials/resolve.js";
52
+ import { loadSettings } from "../settings/settings.js";
53
+ /** Parse the subcommand and its flags, in both `--flag value` and `--flag=value` forms. */
54
+ export function parseArgs(args) {
55
+ const first = args[0];
56
+ const action = first === 'approve' ? 'approve' : first === 'deny' ? 'deny' : 'list';
57
+ // `list` is the default AND an explicit word; anything else that is not a flag
58
+ // is a positional belonging to the decision verbs.
59
+ const rest = first === 'approve' || first === 'deny' || first === 'list' ? args.slice(1) : args;
60
+ const parsed = { action };
61
+ const positionals = [];
62
+ for (let i = 0; i < rest.length; i++) {
63
+ const a = rest[i];
64
+ if (!a.startsWith('--')) {
65
+ positionals.push(a);
66
+ continue;
67
+ }
68
+ const eq = a.indexOf('=');
69
+ const name = eq === -1 ? a : a.slice(0, eq);
70
+ if (name === '--json') {
71
+ parsed.json = true;
72
+ continue;
73
+ }
74
+ if (name !== '--note' && name !== '--origin')
75
+ return { action, error: `unknown option '${a}'` };
76
+ let value;
77
+ if (eq !== -1)
78
+ value = a.slice(eq + 1);
79
+ else {
80
+ const next = rest[i + 1];
81
+ if (next === undefined)
82
+ return { action, error: `missing value for ${a}` };
83
+ value = next;
84
+ i += 1;
85
+ }
86
+ if (name === '--note')
87
+ parsed.note = value;
88
+ else
89
+ parsed.origin = value;
90
+ }
91
+ if (action === 'list') {
92
+ if (positionals.length > 0)
93
+ return { action, error: `unexpected argument '${positionals[0]}'` };
94
+ return parsed;
95
+ }
96
+ const [order, toolUseId, extra] = positionals;
97
+ if (order === undefined)
98
+ return { action, error: 'missing <workflow>/<run>' };
99
+ if (toolUseId === undefined)
100
+ return { action, error: 'missing <tool-use-id>' };
101
+ if (extra !== undefined)
102
+ return { action, error: `unexpected argument '${extra}'` };
103
+ parsed.order = order;
104
+ parsed.toolUseId = toolUseId;
105
+ return parsed;
106
+ }
107
+ /** Split `<workflow>/<run>`. A run id is opaque, so only the FIRST slash splits. */
108
+ export function splitOrder(order) {
109
+ const slash = order.indexOf('/');
110
+ if (slash <= 0 || slash === order.length - 1)
111
+ return undefined;
112
+ return { workflow: order.slice(0, slash), run: order.slice(slash + 1) };
113
+ }
114
+ function usage(err) {
115
+ err('usage: owenloop work approvals [--json]');
116
+ err(' owenloop work approvals approve <workflow>/<run> <tool-use-id> [--note <text>]');
117
+ err(' owenloop work approvals deny <workflow>/<run> <tool-use-id> [--note <text>]');
118
+ }
119
+ function errMsg(err) {
120
+ return err instanceof Error ? err.message : String(err);
121
+ }
122
+ /**
123
+ * Render one waiting approval, ending with the exact command that answers it.
124
+ *
125
+ * Printing the answer command is not decoration. Whoever reads this list is
126
+ * being asked to make a judgement under time pressure, and making them assemble
127
+ * a three-part key by hand is how the wrong call gets approved.
128
+ */
129
+ function renderApproval(a, waitedMs) {
130
+ const order = `${a.workflow}/${a.run}`;
131
+ const waited = waitedMs >= 0 ? `${Math.round(waitedMs / 1_000)}s` : 'unknown';
132
+ const lines = [
133
+ `${order} step=${a.step} ${a.toolName} waiting ${waited}`,
134
+ ` why: ${a.reason}`,
135
+ ];
136
+ if (a.title !== '')
137
+ lines.push(` call: ${a.title}`);
138
+ lines.push(` approve: owenloop work approvals approve ${order} ${a.toolUseId}`);
139
+ lines.push(` deny: owenloop work approvals deny ${order} ${a.toolUseId}`);
140
+ return lines;
141
+ }
142
+ export async function run(args, deps = {}) {
143
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
144
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
145
+ const env = deps.env ?? process.env;
146
+ const now = deps.now ?? Date.now;
147
+ const parsed = parseArgs(args);
148
+ if (parsed.error !== undefined) {
149
+ err(`owenloop work approvals: ${parsed.error}`);
150
+ usage(err);
151
+ return 2;
152
+ }
153
+ let split;
154
+ if (parsed.action !== 'list') {
155
+ split = splitOrder(parsed.order);
156
+ if (split === undefined) {
157
+ err(`owenloop work approvals: '${parsed.order}' is not <workflow>/<run>`);
158
+ usage(err);
159
+ return 2;
160
+ }
161
+ }
162
+ let settings;
163
+ try {
164
+ settings = loadSettings(env);
165
+ }
166
+ catch (e) {
167
+ err(`owenloop work approvals: ${errMsg(e)}`);
168
+ return 1;
169
+ }
170
+ const origin = parsed.origin ?? settings.hubOrigin;
171
+ if (origin === undefined || origin.trim() === '') {
172
+ err('owenloop work approvals: no hub origin — pass --origin <url> or set hubOrigin in settings');
173
+ return 2;
174
+ }
175
+ const account = env['OWENLOOP_ACCOUNT'] ?? 'default';
176
+ const bearer = await resolveBearer({ origin, account, env });
177
+ if (!bearer.ok) {
178
+ err(`owenloop work approvals: ${bearer.message}`);
179
+ return bearer.code;
180
+ }
181
+ const token = bearer.token;
182
+ const hub = deps.hub ?? createHubClient({ origin, getToken: async () => token });
183
+ if (parsed.action === 'list') {
184
+ let approvals;
185
+ try {
186
+ approvals = (await hub.listPendingApprovals()).approvals;
187
+ }
188
+ catch (e) {
189
+ err(`owenloop work approvals: ${errMsg(e)}`);
190
+ return 1;
191
+ }
192
+ if (parsed.json === true) {
193
+ out(JSON.stringify(approvals, null, 2));
194
+ return 0;
195
+ }
196
+ if (approvals.length === 0) {
197
+ out('no workers are blocked on an approval');
198
+ return 0;
199
+ }
200
+ const at = now();
201
+ for (const a of approvals) {
202
+ for (const line of renderApproval(a, at - a.requestedAt))
203
+ out(line);
204
+ out('');
205
+ }
206
+ return 0;
207
+ }
208
+ try {
209
+ const res = await hub.answerApproval({
210
+ workflow: split.workflow,
211
+ run: split.run,
212
+ tool_use_id: parsed.toolUseId,
213
+ decision: parsed.action === 'approve' ? 'approve' : 'deny',
214
+ ...(parsed.note !== undefined ? { note: parsed.note } : {}),
215
+ });
216
+ if (res.ok === false) {
217
+ // The common case by far: the worker gave up waiting and the approval is
218
+ // no longer live. Said plainly, because "failed" would read as a bug.
219
+ err(`owenloop work approvals: not answered — ${res.reason ?? 'the approval is no longer pending'}`);
220
+ return 1;
221
+ }
222
+ if (res.text !== '')
223
+ out(res.text);
224
+ out(`${parsed.action}d ${split.workflow}/${split.run} ${parsed.toolUseId}`);
225
+ return 0;
226
+ }
227
+ catch (e) {
228
+ err(`owenloop work approvals: ${errMsg(e)}`);
229
+ return 1;
230
+ }
231
+ }
@@ -30,6 +30,8 @@ export interface ShiftLoopOptions {
30
30
  /** Shift name for presence. INITIAL value only — live-mutable via
31
31
  * `ShiftLoop.setShift` (MCP `clock_in`). */
32
32
  name: string;
33
+ /** Stable owner key for session records; unlike `name`, it is not clocked in. */
34
+ shiftOwner?: string;
33
35
  /**
34
36
  * W7: this Shift process incarnation's self-declared id (`shf_<uuid>`)
35
37
  * and process start time — carried on presence pings (attribution/
@@ -326,6 +326,8 @@ export function createShiftLoop(opts) {
326
326
  run: c.order.run,
327
327
  step: c.order.step,
328
328
  ...(childKind === 'agent-run' ? { kind: 'agent-run' } : {}),
329
+ ...(childKind === 'agent-run' ? { shiftName } : {}),
330
+ ...(childKind === 'agent-run' && opts.shiftOwner !== undefined ? { shiftOwner: opts.shiftOwner } : {}),
329
331
  startGate: reserved.gatePath,
330
332
  });
331
333
  cancel = spawned.cancel ?? spawned.terminate;
@@ -287,6 +287,14 @@ export async function runShiftRuntime(parsed, options = {}) {
287
287
  process.stderr.write(`${roleLabel}: ${errMsg(err)}\n`);
288
288
  return 1;
289
289
  }
290
+ const now = () => Date.now();
291
+ const shiftId = `shf_${randomUUID()}`;
292
+ const startedAt = now();
293
+ const name = resolveShiftName(parsed.name, { shiftId });
294
+ // Explicit names are the human/stable identity. Unnamed shifts deliberately
295
+ // keep their per-boot public suffix for presence uniqueness, so their durable
296
+ // state directory is the stable owner key used by session reconciliation.
297
+ const shiftOwner = parsed.name ?? stateDir;
290
298
  try {
291
299
  ensureStateDir(stateDir);
292
300
  }
@@ -295,12 +303,23 @@ export async function runShiftRuntime(parsed, options = {}) {
295
303
  return 1;
296
304
  }
297
305
  {
298
- const liveRunIds = new Set(reconcileInFlight(stateDir).live.filter((r) => r.kind === 'agent-run').map((r) => r.run));
306
+ // Reconcile the Shift's own dispatch records for capacity housekeeping. The
307
+ // session sweep below must use the session row's PID and ownership fields,
308
+ // not this run-id set, because every Shift on the machine shares the store.
309
+ reconcileInFlight(stateDir);
299
310
  try {
300
- const retired = reconcileActiveSessions(sessionsPath(cacheDir), liveRunIds, Date.now());
311
+ const configuredHarness = env['OWENLOOP_HARNESS'];
312
+ const retired = reconcileActiveSessions(sessionsPath(cacheDir), {
313
+ shiftName: name,
314
+ shiftOwner,
315
+ ...(configuredHarness !== undefined && configuredHarness.trim() !== ''
316
+ ? { harness: configuredHarness }
317
+ : {}),
318
+ }, Date.now());
301
319
  for (const rec of retired) {
302
320
  process.stderr.write(`${roleLabel}: retired orphaned session ${rec.workflow}/${rec.run} step '${rec.step}' ` +
303
- `(harness '${rec.harness}', attempt ${String(rec.attempt ?? 1)}) — its worker is gone, ` +
321
+ `(harness '${rec.harness}', attempt ${String(rec.attempt ?? 1)}, ` +
322
+ `shift '${String(rec.shiftName)}', pid ${String(rec.pid)} confirmed dead) — its worker is gone, ` +
304
323
  'so the next attempt replays cold\n');
305
324
  }
306
325
  }
@@ -361,7 +380,6 @@ export async function runShiftRuntime(parsed, options = {}) {
361
380
  ? parsed.workRoots.map((entry) => resolve(process.cwd(), entry))
362
381
  : resolveAllowedWorkdirRoots(env, settings.allowedWorkdirRoots, process.cwd());
363
382
  const hub = createHubClient({ origin, getToken: async () => token });
364
- const now = () => Date.now();
365
383
  const monotonicNow = () => performance.now();
366
384
  const home = [env.HOME, env.USERPROFILE].find((value) => value !== undefined && value.trim() !== '');
367
385
  // Legacy orders and modern agent orders do not need Shift-side instruction
@@ -383,9 +401,6 @@ export async function runShiftRuntime(parsed, options = {}) {
383
401
  return undefined;
384
402
  return instructionSource.getVerifiedStep(order.defDigest, order.step);
385
403
  };
386
- const shiftId = `shf_${randomUUID()}`;
387
- const startedAt = now();
388
- const name = resolveShiftName(parsed.name, { shiftId });
389
404
  let daemon;
390
405
  /**
391
406
  * `loop` is constructed BELOW this function, so it is captured by reference
@@ -489,6 +504,7 @@ export async function runShiftRuntime(parsed, options = {}) {
489
504
  cap,
490
505
  serveCrews: parsed.serveCrews ?? [],
491
506
  name,
507
+ shiftOwner,
492
508
  commandRouting: settings.commandRouting,
493
509
  resolveOrderStep,
494
510
  pollIntervalMs,
@@ -32,6 +32,10 @@ export interface SpawnSpec {
32
32
  harness?: string;
33
33
  /** Closed start gate created by the durable Shift reservation. */
34
34
  startGate?: string;
35
+ /** Stable shift name in force when this worker was dispatched. */
36
+ shiftName?: string;
37
+ /** Stable owner key for session reconciliation. */
38
+ shiftOwner?: string;
35
39
  }
36
40
  /** The result the loop records plus best-effort pre-start cancellation handles. */
37
41
  export interface SpawnResult {
@@ -170,6 +170,12 @@ export function buildSpawnPlan(spec, origin, account, binPath, execPath = proces
170
170
  ...process.env,
171
171
  OWENLOOP_ACCOUNT: account,
172
172
  ...(spec.startGate !== undefined ? { OWENLOOP_START_GATE: spec.startGate } : {}),
173
+ ...(spec.shiftName !== undefined && spec.shiftName !== ''
174
+ ? { OWENLOOP_SHIFT_NAME: spec.shiftName }
175
+ : {}),
176
+ ...(spec.shiftOwner !== undefined && spec.shiftOwner !== ''
177
+ ? { OWENLOOP_SHIFT_OWNER: spec.shiftOwner }
178
+ : {}),
173
179
  ...(allowedWorkdirRoots !== undefined && allowedWorkdirRoots.length > 0
174
180
  ? { OWENLOOP_ALLOWED_WORKDIR_ROOTS: allowedWorkdirRoots.join(':') }
175
181
  : {}),