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
@@ -29,30 +29,35 @@
29
29
  * `full-access`, and the two exist separately so that choice is stated rather
30
30
  * than inferred.
31
31
  *
32
- * WHAT `auto-safe` COSTS YOU TODAY, MEASURED. The three positions above
33
- * describe the vocabulary, not a guarantee about how far any given classifier
34
- * actually goes before it consults someone. On one shipped adapter the
35
- * classifier was probed with five actions — among them a recursive delete on an
36
- * absolute path outside the session working directory, an outbound network
37
- * request, and a read of a file outside that directory — and it consulted the
38
- * host on none of them and reported no auto-denial for any of them; four ran.
39
- * On the other, the position that maps to `auto-safe` keys its judgment on
32
+ * WHO ACTUALLY DOES THE GATING, AND WHAT IT COSTS. The three positions above
33
+ * describe the vocabulary, not a guarantee about how far any given VENDOR
34
+ * classifier goes before it consults someone — and measurement showed the
35
+ * vendor classifiers do not, in practice, consult anyone. One was probed with
36
+ * five actions, among them a recursive delete on an absolute path outside the
37
+ * session working directory, an outbound network request, and a read of a file
38
+ * outside that directory; it consulted the host on none of them and reported no
39
+ * auto-denial for any of them, and four ran. The other keys its judgment on
40
40
  * filesystem access being restricted, so a step that also declares
41
41
  * `filesystem: unrestricted` moves it close to `full-access` as well.
42
42
  *
43
- * The practical consequence for a definition author: choosing `auto-safe`
44
- * because you want a person consulted on the dangerous cases may get you
45
- * neither the prompt nor a record that one was skipped. Choose `ask` when a
46
- * human decision genuinely has to happen, and `full-access` when it genuinely
47
- * must not. Treat `auto-safe` as the classifier's own judgment with no
48
- * guaranteed appeal, not as a supervised `full-access`.
43
+ * So `auto-safe` is NOT implemented by handing the decision to a vendor
44
+ * classifier and hoping. An adapter that can intercept its harness's tool calls
45
+ * gates them itself (see `./gatekeeper.ts`) — path containment against the
46
+ * step's own working directory, plus a short deny-list of destructive shell
47
+ * patterns — which is a blunter instrument than a model-side classifier and the
48
+ * only one of the two that can actually escalate. An adapter that CANNOT
49
+ * intercept owes this vocabulary the other legitimate answer: refuse the value
50
+ * in `preflight`, per "WHAT AN ADAPTER OWES THIS VOCABULARY" below.
49
51
  *
50
- * `ask` and `auto-safe` are meaningful only where something can answer a
51
- * prompt. In a Shift-dispatched run nothing can, so a prompt is a stall: the
52
- * Step Agent stops mid-turn, submits nothing, and the hub re-arms the step into
53
- * a retry storm whose every worker dies in the same place. That is a reason for
54
- * a definition author to choose `full-access` for unattended steps, not a
55
- * reason for an adapter to silently upgrade one value into another.
52
+ * `ask` and `auto-safe` name positions where something is consulted. In a
53
+ * Shift-dispatched run no person is watching at the moment of the call, so the
54
+ * consultation cannot be synchronous: an adapter refuses the call and routes the
55
+ * agent to the `ask` MCP tool, which freezes the owed artifact and puts the
56
+ * question on a human's attention feed with an answer path back into the next
57
+ * attempt. What an adapter must never do is leave the call waiting on a prompt
58
+ * nobody will answer — that is a stall, and the hub re-arms the step into a
59
+ * retry storm whose every worker dies in the same place. Nor may it silently
60
+ * upgrade one value into another to avoid the problem.
56
61
  *
57
62
  * WHAT AN ADAPTER OWES THIS VOCABULARY. For each value an adapter must either
