owenloop 0.5.6 → 0.5.8

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 (82) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +3 -6
  3. package/dist/packages/work/src/agent/approvals.d.ts +53 -0
  4. package/dist/packages/work/src/agent/approvals.js +132 -0
  5. package/dist/packages/work/src/agent/brief.d.ts +12 -0
  6. package/dist/packages/work/src/agent/brief.js +51 -0
  7. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  8. package/dist/packages/work/src/agent/capability-model.js +94 -91
  9. package/dist/packages/work/src/agent/loop.d.ts +43 -25
  10. package/dist/packages/work/src/agent/loop.js +135 -50
  11. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  12. package/dist/packages/work/src/exec/loop.js +37 -15
  13. package/dist/packages/work/src/harness/child-env.js +4 -5
  14. package/dist/packages/work/src/harness/claude.d.ts +4 -0
  15. package/dist/packages/work/src/harness/claude.js +72 -3
  16. package/dist/packages/work/src/harness/codex.d.ts +37 -1
  17. package/dist/packages/work/src/harness/codex.js +136 -18
  18. package/dist/packages/work/src/harness/contract.d.ts +54 -1
  19. package/dist/packages/work/src/harness/session-store.d.ts +127 -17
  20. package/dist/packages/work/src/harness/session-store.js +157 -60
  21. package/dist/packages/work/src/hub/client.d.ts +13 -1
  22. package/dist/packages/work/src/hub/client.js +3 -0
  23. package/dist/packages/work/src/hub/types.d.ts +104 -3
  24. package/dist/packages/work/src/main.js +1 -0
  25. package/dist/packages/work/src/roles/agent-run.js +52 -42
  26. package/dist/packages/work/src/roles/approvals.d.ts +76 -0
  27. package/dist/packages/work/src/roles/approvals.js +231 -0
  28. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  29. package/dist/packages/work/src/roles/sessions.js +9 -2
  30. package/dist/packages/work/src/roles/settings.js +1 -1
  31. package/dist/packages/work/src/settings/roster.d.ts +21 -0
  32. package/dist/packages/work/src/settings/roster.js +80 -0
  33. package/dist/packages/work/src/settings/settings.d.ts +12 -24
  34. package/dist/packages/work/src/settings/settings.js +17 -35
  35. package/dist/packages/work/src/shift/loop.d.ts +2 -0
  36. package/dist/packages/work/src/shift/loop.js +2 -0
  37. package/dist/packages/work/src/shift/runtime.js +17 -9
  38. package/dist/packages/work/src/shift/spawn.d.ts +10 -53
  39. package/dist/packages/work/src/shift/spawn.js +28 -60
  40. package/dist/packages/work/src/usage.d.ts +1 -1
  41. package/dist/packages/work/src/usage.js +8 -4
  42. package/dist/src/capabilities.d.ts +44 -0
  43. package/dist/src/capabilities.js +38 -0
  44. package/dist/src/cli.d.ts +1 -0
  45. package/dist/src/cli.js +460 -5
  46. package/dist/src/config-dir.d.ts +13 -18
  47. package/dist/src/config-dir.js +15 -23
  48. package/dist/src/credentials.d.ts +1 -1
  49. package/dist/src/credentials.js +1 -1
  50. package/dist/src/crypto/records.d.ts +3 -0
  51. package/dist/src/crypto/records.js +19 -0
  52. package/dist/src/crypto/trust-roots.d.ts +2 -2
  53. package/dist/src/crypto/trust-roots.js +2 -2
  54. package/dist/src/engine.d.ts +14 -0
  55. package/dist/src/engine.js +26 -14
  56. package/dist/src/global-config.d.ts +4 -7
  57. package/dist/src/global-config.js +4 -7
  58. package/dist/src/hub.d.ts +207 -5
  59. package/dist/src/hub.js +263 -3
  60. package/dist/src/index.d.ts +2 -2
  61. package/dist/src/index.js +1 -1
  62. package/dist/src/model.d.ts +37 -1
  63. package/dist/src/model.js +47 -1
  64. package/dist/src/schemas/index.d.ts +19 -0
  65. package/dist/src/schemas/order.v1.schema.json +15 -1
  66. package/dist/src/store/pre-commit-verifier.js +1 -1
  67. package/dist/src/types.d.ts +58 -4
  68. package/dist/src/work-settings.d.ts +2 -4
  69. package/dist/src/work-settings.js +2 -4
  70. package/docs/agent-runner.md +2 -2
  71. package/docs/bundles.md +3 -1
  72. package/docs/cli.md +295 -101
  73. package/docs/crypto.md +14 -14
  74. package/docs/routing.md +607 -0
  75. package/docs/shift-logs.md +22 -6
  76. package/package.json +1 -1
  77. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/claude-code/plugin/.mcp.json +1 -1
  79. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  80. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  81. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  82. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