58
63
  * map it onto the vendor mode with the same meaning, or refuse it in
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The tool-call gatekeeper: the decision an adapter makes when its harness asks
3
+ * "may this tool call run?".
4
+ *
5
+ * WHY THIS EXISTS. `permissionMode` names three positions — `ask` (a human is
6
+ * the gate), `auto-safe` (a classifier is the gate, a human is the exception
7
+ * path), `full-access` (nothing is gated). Until this module, only the third
8
+ * one was real:
9
+ *
10
+ * - `ask` mapped to the SDK's `default` mode, which routes every unapproved
11
+ * tool call to a `canUseTool` callback and DENIES when no callback is wired.
12
+ * No callback was wired anywhere in this codebase. So `ask` denied everything,
13
+ * silently and finally: the agent saw a bare tool error, nobody was prompted,
14
+ * and nothing was recorded. That is the mechanism behind a planner step
15
+ * reporting that every read of its own target repository was blocked.
16
+ * - `auto-safe` mapped to the SDK's `auto` mode, whose model-side classifier was
17
+ * measured (SDK 0.3.220, callback wired throughout) to consult the host on
18
+ * NONE of five probe actions and to auto-deny none of them: four ran,
19
+ * including a recursive delete on an absolute path outside the session working
20
+ * directory, an outbound network request, and a read under `$HOME`. `auto`
21
+ * never reaches the callback at all, so no amount of host-side wiring gives it
22
+ * an exception path.
23
+ *
24
+ * The practical response to both was to write `permissionMode: full-access` on
25
+ * every step, because it was the only value whose behavior matched its name.
26
+ * That is a workflow author turning permissions off to get work done, which is
27
+ * the failure this module exists to end.
28
+ *
29
+ * WHAT THIS MODULE DECIDES, AND WHAT IT DOES NOT. It answers one question per
30
+ * tool call — allow it, or escalate it — against a stated policy. It does NOT
31
+ * decide what escalation means: the adapter owns that, because the useful
32
+ * answers differ by deployment. Today every adapter denies an escalated call
33
+ * with guidance routing the agent to the `ask` MCP tool, which puts the question
34
+ * to a person through the hub. A worker that can block on a hub-side approval
35
+ * gate would instead wait here and resolve the original call. Keeping that
36
+ * choice out of this module is what lets the second shape land without
37
+ * reopening the classification.
38
+ *
39
+ * HONESTY ABOUT THE CLASSIFIER. Two of the three checks below are decidable and
40
+ * one is not. Path containment is decidable: a resolved path either is or is not
41
+ * inside the tree this step was given. A shell command is not — no pattern list
42
+ * decides whether an arbitrary `bash -c` string is safe, and this one does not
43
+ * pretend to. `dangerousCommand` is a DENY-LIST of high-signal, rarely-legitimate
44
+ * patterns. It catches the measured probes and the ordinary footguns; a
45
+ * deliberately obfuscated command gets past it. The deny-list is kept short on
46
+ * purpose: under `classifier` policy a false positive stops real work in a
47
+ * headless run, and the honest posture for a mode documented as "proceeds on
48
+ * ordinary work" is to allow what it cannot judge. A step whose commands must
49
+ * genuinely all be reviewed should say `permissionMode: ask`, which escalates
50
+ * every shell call without consulting the deny-list at all.
51
+ */
52
+ /**
53
+ * How much the gatekeeper escalates, derived by the adapter from the step's
54
+ * authored `permissionMode`.
55
+ *
56
+ * - `human-gate` — the `ask` position. Everything beyond a trivially safe read
57
+ * inside the step's own directory escalates. The classifier is not consulted:
58
+ * the point of `ask` is that a person sees the call, not that a pattern list
59
+ * approves of it first.
60
+ * - `classifier` — the `auto-safe` position, and the right reading of a step
61
+ * that named the vendor's own `default`/`acceptEdits` or named nothing at all.
62
+ * Ordinary work proceeds; the checks below escalate what they can actually
63
+ * establish is dangerous.
64
+ * - `deny-unapproved` — the vendor's `dontAsk`, whose documented meaning is to
65
+ * deny an unapproved call rather than consult anyone. Present so that value
66
+ * keeps its meaning rather than being quietly widened into `classifier`. In
67
+ * practice the SDK short-circuits this mode before the callback, so it is a
68
+ * statement of intent more than a live path.
69
+ */
70
+ export type GatePolicy = 'human-gate' | 'classifier' | 'deny-unapproved';
71
+ /** One tool call, as much as the gatekeeper needs to judge it. */
72
+ export interface GateCall {
73
+ /** The harness's own tool name, e.g. `Read`, `Bash`, `mcp__owenloop__submit`. */
74
+ toolName: string;
75
+ /** The tool's arguments, unvalidated — this is a model-authored bag. */
76
+ input: Record<string, unknown>;
77
+ /**
78
+ * The directory this step was placed in and is entitled to work inside. For
79
+ * an owenloop order this is the resolved `workdir`; containment is measured
80
+ * against it and nothing else.
81
+ */
82
+ workdir: string;
83
+ /**
84
+ * A path the harness itself already determined to be outside the directories
85
+ * it allows, when it says so. Authoritative when present: the harness sees
86
+ * shell commands this module deliberately does not try to parse.
87
+ */
88
+ blockedPath?: string;
89
+ }
90
+ /** The gatekeeper's answer. `reason` is written to be shown to a person and to
91
+ * the agent, so it names the specific thing that triggered it. */
92
+ export type GateVerdict = {
93
+ decision: 'allow';
94
+ } | {
95
+ decision: 'escalate';
96
+ reason: string;
97
+ };
98
+ /**
99
+ * Whether `candidate` resolves inside `root`.
100
+ *
101
+ * Resolved against `root` first, so a relative path means what the harness will
102
+ * mean by it. The `..` test is on the RELATIVE result rather than on the input
103
+ * string: `a/../../b` contains no leading `..` but lands outside, and a string
104
+ * test would pass it.
105
+ */
106
+ export declare function isInside(root: string, candidate: string): boolean;
107
+ /**
108
+ * The first deny-list pattern this command matches, or `undefined`.
109
+ *
110
+ * Exported for the tests, which assert the list's shape directly: the value of a
111
+ * deny-list is entirely in which patterns are on it, so those assertions are the
112
+ * documentation of what it does and does not claim to catch.
113
+ */
114
+ export declare function dangerousCommand(command: string): string | undefined;
115
+ /**
116
+ * Judge one tool call.
117
+ *
118
+ * ORDER MATTERS. The owenloop mount is cleared first so no later rule can strand
119
+ * a step's ability to submit or escalate. The harness's own `blockedPath` is
120
+ * consulted next because it is authoritative and covers cases this module cannot
121
+ * see. Only then does policy divide: `human-gate` escalates everything but a
122
+ * contained read, `classifier` runs the two checks it can actually decide.
123
+ */
124
+ export declare function classifyToolCall(call: GateCall, policy: GatePolicy): GateVerdict;
@@ -0,0 +1,208 @@
1
+ /**
2
+ * The tool-call gatekeeper: the decision an adapter makes when its harness asks
3
+ * "may this tool call run?".
4
+ *
5
+ * WHY THIS EXISTS. `permissionMode` names three positions — `ask` (a human is
6
+ * the gate), `auto-safe` (a classifier is the gate, a human is the exception
7
+ * path), `full-access` (nothing is gated). Until this module, only the third
8
+ * one was real:
9
+ *
10
+ * - `ask` mapped to the SDK's `default` mode, which routes every unapproved
11
+ * tool call to a `canUseTool` callback and DENIES when no callback is wired.
12
+ * No callback was wired anywhere in this codebase. So `ask` denied everything,
13
+ * silently and finally: the agent saw a bare tool error, nobody was prompted,
14
+ * and nothing was recorded. That is the mechanism behind a planner step
15
+ * reporting that every read of its own target repository was blocked.
16
+ * - `auto-safe` mapped to the SDK's `auto` mode, whose model-side classifier was
17
+ * measured (SDK 0.3.220, callback wired throughout) to consult the host on
18
+ * NONE of five probe actions and to auto-deny none of them: four ran,
19
+ * including a recursive delete on an absolute path outside the session working
20
+ * directory, an outbound network request, and a read under `$HOME`. `auto`
21
+ * never reaches the callback at all, so no amount of host-side wiring gives it
22
+ * an exception path.
23
+ *
24
+ * The practical response to both was to write `permissionMode: full-access` on
25
+ * every step, because it was the only value whose behavior matched its name.
26
+ * That is a workflow author turning permissions off to get work done, which is
27
+ * the failure this module exists to end.
28
+ *
29
+ * WHAT THIS MODULE DECIDES, AND WHAT IT DOES NOT. It answers one question per
30
+ * tool call — allow it, or escalate it — against a stated policy. It does NOT
31
+ * decide what escalation means: the adapter owns that, because the useful
32
+ * answers differ by deployment. Today every adapter denies an escalated call
33
+ * with guidance routing the agent to the `ask` MCP tool, which puts the question
34
+ * to a person through the hub. A worker that can block on a hub-side approval
35
+ * gate would instead wait here and resolve the original call. Keeping that
36
+ * choice out of this module is what lets the second shape land without
37
+ * reopening the classification.
38
+ *
39
+ * HONESTY ABOUT THE CLASSIFIER. Two of the three checks below are decidable and
40
+ * one is not. Path containment is decidable: a resolved path either is or is not
41
+ * inside the tree this step was given. A shell command is not — no pattern list
42
+ * decides whether an arbitrary `bash -c` string is safe, and this one does not
43
+ * pretend to. `dangerousCommand` is a DENY-LIST of high-signal, rarely-legitimate
44
+ * patterns. It catches the measured probes and the ordinary footguns; a
45
+ * deliberately obfuscated command gets past it. The deny-list is kept short on
46
+ * purpose: under `classifier` policy a false positive stops real work in a
47
+ * headless run, and the honest posture for a mode documented as "proceeds on
48
+ * ordinary work" is to allow what it cannot judge. A step whose commands must
49
+ * genuinely all be reviewed should say `permissionMode: ask`, which escalates
50
+ * every shell call without consulting the deny-list at all.
51
+ */
52
+ import { isAbsolute, relative, resolve } from 'node:path';
53
+ const ALLOW = { decision: 'allow' };
54
+ /**
55
+ * Tools that read without mutating anything. Under `human-gate` these are the
56
+ * "trivially safe reads" the `ask` position exempts — but only inside the
57
+ * step's own directory; a read of an arbitrary absolute path is exactly the
58
+ * probe that ran unchallenged under `auto`.
59
+ */
60
+ const READ_ONLY_TOOLS = new Set(['Read', 'Glob', 'Grep', 'NotebookRead']);
61
+ /**
62
+ * Where each tool names a filesystem path. Only tools whose path argument is a
63
+ * plain string are listed: containment is checked where it can be checked, and
64
+ * a tool absent from this table simply is not path-checked rather than being
65
+ * guessed at.
66
+ */
67
+ const PATH_ARGS = Object.freeze({
68
+ Read: ['file_path'],
69
+ Write: ['file_path'],
70
+ Edit: ['file_path'],
71
+ NotebookRead: ['notebook_path'],
72
+ NotebookEdit: ['notebook_path'],
73
+ Glob: ['path'],
74
+ Grep: ['path'],
75
+ });
76
+ /**
77
+ * The owenloop MCP mount, which is ALWAYS allowed under every policy.
78
+ *
79
+ * This is not a convenience. `submit` is how a step discharges what it owes and
80
+ * `ask` is how it escalates to a person — including how it escalates a call this
81
+ * very gatekeeper just refused. Gating either one makes an escalated step unable
82
+ * to report that it is stuck, which converts a recoverable stall into a silent
83
+ * one. The mount is worker-owned and its surface is fixed at four tools
84
+ * (`get_order`, `submit`, `reject`, `ask`), none of which touch the filesystem
85
+ * or the network beyond the hub, so there is nothing here for a human to weigh.
86
+ */
87
+ const OWENLOOP_MCP_PREFIX = 'mcp__owenloop__';
88
+ /**
89
+ * Shell patterns the deny-list escalates. Each entry has to clear a high bar:
90
+ * genuinely destructive or exfiltrating, AND essentially never legitimate in a
91
+ * step doing repository work. Anything that merely LOOKS alarming but has an
92
+ * ordinary use in this pipeline is deliberately absent — `git push --force`, for
93
+ * one, is routine on a step's own branch, and escalating it would stop real work
94
+ * every run in exchange for no safety.
95
+ */
96
+ const DANGEROUS_COMMAND_PATTERNS = Object.freeze([
97
+ { pattern: /\b(?:sudo|doas)\b/u, what: 'runs a command as another user' },
98
+ {
99
+ pattern: /\brm\s+(?:-[a-zA-Z]*[rR][a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*[rR])\b/u,
100
+ what: 'is a recursive force-delete',
101
+ },
102
+ { pattern: /\bdd\b[^\n]*\bof=\/dev\//u, what: 'writes directly to a device' },
103
+ { pattern: /\b(?:mkfs(?:\.\w+)?|diskutil\s+erase\w*)\b/u, what: 'erases or formats a volume' },
104
+ { pattern: /\bchown\b/u, what: 'changes file ownership' },
105
+ { pattern: /\bchmod\s+(?:[0-7]*777|a\+[rwx]*w)/u, what: 'makes a file world-writable' },
106
+ {
107
+ pattern: /\b(?:curl|wget)\b[^\n]*(?:\s-X\s*(?:POST|PUT|PATCH|DELETE)\b|\s--(?:data|upload-file|post-file)\b|\s-d\s)/u,
108
+ what: 'sends data to a remote host',
109
+ },
110
+ {
111
+ pattern: /\b(?:crontab|launchctl|systemctl|schtasks)\b/u,
112
+ what: 'changes what runs on this machine outside this step',
113
+ },
114
+ {
115
+ pattern: /(?:>>?\s*)(?:~|\$HOME)?\/?\.(?:zshrc|bashrc|bash_profile|zprofile|profile)\b/u,
116
+ what: 'writes to a shell startup file',
117
+ },
118
+ ]);
119
+ /** Every string in a model-authored argument bag, at the top level. Enough for
120
+ * the path table (whose arguments are all top-level strings) without walking an
121
+ * arbitrary nested value. */
122
+ function stringArg(input, key) {
123
+ const v = input[key];
124
+ return typeof v === 'string' && v !== '' ? v : undefined;
125
+ }
126
+ /**
127
+ * Whether `candidate` resolves inside `root`.
128
+ *
129
+ * Resolved against `root` first, so a relative path means what the harness will
130
+ * mean by it. The `..` test is on the RELATIVE result rather than on the input
131
+ * string: `a/../../b` contains no leading `..` but lands outside, and a string
132
+ * test would pass it.
133
+ */
134
+ export function isInside(root, candidate) {
135
+ const absRoot = resolve(root);
136
+ const absCandidate = isAbsolute(candidate) ? resolve(candidate) : resolve(absRoot, candidate);
137
+ if (absCandidate === absRoot)
138
+ return true;
139
+ const rel = relative(absRoot, absCandidate);
140
+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
141
+ }
142
+ /**
143
+ * The first deny-list pattern this command matches, or `undefined`.
144
+ *
145
+ * Exported for the tests, which assert the list's shape directly: the value of a
146
+ * deny-list is entirely in which patterns are on it, so those assertions are the
147
+ * documentation of what it does and does not claim to catch.
148
+ */
149
+ export function dangerousCommand(command) {
150
+ for (const { pattern, what } of DANGEROUS_COMMAND_PATTERNS) {
151
+ if (pattern.test(command))
152
+ return what;
153
+ }
154
+ return undefined;
155
+ }
156
+ /**
157
+ * Judge one tool call.
158
+ *
159
+ * ORDER MATTERS. The owenloop mount is cleared first so no later rule can strand
160
+ * a step's ability to submit or escalate. The harness's own `blockedPath` is
161
+ * consulted next because it is authoritative and covers cases this module cannot
162
+ * see. Only then does policy divide: `human-gate` escalates everything but a
163
+ * contained read, `classifier` runs the two checks it can actually decide.
164
+ */
165
+ export function classifyToolCall(call, policy) {
166
+ if (call.toolName.startsWith(OWENLOOP_MCP_PREFIX))
167
+ return ALLOW;
168
+ if (policy === 'deny-unapproved') {
169
+ return { decision: 'escalate', reason: `permissionMode denies unapproved tool calls` };
170
+ }
171
+ // The harness saw something this module did not — trust it.
172
+ if (call.blockedPath !== undefined && call.blockedPath !== '') {
173
+ return {
174
+ decision: 'escalate',
175
+ reason: `the harness flagged \`${call.blockedPath}\` as outside the directories this step may touch`,
176
+ };
177
+ }
178
+ const paths = (PATH_ARGS[call.toolName] ?? [])
179
+ .map((key) => stringArg(call.input, key))
180
+ .filter((p) => p !== undefined);
181
+ for (const p of paths) {
182
+ if (!isInside(call.workdir, p)) {
183
+ return {
184
+ decision: 'escalate',
185
+ reason: `\`${p}\` is outside this step's working directory (\`${call.workdir}\`)`,
186
+ };
187
+ }
188
+ }
189
+ if (policy === 'human-gate') {
190
+ // Every path this tool named is contained, or it named none. A read is the
191
+ // one thing `ask` lets through; anything that can mutate or reach the
192
+ // network is what the position exists to put in front of a person.
193
+ if (READ_ONLY_TOOLS.has(call.toolName))
194
+ return ALLOW;
195
+ return {
196
+ decision: 'escalate',
197
+ reason: `permissionMode is \`ask\`, so \`${call.toolName}\` needs a person's approval`,
198
+ };
199
+ }
200
+ const command = stringArg(call.input, 'command');
201
+ if (call.toolName === 'Bash' && command !== undefined) {
202
+ const what = dangerousCommand(command);
203
+ if (what !== undefined) {
204
+ return { decision: 'escalate', reason: `the command ${what}` };
205
+ }
206
+ }
207
+ return ALLOW;
208
+ }
@@ -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`. */
@@ -13,6 +14,14 @@ export interface SessionRecord {
13
14
  attempt: number;
14
15
  /** Adapter id (`HarnessSessionRef.harness`). */
15
16
  harness: string;
17
+ /** PID of the agent-run worker that owns the active session, when recorded. */
18
+ pid?: number;
19
+ /** Stable shift name in force when the worker was dispatched, when recorded. */
20
+ shiftName?: string;
21
+ /** Stable owner key; explicit shift names use the name, unnamed shifts use stateDir. */
22
+ shiftOwner?: string;
23
+ /** Per-boot shift incarnation that dispatched the worker, for diagnostics. */
24
+ shiftId?: string;
16
25
  /** Provider-native session token (`HarnessSessionRef.token`). Machine-local. */
17
26
  token: string;
18
27
  cwd: string;
@@ -44,6 +53,8 @@ export interface SessionStoreOptions {
44
53
  * ("skipping corrupt record") or a parsed object that failed the schema
45
54
  * ("skipping invalid record"). Default writes to stderr. */
46
55
  warn?: (line: string) => void;
56
+ /** Optional debug sink for conservative reconciliation skips. */
57
+ debug?: (line: string) => void;
47
58
  /** Test barrier invoked under the writer lock after a retirement snapshot. */
48
59
  afterWriterSnapshot?: () => void;
49
60
  /** Compaction threshold in bytes, checked after each append. Default 2 MB. */
@@ -137,8 +148,8 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
137
148
  * provider-side session is intact. A reboot does not invalidate one. Leaving
138
149
  * those rows alone is precisely what "resume still works after a reboot" means.
139
150
  *
140
- * So ONLY `active` rows are eligible, and only for runs absent from
141
- * `liveRunIds`.
151
+ * So ONLY `active` rows are eligible, and each candidate is checked against its
152
+ * recorded owner and worker PID before any retirement row is appended.
142
153
  *
143
154
  * ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
144
155
  *
@@ -147,16 +158,33 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
147
158
  * would carry a model that believes work happened which did not. The cost of
148
159
  * retiring it is one cold replay. The cost of resuming it is silent divergence.
149
160
  *
150
- * ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
151
- *
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.
161
+ * ── WHY THE RUN-ID SET THIS REPLACED WAS UNSAFE ──────────────────────────────
162
+ *
163
+ * This used to take `liveRunIds` — the run ids with a live `agent-run` child in
164
+ * the BOOTING shift's state dir — and retire every `active` row outside it. That
165
+ * is correct only on a machine running exactly one shift. It does not: the
166
+ * sessions store is per-CACHE-DIR and therefore machine-wide, while a state dir
167
+ * is per-shift. So shift A booting saw shift B's currently-running workers as
168
+ * orphans and killed their resumable sessions out from under them, mid-turn.
169
+ * A prior version of this comment told the next reader NOT to put a pid on
170
+ * `SessionRecord`, on the grounds that the shift state dir was already the
171
+ * system of record for liveness. That was the mistaken premise: one shift's
172
+ * state dir is evidence about ONE shift, and this file is read by all of them.
173
+ *
174
+ * ── FAIL-SAFE OWNERSHIP AND LIVENESS ─────────────────────────────────────────
175
+ *
176
+ * Boot-time reconciliation is allowed to retire an `active` row only when the
177
+ * row names this shift, carries a valid worker PID, and that PID is provably
178
+ * gone. Missing or foreign ownership, an unknown PID, a live PID, and any
179
+ * liveness ambiguity all leave the row untouched. A stale row is cheaper than
180
+ * destroying a live resumable session, so the predicate intentionally errs in
181
+ * that direction.
182
+ *
183
+ * A CONSEQUENCE WORTH KNOWING: every row written before this landed has no
184
+ * `pid` and no owner, so none of them is ever retired. That is the fail-safe
185
+ * direction and it costs nothing — an un-retired stale row is one failed resume
186
+ * that falls back to a cold replay, which is what retiring it would have caused
187
+ * anyway.
160
188
  *
161
189
  * IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
162
190
  * `active` left and appends nothing.
@@ -164,12 +192,34 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
164
192
  * FAILURE STANCE: `appendSession` propagates, and so does this — same as
165
193
  * `markRunSessionsDead`.
166
194
  *
167
- * @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
168
- * this set is skipped whatever its status.
195
+ * @param context the booting shift's ownership and harness identity plus the
196
+ * injectable PID liveness probe.
169
197
  * @returns the records that were retired, as they were BEFORE retirement, so the
170
198
  * caller can log what it took away.
171
199
  */
172
- export declare function reconcileActiveSessions(file: string, liveRunIds: ReadonlySet<string>, now: number, opts?: SessionStoreOptions): SessionRecord[];
200
+ export interface SessionReconcileContext {
201
+ /** Public shift name in force when this shift booted. */
202
+ shiftName: string;
203
+ /** Stable owner key; falls back to `shiftName` for older callers/records. */
204
+ shiftOwner?: string;
205
+ /** Configured harness guard, when this shift has one. */
206
+ harness?: string;
207
+ /** PID probe; defaults to the existing shift-state probe. */
208
+ isAlive?: Liveness;
209
+ }
210
+ export interface RetireDecision {
211
+ retire: boolean;
212
+ reason: string;
213
+ }
214
+ /**
215
+ * Decide whether one active session row is safe to retire.
216
+ *
217
+ * The function is deliberately independent of the JSONL writer. Callers can
218
+ * exercise the safety predicate with a deterministic PID probe, while the
219
+ * production path uses `process.kill(pid, 0)` through `defaultIsAlive`.
220
+ */
221
+ export declare function shouldRetireSession(record: SessionRecord, context: SessionReconcileContext): RetireDecision;
222
+ export declare function reconcileActiveSessions(file: string, context: SessionReconcileContext, now: number, opts?: SessionStoreOptions): SessionRecord[];
173
223
  /**
174
224
  * Append one record, then compact when the file has grown past `maxBytes`.
175
225
  *
@@ -52,6 +52,7 @@
52
52
  import { closeSync, fstatSync, fsyncSync, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
53
53
  import { join } from 'node:path';
54
54
  import { acquireFileLockSync, releaseFileLock } from "../../../../src/lock.js";
55
+ import { defaultIsAlive } from "../shift/state.js";
55
56
  const STATUSES = new Set(['active', 'turn-ended', 'submitted', 'dead']);
56
57
  /** Default compaction threshold — plan §3's 2 MB. */
57
58
  export const DEFAULT_MAX_BYTES = 2_000_000;
@@ -456,57 +457,51 @@ export function markRunSessionsDead(file, workflow, run, now, opts = {}) {
456
457
  });
457
458
  }
458
459
  /**
459
- * PHASE 6, ITEM 4 — retire the `active` sessions of runs that are no longer
460
- * running, so a crash or a reboot does not leave the store claiming a turn is in
461
- * flight when no process exists.
460
+ * Decide whether one active session row is safe to retire.
462
461
  *
463
- * WHAT IS BROKEN WITHOUT THIS. `src/agent/loop.ts` writes `status: 'active'` when
464
- * a turn starts and rewrites it at turn end. A worker killed mid-turn — SIGKILL,
465
- * a panic, a reboot — never reaches the rewrite, so the newest row for that step
466
- * says `active` forever. Nothing else ever corrects it.
467
- *
468
- * ── WHY THIS IS NOT `markRunSessionsDead` ────────────────────────────────────
469
- *
470
- * `markRunSessionsDead` retires EVERY non-`dead` newest row of a run. Reusing it
471
- * here would destroy exactly the capability this phase has to keep working:
472
- * `src/agent/loop.ts` refuses to resume a session whose previous status is
473
- * `dead`, and a `turn-ended` or `submitted` row is a COMPLETED turn whose
474
- * provider-side session is intact. A reboot does not invalidate one. Leaving
475
- * those rows alone is precisely what "resume still works after a reboot" means.
476
- *
477
- * So ONLY `active` rows are eligible, and only for runs absent from
478
- * `liveRunIds`.
479
- *
480
- * ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
481
- *
482
- * An interrupted turn is the state you least want to resume into: the harness may
483
- * have half-applied tool calls the worker has no record of, so a resumed session
484
- * would carry a model that believes work happened which did not. The cost of
485
- * retiring it is one cold replay. The cost of resuming it is silent divergence.
486
- *
487
- * ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
488
- *
489
- * An `owenloop work agent-run` started BY HAND, outside the shift, has no child record
490
- * in the shift state dir, so a shift booting at that moment sees its `active` row
491
- * as orphaned and retires it. The cost is one cold replay on a hand-run debugging
492
- * session. Two things keep it small: the caller invokes this at BOOT only, which
493
- * narrows the window to an instant, and every retirement is returned so the
494
- * caller can log it with its `(workflow, run, step)`. Do NOT add a pid field to
495
- * `SessionRecord` to close this — the record is deliberately machine-portable
496
- * metadata, and the shift state dir is already the system of record for liveness.
497
- *
498
- * IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
499
- * `active` left and appends nothing.
500
- *
501
- * FAILURE STANCE: `appendSession` propagates, and so does this — same as
502
- * `markRunSessionsDead`.
503
- *
504
- * @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
505
- * this set is skipped whatever its status.
506
- * @returns the records that were retired, as they were BEFORE retirement, so the
507
- * caller can log what it took away.
462
+ * The function is deliberately independent of the JSONL writer. Callers can
463
+ * exercise the safety predicate with a deterministic PID probe, while the
464
+ * production path uses `process.kill(pid, 0)` through `defaultIsAlive`.
508
465
  */
509
- export function reconcileActiveSessions(file, liveRunIds, now, opts = {}) {
466
+ export function shouldRetireSession(record, context) {
467
+ const recordOwner = record.shiftOwner ?? record.shiftName;
468
+ const contextOwner = context.shiftOwner ?? context.shiftName;
469
+ if (typeof recordOwner !== 'string' || recordOwner.trim() === '') {
470
+ return { retire: false, reason: 'session has no owning shift name' };
471
+ }
472
+ if (typeof contextOwner !== 'string' || contextOwner.trim() === '') {
473
+ return { retire: false, reason: 'booting shift has no stable owner key' };
474
+ }
475
+ if (recordOwner !== contextOwner) {
476
+ return {
477
+ retire: false,
478
+ reason: `session belongs to shift '${recordOwner}', not '${contextOwner}'`,
479
+ };
480
+ }
481
+ const pid = record.pid;
482
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
483
+ return { retire: false, reason: 'session has no valid worker pid' };
484
+ }
485
+ const isAlive = context.isAlive ?? defaultIsAlive;
486
+ let alive;
487
+ try {
488
+ alive = isAlive(pid);
489
+ }
490
+ catch {
491
+ return { retire: false, reason: `worker pid ${String(pid)} liveness is unknown` };
492
+ }
493
+ if (alive) {
494
+ return { retire: false, reason: `worker pid ${String(pid)} is alive` };
495
+ }
496
+ if (context.harness !== undefined && context.harness !== '' && record.harness !== context.harness) {
497
+ return {
498
+ retire: false,
499
+ reason: `harness mismatch: session uses '${record.harness}', shift uses '${context.harness}'`,
500
+ };
501
+ }
502
+ return { retire: true, reason: `worker pid ${String(pid)} is confirmed dead` };
503
+ }
504
+ export function reconcileActiveSessions(file, context, now, opts = {}) {
510
505
  mkdirSync(join(file, '..'), { recursive: true });
511
506
  return withWriterLock(file, () => {
512
507
  const newest = new Map();
@@ -518,8 +513,15 @@ export function reconcileActiveSessions(file, liveRunIds, now, opts = {}) {
518
513
  for (const rec of newest.values()) {
519
514
  if (rec.status !== 'active')
520
515
  continue; // a completed turn is still resumable
521
- if (liveRunIds.has(rec.run))
522
- continue; // its worker is alive; the row is true
516
+ const decision = shouldRetireSession(rec, context);
517
+ if (!decision.retire) {
518
+ opts.debug?.(`owenloop work sessions: skipped orphan reconciliation for ${rec.workflow}/${rec.run} ` +
519
+ `step '${rec.step}': ${decision.reason}`);
520
+ if (decision.reason.startsWith('harness mismatch:')) {
521
+ (opts.warn ?? defaultWarn)(`owenloop work sessions: refusing to retire ${rec.workflow}/${rec.run} step '${rec.step}': ${decision.reason}`);
522
+ }
523
+ continue;
524
+ }
523
525
  appendSessionUnlocked(file, { ...rec, status: 'dead', updatedAt: now }, opts);
524
526
  retired.push(rec);
525
527
  }