@@ -266,10 +266,9 @@ function isPlainMap(v) {
266
266
  const MOUNT_ENV_KEEP = ['HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME'];
267
267
  /**
268
268
  * `OWENLOOP_CONFIG_DIR` rides the `OWENLOOP_*` allowlist below rather than this
269
- * list, but it belongs to the same job: without it a mount whose parent scoped
270
- * owenloop's config with `OWENLOOP_CONFIG_DIR` would fall back to
271
- * `XDG_CONFIG_HOME` and read a DIFFERENT settings file than the shift that
272
- * spawned it.
269
+ * list, but it belongs to the same job: without it a mount whose parent uses an
270
+ * explicit configuration root would instead use its inherited HOME-rooted
271
+ * settings directory.
273
272
  */
274
273
  /**
275
274
  * The environment for the owenloop mount, forwarded from THIS process.
@@ -670,17 +669,94 @@ function createTurnGate(onEvent) {
670
669
  },
671
670
  };
672
671
  }
672
+ const BRIDGEABLE_APPROVALS = Object.freeze({
673
+ 'item/commandExecution/requestApproval': { kind: 'exec', toolName: 'command', legacy: false },
674
+ 'item/fileChange/requestApproval': { kind: 'file', toolName: 'file-change', legacy: false },
675
+ 'execCommandApproval': { kind: 'exec', toolName: 'command', legacy: true },
676
+ 'applyPatchApproval': { kind: 'patch', toolName: 'file-change', legacy: true },
677
+ });
678
+ /** Join a legacy `command: string[]` (or pass a v2 `command: string`) for display. */
679
+ function commandText(value) {
680
+ if (Array.isArray(value)) {
681
+ const parts = value.filter((p) => typeof p === 'string');
682
+ return parts.length > 0 ? parts.join(' ') : undefined;
683
+ }
684
+ return str(value);
685
+ }
686
+ /**
687
+ * Turn one approval request into the question a person will actually read.
688
+ *
689
+ * The identity (`toolUseId`) has to be stable for the life of the call and
690
+ * unique among live calls, because the hub keys the approval on it. `itemId` /
691
+ * `callId` is that identity; `approvalId` is appended when present, since one
692
+ * item can raise several callbacks (the zsh-exec-bridge case) and collapsing
693
+ * them would let one answer decide two commands.
694
+ *
695
+ * `toolInput` is trimmed rather than forwarded whole. The raw params carry full
696
+ * file diffs and policy-amendment proposals, and a hub row nobody can read is
697
+ * not evidence — the command and the paths are what the decision turns on.
698
+ */
699
+ function describeApproval(shape, params) {
700
+ const p = asMap(params);
701
+ const base = str(p['itemId']) ?? str(p['callId']) ?? 'unknown';
702
+ const callback = str(p['approvalId']);
703
+ const toolUseId = `${shape.kind}:${base}${callback !== undefined ? `:${callback}` : ''}`;
704
+ const command = commandText(p['command']);
705
+ const cwd = str(p['cwd']);
706
+ const files = Object.keys(asMap(p['fileChanges']));
707
+ const grantRoot = str(p['grantRoot']);
708
+ const detail = command !== undefined
709
+ ? command
710
+ : files.length > 0
711
+ ? `writes ${files.join(', ')}`
712
+ : grantRoot !== undefined
713
+ ? `writes under ${grantRoot}`
714
+ : 'a change this harness would not make on its own';
715
+ return {
716
+ toolUseId,
717
+ toolName: shape.toolName,
718
+ toolInput: {
719
+ ...(command !== undefined ? { command } : {}),
720
+ ...(cwd !== undefined ? { cwd } : {}),
721
+ ...(files.length > 0 ? { files } : {}),
722
+ ...(grantRoot !== undefined ? { grantRoot } : {}),
723
+ },
724
+ // The harness's own words when it supplied them. When it did not, say WHY
725
+ // this arrived rather than inventing a hazard nobody assessed: the step's
726
+ // approval policy is what escalated it.
727
+ reason: str(p['reason']) ??
728
+ "the step's approval policy escalated this call instead of running it unattended",
729
+ title: cap(detail),
730
+ };
731
+ }
673
732
  /**
674
733
  * Answer every server→client request. An unanswered one hangs the turn past the
675
734
  * worker's lease, which is the single worst outcome available in this file.
676
735
  *
677
- * Exactly ONE thing is auto-approved — a tool call on owenloop's own MCP mount,
678
- * see the `mcpServer/elicitation/request` case. Everything else is refused:
679
- * under `approvalPolicy:'never'` a command/file approval request should not
680
- * arrive at all; if one does, throwing (which the client turns into a JSON-RPC
681
- * error reply) is a loud, non-hanging failure, whereas inventing an approval the
682
- * policy said would never be asked for is a security decision this adapter is
683
- * not authorized to make.
736
+ * TWO THINGS CAN BE GRANTED WITHOUT A PERSON, and only two.
737
+ *
738
+ * 1. A tool call on owenloop's own MCP mount — see the
739
+ * `mcpServer/elicitation/request` case.
740
+ * 2. Nothing else.
741
+ *
742
+ * WHAT CHANGED WHEN THE APPROVAL CHANNEL LANDED. The four requests in
743
+ * `BRIDGEABLE_APPROVALS` used to be refused with a throw, on the reasoning that
744
+ * "inventing an approval the policy said would never be asked for is a security
745
+ * decision this adapter is not authorized to make". That reasoning still holds
746
+ * exactly — and it is why `approvals` is the ONLY thing that changes it. With a
747
+ * requester wired in, this adapter is no longer inventing anything: it is
748
+ * relaying a question to a person and replying with THEIR answer. With no
749
+ * requester, the old refusal is what still happens, byte for byte.
750
+ *
751
+ * A REFUSAL IS NEVER A HANG. Every path here replies: an approval becomes
752
+ * `accept`/`approved`, and a denial, a deadline, an unreachable hub, or a
753
+ * requester that throws all become `decline`/`denied` plus a `progress` line
754
+ * naming the cause. On the legacy pair the person's reason travels back to the
755
+ * model inside `{denied:{rejection}}`; the v2 decision enum has no message
756
+ * field, so there the reason reaches the log and not the model.
757
+ *
758
+ * `item/permissions/requestApproval` is still refused unconditionally — see
759
+ * `BRIDGEABLE_APPROVALS` for why a permission profile is not a yes/no question.
684
760
  *
685
761
  * `item/tool/requestUserInput` and every non-owenloop elicitation emit
686
762
  * `needs_input` and then throw: the Phase 1 contract deliberately has no reply
@@ -688,8 +764,33 @@ function createTurnGate(onEvent) {
688
764
  * error reply surfaces to the model as a failed tool call — the least-wrong
689
765
  * behavior available (contract observation 3).
690
766
  */
691
- function handleServerRequest(onEvent) {
767
+ export function handleServerRequest(onEvent, approvals) {
692
768
  return async (method, params) => {
769
+ const shape = BRIDGEABLE_APPROVALS[method];
770
+ if (shape !== undefined && approvals !== undefined) {
771
+ const ask = describeApproval(shape, params);
772
+ let denial = 'the approval channel produced no answer';
773
+ try {
774
+ const outcome = await approvals(ask);
775
+ if (outcome.decision === 'approved') {
776
+ onEvent({ kind: 'progress', text: `approved '${method}': ${ask.title}` });
777
+ return shape.legacy ? { decision: 'approved' } : { decision: 'accept' };
778
+ }
779
+ denial = outcome.note !== undefined && outcome.note !== ''
780
+ ? `${outcome.reason ?? 'denied'} — ${outcome.note}`
781
+ : (outcome.reason ?? 'denied');
782
+ }
783
+ catch (err) {
784
+ // The requester is contracted to always answer, so this is a defect in
785
+ // it rather than an expected path. It still cannot be allowed to hang
786
+ // the turn: a broken channel denies, exactly like a silent one.
787
+ denial = `the approval channel failed: ${describe(err)}`;
788
+ }
789
+ onEvent({ kind: 'progress', text: `denied '${method}': ${cap(denial)}` });
790
+ return shape.legacy
791
+ ? { decision: { denied: { rejection: denial } } }
792
+ : { decision: 'decline' };
793
+ }
693
794
  switch (method) {
694
795
  case 'item/tool/requestUserInput': {
695
796
  const questions = asMap(params)['questions'];
@@ -723,14 +824,26 @@ function handleServerRequest(onEvent) {
723
824
  onEvent({ kind: 'needs_input', question: cap(message) });
724
825
  throw new Error('owenloop hosts this session headlessly and cannot answer an elicitation');
725
826
  }
827
+ case 'item/permissions/requestApproval': {
828
+ // Refused even WITH an approval channel: the reply is a permission
829
+ // profile, not a decision, so there is no question a person could be
830
+ // shown whose answer this would be.
831
+ onEvent({
832
+ kind: 'progress',
833
+ text: `refusing '${method}': granting it means synthesizing a permission profile, not answering a question`,
834
+ });
835
+ throw new Error(`'${method}' is not answerable by a headless host`);
836
+ }
726
837
  case 'item/commandExecution/requestApproval':
727
838
  case 'item/fileChange/requestApproval':
728
- case 'item/permissions/requestApproval':
729
839
  case 'applyPatchApproval':
730
840
  case 'execCommandApproval': {
841
+ // Only reachable with NO approval channel wired in — with one, the
842
+ // branch above this switch handled it. Unchanged from before the
843
+ // channel existed: this adapter does not invent an approval.
731
844
  onEvent({
732
845
  kind: 'progress',
733
- text: `refusing '${method}': owenloop runs with approvalPolicy 'never' and does not grant approvals`,
846
+ text: `refusing '${method}': no approval channel is wired to this session, so nobody can grant it`,
734
847
  });
735
848
  throw new Error(`'${method}' is not answerable by a headless host`);
736
849
  }
@@ -742,7 +855,7 @@ function handleServerRequest(onEvent) {
742
855
  };
743
856
  }
744
857
  /** Spawn one app-server, complete the handshake, and return the wired client. */
745
- async function openClient(cwd, onEvent, gate) {
858
+ async function openClient(cwd, onEvent, gate, approvals) {
746
859
  let exitReported = false;
747
860
  const reportExit = (exitCode, error) => {
748
861
  if (exitReported)
@@ -772,7 +885,12 @@ async function openClient(cwd, onEvent, gate) {
772
885
  // — unsolicited traffic arrives before any request completes, and throwing
773
886
  // on one would kill a healthy session.
774
887
  onNotification: (method, params) => gate.onNotification(method, params),
775
- onServerRequest: handleServerRequest(onEvent),
888
+ // A blocked approval parks INSIDE this handler, for as long as it takes a
889
+ // person to answer. That is safe here and nowhere else in this file: the
890
+ // transport fires each server request without awaiting it (`void (async …)`
891
+ // in `jsonrpc-stdio.ts`), so the reader keeps draining notifications, and no
892
+ // timeout wraps a server request the way `client.request` wraps ours.
893
+ onServerRequest: handleServerRequest(onEvent, approvals),
776
894
  onStderr: (line) => onEvent({ kind: 'progress', text: cap(line) }),
777
895
  onExit: (code, signal) => {
778
896
  reportExit(code, signal === null ? undefined : `killed by ${signal}`);
@@ -958,7 +1076,7 @@ export const codexAdapter = {
958
1076
  const startParams = buildThreadStartParams(args, onEvent);
959
1077
  // Handshake failure disposes the child inside `openClient` — see the catch
960
1078
  // there. Nothing is spawned and unowned by the time this rejects.
961
- const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
1079
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
962
1080
  let threadId;
963
1081
  try {
964
1082
  const res = await client.request('thread/start', startParams, SETUP_TIMEOUT_MS);
@@ -1022,7 +1140,7 @@ export const codexAdapter = {
1022
1140
  SESSIONS.delete(ref.token);
1023
1141
  await previous.client.dispose();
1024
1142
  }
1025
- const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
1143
+ const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
1026
1144
  try {
1027
1145
  await client.request('thread/resume', resumeParams, SETUP_TIMEOUT_MS);
1028
1146
  }
@@ -202,6 +202,53 @@ export interface PermissionIssue {
202
202
  field?: string;
203
203
  message: string;
204
204
  }
205
+ /**
206
+ * ONE escalated tool call, as the adapter hands it to the approval channel.
207
+ *
208
+ * `toolUseId` is the HARNESS's own id for the blocked call. It is the approval's
209
+ * identity, which is what makes a repeat of the same request the same question
210
+ * rather than a second one — an adapter that polls does so by re-sending an
211
+ * identical request.
212
+ */
213
+ export interface ApprovalRequest {
214
+ toolUseId: string;
215
+ toolName: string;
216
+ /** The call's arguments, as the harness presented them. */
217
+ toolInput: unknown;
218
+ /** Why the gatekeeper would not allow the call on its own. Shown to a person. */
219
+ reason: string;
220
+ /** The harness's own one-line rendering of the prompt, when it has one. */
221
+ title?: string;
222
+ /** Aborts the wait when the harness gives up on the call (session teardown). */
223
+ signal?: AbortSignal;
224
+ }
225
+ /**
226
+ * What came back. `note` is the deciding person's own words, when they left any.
227
+ *
228
+ * THERE IS NO THIRD OUTCOME. A timeout, a hub error, a lease that ended while
229
+ * the worker waited — every one of them is `denied`, with a `reason` an adapter
230
+ * can put in front of the agent. The alternative would be an adapter that has to
231
+ * decide what "no answer" means at the moment it is least able to, and the
232
+ * failure mode of guessing wrong is a tool call that runs because nobody said
233
+ * no.
234
+ */
235
+ export interface ApprovalOutcome {
236
+ decision: 'approved' | 'denied';
237
+ /** Why, when the decision was not a person's explicit yes. */
238
+ reason?: string;
239
+ note?: string;
240
+ }
241
+ /**
242
+ * The channel an adapter uses to ask a PERSON about one tool call and wait.
243
+ *
244
+ * Supplied by the worker, not built by an adapter: it is the worker that holds
245
+ * the hub client and knows which run this session is serving. An adapter that
246
+ * receives no requester keeps its pre-existing behavior — refuse the call and
247
+ * route the agent to `ask` — which is why this is optional rather than required.
248
+ * Nothing about the shape is vendor-specific; every harness that can intercept a
249
+ * tool call can use it.
250
+ */
251
+ export type ApprovalRequester = (req: ApprovalRequest) => Promise<ApprovalOutcome>;
205
252
  /** Everything an adapter needs to launch one step agent. */
206
253
  export interface StartArgs {
207
254
  /** The fully rendered step prompt. */
@@ -244,6 +291,12 @@ export interface StartArgs {
244
291
  };
245
292
  /** Normalized from the step def by `normalizeStepPermissions`. */
246
293
  permissions: StepPermissions;
294
+ /**
295
+ * The human approval channel for escalated tool calls, when this deployment
296
+ * has one. ABSENT means the adapter's existing refuse-and-route-to-`ask`
297
+ * behavior stands — that is a supported deployment, not a degraded one.
298
+ */
299
+ approvals?: ApprovalRequester;
247
300
  }
248
301
  /**
249
302
  * Everything an adapter needs to RESUME an existing session with one message.
@@ -271,7 +324,7 @@ export interface StartArgs {
271
324
  * happened to hold, and it must NOT fall back to a minimal option set on a map
272
325
  * miss.
273
326
  */
274
- export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort'>;
327
+ export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort' | 'approvals'>;
275
328
  /**
276
329
  * One harness implementation.
277
330
  *
@@ -1,3 +1,4 @@
1
+ import { type Liveness } from '../shift/state.ts';
1
2
  /** Where a step attempt is in its life. */
2
3
  export type SessionStatus = 'active' | 'turn-ended' | 'submitted' | 'dead';
3
4
  /** One line of `sessions.jsonl`. */
@@ -10,9 +11,33 @@ export interface SessionRecord {
10
11
  * contract lists it and Phase 6's `owenloop work sessions` display prints it.
11
12
  * ALWAYS build it with `orderId()` so the two can never drift. */
12
13
  order: string;
14
+ /**
15
+ * `OrderPacket.key` — the fan-out key of the engine task this firing served.
16
+ *
17
+ * WHY IT IS HERE, AND WHY IT IS OPTIONAL. `run` identifies ONE FIRING and is
18
+ * minted fresh every time the engine claims the step, so `(workflow, run,
19
+ * step)` can never name the same work twice. `(workflow, step, key)` is the
20
+ * engine's own task identity — the `UNIQUE (workflow, step, key)` on its
21
+ * `task` table — and is the only triple here that survives a re-offer. See
22
+ * `latestForTask`.
23
+ *
24
+ * OPTIONAL because every row written before this field existed lacks it. Such
25
+ * a row is never attributed to a task (`latestForTask` skips it) rather than
26
+ * being guessed at. `''` is a REAL key — an unfanned step — so the absence
27
+ * must be tested as `undefined`, never as falsy.
28
+ */
29
+ key?: string;
13
30
  attempt: number;
14
31
  /** Adapter id (`HarnessSessionRef.harness`). */
15
32
  harness: string;
33
+ /** PID of the agent-run worker that owns the active session, when recorded. */
34
+ pid?: number;
35
+ /** Stable shift name in force when the worker was dispatched, when recorded. */
36
+ shiftName?: string;
37
+ /** Stable owner key; explicit shift names use the name, unnamed shifts use stateDir. */
38
+ shiftOwner?: string;
39
+ /** Per-boot shift incarnation that dispatched the worker, for diagnostics. */
40
+ shiftId?: string;
16
41
  /** Provider-native session token (`HarnessSessionRef.token`). Machine-local. */
17
42
  token: string;
18
43
  cwd: string;
@@ -44,6 +69,8 @@ export interface SessionStoreOptions {
44
69
  * ("skipping corrupt record") or a parsed object that failed the schema
45
70
  * ("skipping invalid record"). Default writes to stderr. */
46
71
  warn?: (line: string) => void;
72
+ /** Optional debug sink for conservative reconciliation skips. */
73
+ debug?: (line: string) => void;
47
74
  /** Test barrier invoked under the writer lock after a retirement snapshot. */
48
75
  afterWriterSnapshot?: () => void;
49
76
  /** Compaction threshold in bytes, checked after each append. Default 2 MB. */
@@ -75,11 +102,55 @@ export declare function orderId(workflow: string, run: string): string;
75
102
  */
76
103
  export declare function readSessions(file: string, opts?: SessionStoreOptions): SessionRecord[];
77
104
  /**
78
- * The newest record for `(workflow, run, step)`, or `null` when the file is
79
- * missing or holds no match. Scans forward and keeps the LAST match (last-wins).
80
- * Side-effect-free — it never writes, never compacts, and never throws.
105
+ * The newest record for `(workflow, run, step)` — that is, for ONE FIRING of one
106
+ * step — or `null` when the file is missing or holds no match. Scans forward and
107
+ * keeps the LAST match (last-wins). Side-effect-free: it never writes, never
108
+ * compacts, and never throws.
109
+ *
110
+ * ── THIS IS THE PER-FIRING LOOKUP. IT CANNOT FIND A PREVIOUS FIRING. ─────────
111
+ *
112
+ * The hub mints a fresh `run` id every time it claims a step. Two firings of the
113
+ * same step therefore NEVER share a `run`, so this function can only ever return
114
+ * a record written during the very firing that is asking. Use it for questions
115
+ * that really are about one firing — "did THIS firing already take a work dir?",
116
+ * "which sessions belong to the run I am tearing down?" — and never to ask "has
117
+ * this step run before?". That second question is `latestForTask`.
81
118
  */
82
119
  export declare function latestFor(file: string, workflow: string, run: string, step: string): SessionRecord | null;
120
+ /**
121
+ * The engine's own identity for a unit of work: one STEP of one WORKFLOW at one
122
+ * fan-out KEY. The hub enforces `UNIQUE (workflow, step, key)` on its task table,
123
+ * which is what makes this triple stable across re-offers where `run` is not.
124
+ */
125
+ export interface SessionTaskRef {
126
+ workflow: string;
127
+ step: string;
128
+ /** `OrderPacket.key`. `''` for a step that does not fan out — a real value,
129
+ * not a missing one. */
130
+ key: string;
131
+ }
132
+ /**
133
+ * The newest record for an engine TASK — the last session recorded for this
134
+ * step at this key, no matter which firing wrote it — or `null` when there is
135
+ * none. Last-wins, side-effect-free, same as `latestFor`.
136
+ *
137
+ * ── WHY THIS EXISTS ALONGSIDE `latestFor` ────────────────────────────────────
138
+ *
139
+ * `latestFor` keys on `run`, which the hub re-mints per firing, so it answers
140
+ * "what happened during THIS firing?". Resume needs the opposite question: "did
141
+ * a previous firing of this same step leave a session I can re-enter?" Only
142
+ * `(workflow, step, key)` survives long enough to answer that.
143
+ *
144
+ * ── WHY A ROW WITHOUT `key` NEVER MATCHES ────────────────────────────────────
145
+ *
146
+ * Rows written before `key` existed carry no task identity at all. Guessing one
147
+ * — treating absent as `''`, say — would attribute an unfanned row and a fanned
148
+ * row to the same task and hand a worker someone else's session. Skipping them
149
+ * costs only a cold start on the first firing after upgrade, which is the safe
150
+ * direction to be wrong in. The test is `=== undefined`, because `''` is a real
151
+ * key that must match.
152
+ */
153
+ export declare function latestForTask(file: string, task: SessionTaskRef): SessionRecord | null;
83
154
  /**
84
155
  * Rewrite `file` with only the last record per `(workflow, run, step)`,
85
156
  * preserving FIRST-SEEN key order, via temp file + rename. Corrupt lines are
@@ -137,8 +208,8 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
137
208
  * provider-side session is intact. A reboot does not invalidate one. Leaving
138
209
  * those rows alone is precisely what "resume still works after a reboot" means.
139
210
  *
140
- * So ONLY `active` rows are eligible, and only for runs absent from
141
- * `liveRunIds`.
211
+ * So ONLY `active` rows are eligible, and each candidate is checked against its
212
+ * recorded owner and worker PID before any retirement row is appended.
142
213
  *
143
214
  * ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
144
215
  *
@@ -147,16 +218,33 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
147
218
  * would carry a model that believes work happened which did not. The cost of
148
219
  * retiring it is one cold replay. The cost of resuming it is silent divergence.
149
220
  *
150
- * ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
221
+ * ── WHY THE RUN-ID SET THIS REPLACED WAS UNSAFE ──────────────────────────────
222
+ *
223
+ * This used to take `liveRunIds` — the run ids with a live `agent-run` child in
224
+ * the BOOTING shift's state dir — and retire every `active` row outside it. That
225
+ * is correct only on a machine running exactly one shift. It does not: the
226
+ * sessions store is per-CACHE-DIR and therefore machine-wide, while a state dir
227
+ * is per-shift. So shift A booting saw shift B's currently-running workers as
228
+ * orphans and killed their resumable sessions out from under them, mid-turn.
229
+ * A prior version of this comment told the next reader NOT to put a pid on
230
+ * `SessionRecord`, on the grounds that the shift state dir was already the
231
+ * system of record for liveness. That was the mistaken premise: one shift's
232
+ * state dir is evidence about ONE shift, and this file is read by all of them.
233
+ *
234
+ * ── FAIL-SAFE OWNERSHIP AND LIVENESS ─────────────────────────────────────────
151
235
  *
152
- * An `owenloop work agent-run` started BY HAND, outside the shift, has no child record
153
- * in the shift state dir, so a shift booting at that moment sees its `active` row
154
- * as orphaned and retires it. The cost is one cold replay on a hand-run debugging
155
- * session. Two things keep it small: the caller invokes this at BOOT only, which
156
- * narrows the window to an instant, and every retirement is returned so the
157
- * caller can log it with its `(workflow, run, step)`. Do NOT add a pid field to
158
- * `SessionRecord` to close this — the record is deliberately machine-portable
159
- * metadata, and the shift state dir is already the system of record for liveness.
236
+ * Boot-time reconciliation is allowed to retire an `active` row only when the
237
+ * row names this shift, carries a valid worker PID, and that PID is provably
238
+ * gone. Missing or foreign ownership, an unknown PID, a live PID, and any
239
+ * liveness ambiguity all leave the row untouched. A stale row is cheaper than
240
+ * destroying a live resumable session, so the predicate intentionally errs in
241
+ * that direction.
242
+ *
243
+ * A CONSEQUENCE WORTH KNOWING: every row written before this landed has no
244
+ * `pid` and no owner, so none of them is ever retired. That is the fail-safe
245
+ * direction and it costs nothing — an un-retired stale row is one failed resume
246
+ * that falls back to a cold replay, which is what retiring it would have caused
247
+ * anyway.
160
248
  *
161
249
  * IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
162
250
  * `active` left and appends nothing.
@@ -164,12 +252,34 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
164
252
  * FAILURE STANCE: `appendSession` propagates, and so does this — same as
165
253
  * `markRunSessionsDead`.
166
254
  *
167
- * @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
168
- * this set is skipped whatever its status.
255
+ * @param context the booting shift's ownership and harness identity plus the
256
+ * injectable PID liveness probe.
169
257
  * @returns the records that were retired, as they were BEFORE retirement, so the
170
258
  * caller can log what it took away.
171
259
  */
172
- export declare function reconcileActiveSessions(file: string, liveRunIds: ReadonlySet<string>, now: number, opts?: SessionStoreOptions): SessionRecord[];
260
+ export interface SessionReconcileContext {
261
+ /** Public shift name in force when this shift booted. */
262
+ shiftName: string;
263
+ /** Stable owner key; falls back to `shiftName` for older callers/records. */
264
+ shiftOwner?: string;
265
+ /** Configured harness guard, when this shift has one. */
266
+ harness?: string;
267
+ /** PID probe; defaults to the existing shift-state probe. */
268
+ isAlive?: Liveness;
269
+ }
270
+ export interface RetireDecision {
271
+ retire: boolean;
272
+ reason: string;
273
+ }
274
+ /**
275
+ * Decide whether one active session row is safe to retire.
276
+ *
277
+ * The function is deliberately independent of the JSONL writer. Callers can
278
+ * exercise the safety predicate with a deterministic PID probe, while the
279
+ * production path uses `process.kill(pid, 0)` through `defaultIsAlive`.
280
+ */
281
+ export declare function shouldRetireSession(record: SessionRecord, context: SessionReconcileContext): RetireDecision;
282
+ export declare function reconcileActiveSessions(file: string, context: SessionReconcileContext, now: number, opts?: SessionStoreOptions): SessionRecord[];
173
283
  /**
174
284
  * Append one record, then compact when the file has grown past `maxBytes`.
175
285
  *