podster 0.0.0-stage → 0.0.1-test.2

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 (53) hide show
  1. package/README.md +116 -2
  2. package/build/core/adapter.js +1 -0
  3. package/build/core/broker.js +461 -0
  4. package/build/core/capabilities.js +49 -0
  5. package/build/core/claude-profile.js +35 -0
  6. package/build/core/connection.js +106 -0
  7. package/build/core/errors.js +115 -0
  8. package/build/core/gateway.js +93 -0
  9. package/build/core/lifecycle.js +1207 -0
  10. package/build/core/nudge.js +340 -0
  11. package/build/core/pairing.js +285 -0
  12. package/build/core/policy.js +741 -0
  13. package/build/core/poller.js +261 -0
  14. package/build/core/prompt.js +93 -0
  15. package/build/core/record.js +106 -0
  16. package/build/core/repository.js +272 -0
  17. package/build/core/results.js +149 -0
  18. package/build/core/run-interface.js +464 -0
  19. package/build/core/runs.js +172 -0
  20. package/build/core/runtime.js +38 -0
  21. package/build/core/state.js +41 -0
  22. package/build/core/storage.js +125 -0
  23. package/build/core/thumbprint.js +15 -0
  24. package/build/core/tool-policy.js +130 -0
  25. package/build/node/broker-listener.js +183 -0
  26. package/build/node/child-env.js +26 -0
  27. package/build/node/claude-driver.js +741 -0
  28. package/build/node/claude-engine.js +196 -0
  29. package/build/node/cli.js +273 -0
  30. package/build/node/docker-sandbox.js +465 -0
  31. package/build/node/file-runs.js +63 -0
  32. package/build/node/file-state.js +73 -0
  33. package/build/node/git.js +124 -0
  34. package/build/node/github-api.js +79 -0
  35. package/build/node/hidden-input.js +47 -0
  36. package/build/node/key-store.js +150 -0
  37. package/build/node/keychain.js +160 -0
  38. package/build/node/local-stop.js +67 -0
  39. package/build/node/lock.js +155 -0
  40. package/build/node/nudge-command.js +132 -0
  41. package/build/node/nudge-listener.js +137 -0
  42. package/build/node/platform.js +127 -0
  43. package/build/node/policy-file.js +13 -0
  44. package/build/node/prompter.js +166 -0
  45. package/build/node/provider-transport.js +181 -0
  46. package/build/node/repo-path.js +370 -0
  47. package/build/node/run-command.js +59 -0
  48. package/build/node/safe-fs.js +244 -0
  49. package/claude-image/Dockerfile +29 -0
  50. package/git/credential-helper +23 -0
  51. package/npm-shrinkwrap.json +3173 -0
  52. package/package.json +47 -4
  53. package/sandbox/Dockerfile +17 -0
@@ -0,0 +1,741 @@
1
+ /**
2
+ * Runner's run policy (M7 step 7; RUNNER.md "Run policy and budget"; decision 29 as the owner ruled it on 2026-11-17).
3
+ * Pure: it imports nothing, reads no clock (`now` is an input), uses no randomness and does no I/O. A test holds it so.
4
+ *
5
+ * Inputs: the owner's local configuration (rooms, the organizations allowed in each, run mode, tools, network, caps),
6
+ * the task's IDs, its `provenance` from `get_task`, the inputs the prompt will be built from, whether Runner's authority
7
+ * is fresh (`Poller.authorityFresh()`, passed in as a value), the day's spend and reservations, and `now`. Output: ask,
8
+ * run or refuse, with a reason code. Every input is copied to plain data once, at entry, and read as own properties
9
+ * only, so a getter answers once and nothing on `Object.prototype` counts.
10
+ *
11
+ * - **Ask first is the default.** A room runs unattended only when the machine's owner set `mode: "unattended"` for that
12
+ * one room in this local configuration. There is no all-rooms setting, and nothing from Podster is read for the mode:
13
+ * the task is taken by its IDs alone, and a provenance with any field the contract doesn't have is refused (S-40).
14
+ * - **The least-trusted author decides.** An unattended run needs the requester and every author of every input to be
15
+ * named, of the owner's organization, active, and not marked external by the server; and no input marked external.
16
+ * Unknown or inactive counts as external (F3, G1, G2). Either signal of externality wins: Runner's own comparison with
17
+ * the owner's organization, or the server's flag. Any of them makes it ask, never run.
18
+ * - **Scope.** A requester or author whose organization is named and is neither the owner's nor listed for the room is
19
+ * out of scope, and the task is refused (RUNNER.md: "Do not start; report the missing scope"). An unknown organization
20
+ * can't be scoped, so it asks.
21
+ * - **The room split.** Every unattended room needs the owner to have accepted the trust statement for it, the residual
22
+ * risk RUNNER.md asks every unattended setup to disclose (L3 on #455's review). A public room also needs the
23
+ * public-room warning (decision 232).
24
+ * - **The prompt's inputs** must be exactly those `provenance` lists, in its order, and a change request exactly the one
25
+ * whose `event_id` provenance names (M2 on #455's review). Steps 8 and 9 build the prompt from those inputs only, and
26
+ * the change request from that event only.
27
+ * - **Caps** on spend, run time, turns and output tokens, and the bounded `max_tokens` the broker writes into each
28
+ * request, are required, each a positive integer under a fixed ceiling, with no "none" (condition 3; spike B rulings 3
29
+ * and 5). A configuration lacking any of them is refused whole, as is anything else malformed.
30
+ * - **Tools and network** are facts for step 9's adapter, which enforces them: no shell and no network unless listed by
31
+ * name (condition 2). The adapter's result tool is always named.
32
+ * - **Run decisions** are bound to every run fact, by a canonical form of the whole `RunFacts` (M1 on #455's review), and
33
+ * to the task's version, input hash, repository and base. They are single-use and expire.
34
+ * - **The repository** (M7 step 10; L4 on #455's review): a room has one only when the owner named it here, by full name
35
+ * and GitHub's numeric ID. It is a run fact, with the task's branch, so the decision binds it; the binding's
36
+ * `repository_id` must be that ID. The base can't be known before the task is accepted (`get_repo_access` answers only
37
+ * then), so a decision for such a room is issued with its base unpinned, `pinRunBase` pins it exactly once to the
38
+ * commit Runner's checkout was verified at, and `consumeRunDecision` refuses one still unpinned.
39
+ *
40
+ * **The caller serialises.** Runner must run evaluate-then-issue, and evaluate-then-consume, as one step each per Runner,
41
+ * with nothing else evaluating or reserving between them; the day's reservations it passes in are only right if so. At
42
+ * consume, it passes this decision's own reservation as `own_reservation_micro_usd`, so the fresh evaluation doesn't count
43
+ * it twice (L5 on #455's review). The decision says what it left out, and consume refuses anything but none or the
44
+ * record's own `reserved_micro_usd`, so a caller can't leave out more (L5, bound 2026-11-18).
45
+ *
46
+ * Agent content is data: task text is never an input here, only provenance IDs and organizations. A decision carries
47
+ * IDs, codes, paths and hostnames only, so it can be logged by ID.
48
+ */
49
+ export const POLICY_VERSION = 1;
50
+ export const ADAPTERS = ["claude_agent_sdk"];
51
+ /** Runner's own tools, run in the task's container (spike B ruling 1). Shell only when the owner lists it. */
52
+ export const TOOLS = ["read", "search", "write", "edit", "shell"];
53
+ export const DEFAULT_TOOLS = ["read", "search", "write", "edit"];
54
+ /** The SDK's structured result is itself a tool call, so the policy always names it (spike B ruling 2). */
55
+ export const RESULT_TOOL = "StructuredOutput";
56
+ /** Fixed ceilings, **Proposed** for the owner to review. A cap can be set lower, never above, and never unset. */
57
+ export const CEILINGS = {
58
+ spend_micro_usd: 25_000_000,
59
+ run_time_ms: 24 * 60 * 60 * 1000,
60
+ turns: 1_000,
61
+ output_tokens: 1_000_000,
62
+ max_tokens: 32_000,
63
+ };
64
+ export const MIN_RUN_TIME_MS = 60_000;
65
+ export const DAY_SPEND_CEILING_MICRO_USD = 250_000_000;
66
+ /** How long a run decision may wait before it is used. */
67
+ export const DECISION_TTL_MS = 10 * 60 * 1000;
68
+ /**
69
+ * How many tasks Runner holds at once: the run under way and every finished run whose publication is held for a retry
70
+ * (the ruling on #462's held publications). Runner runs one task at a time, so above one this lets new tasks run while a
71
+ * publication waits. One unless the owner sets `max_active_tasks`; the ceiling is **Proposed**.
72
+ */
73
+ export const MAX_ACTIVE_TASKS_CEILING = 4;
74
+ const MAX_ROOMS = 200;
75
+ const MAX_ORGS = 50;
76
+ const MAX_HOSTS = 50;
77
+ const MAX_AUTHORS = 1_000;
78
+ const MAX_ROOT = 1_024;
79
+ const MAX_NODES = 200_000;
80
+ const MAX_DEPTH = 8;
81
+ const MAX_FACTS_KEY = 4 * 1024 * 1024;
82
+ /**
83
+ * Room, workspace, task, organization, repository and event IDs are lower case, since they reach paths and path-like
84
+ * comparisons (L6 on #455's review, narrowed 2026-11-18). An agent's ID reaches the policy only as a requester or an
85
+ * author, so it is read as an actor ID below, and compared exactly.
86
+ */
87
+ const ID = /^[a-z0-9_-]{1,128}$/;
88
+ /**
89
+ * A requester's or author's ID: a person's is `per_` plus Better Auth's mixed-case ID (`personId` in
90
+ * apps/gateway/src/index.ts). Only ever compared exactly, never used in a path.
91
+ */
92
+ const ACTOR_ID = /^[A-Za-z0-9_-]{1,128}$/;
93
+ const HEX64 = /^[0-9a-f]{64}$/;
94
+ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
95
+ const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
96
+ const TLD = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
97
+ const INPUTS = ["title", "instructions", "acceptance_criteria", "change_request"];
98
+ const fail = (at) => ({ ok: false, at });
99
+ /**
100
+ * A plain-data copy: null-prototype objects of own enumerable keys, arrays, strings, numbers, booleans, null. Each
101
+ * property is read once. Anything else (a class instance, a function, too deep or too large) throws.
102
+ */
103
+ function plain(v, depth, count) {
104
+ count.n += 1;
105
+ if (count.n > MAX_NODES || depth > MAX_DEPTH)
106
+ throw new Error("too_large");
107
+ if (v === null || v === undefined || typeof v === "string" || typeof v === "boolean" || typeof v === "number")
108
+ return v;
109
+ if (Array.isArray(v)) {
110
+ const out = [];
111
+ const length = v.length;
112
+ if (length > MAX_NODES)
113
+ throw new Error("too_large");
114
+ for (let i = 0; i < length; i++)
115
+ out.push(plain(v[i], depth + 1, count));
116
+ return out;
117
+ }
118
+ if (typeof v === "object") {
119
+ const proto = Object.getPrototypeOf(v);
120
+ if (proto !== Object.prototype && proto !== null)
121
+ throw new Error("not_data");
122
+ const out = Object.create(null);
123
+ for (const key of Object.keys(v))
124
+ out[key] = plain(v[key], depth + 1, count);
125
+ return out;
126
+ }
127
+ throw new Error("not_data");
128
+ }
129
+ const NOT_DATA = { not_data: true };
130
+ function copy(v) {
131
+ try {
132
+ return plain(v, 0, { n: 0 });
133
+ }
134
+ catch {
135
+ return NOT_DATA;
136
+ }
137
+ }
138
+ function isObj(v) {
139
+ if (typeof v !== "object" || v === null || Array.isArray(v) || v === NOT_DATA)
140
+ return false;
141
+ const proto = Object.getPrototypeOf(v);
142
+ return proto === Object.prototype || proto === null;
143
+ }
144
+ const own = (o, k) => (Object.hasOwn(o, k) ? o[k] : undefined);
145
+ /** Exactly these keys, the optional ones allowed to be absent. */
146
+ function keysAre(o, required, optional = []) {
147
+ const keys = Object.keys(o);
148
+ return required.every((k) => Object.hasOwn(o, k)) && keys.every((k) => required.includes(k) || optional.includes(k));
149
+ }
150
+ const isId = (v) => typeof v === "string" && ID.test(v);
151
+ const isActorId = (v) => typeof v === "string" && ACTOR_ID.test(v);
152
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
153
+ const inRange = (v, min, max) => isCount(v) && v >= min && v <= max;
154
+ const isInput = (v) => typeof v === "string" && INPUTS.includes(v);
155
+ function uniqueList(v, max, each) {
156
+ if (!Array.isArray(v) || v.length > max)
157
+ return null;
158
+ if (!v.every(each))
159
+ return null;
160
+ return new Set(v).size === v.length ? [...v] : null;
161
+ }
162
+ function isHost(v) {
163
+ if (typeof v !== "string" || v.length > 253)
164
+ return false;
165
+ const labels = v.split(".");
166
+ return labels.length >= 2 && labels.every((l) => LABEL.test(l)) && TLD.test(labels[labels.length - 1]);
167
+ }
168
+ const isTool = (v) => typeof v === "string" && TOOLS.includes(v);
169
+ const GH_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
170
+ const GH_REPO = /^[A-Za-z0-9._-]{1,100}$/;
171
+ /** `owner/name` as GitHub writes it, with nothing that could be a path trick, a URL or an option. */
172
+ export function isFullName(v) {
173
+ if (typeof v !== "string" || v.length > 140)
174
+ return false;
175
+ const parts = v.split("/");
176
+ if (parts.length !== 2 || !GH_OWNER.test(parts[0]) || !GH_REPO.test(parts[1]))
177
+ return false;
178
+ const name = parts[1];
179
+ return name !== "." && name !== ".." && !name.toLowerCase().endsWith(".git") && !name.startsWith("-") && !name.startsWith(".");
180
+ }
181
+ /** The owner's repository setting for a room, checked whole: exactly `full_name` and a positive `provider_repo_id`. */
182
+ export function parseRepoScope(v) {
183
+ if (!isObj(v) || !keysAre(v, ["full_name", "provider_repo_id"]))
184
+ return null;
185
+ const { full_name, provider_repo_id } = v;
186
+ if (!isFullName(full_name) || !isCount(provider_repo_id) || provider_repo_id < 1)
187
+ return null;
188
+ return { full_name, provider_repo_id };
189
+ }
190
+ function isRoot(v) {
191
+ if (typeof v !== "string" || v.length < 2 || v.length > MAX_ROOT || !v.startsWith("/") || v.endsWith("/"))
192
+ return false;
193
+ // A comma, colon or equals sign would be read as a container mount's options (L4 on #459).
194
+ if (/[\u0000-\u001f\u007f\\,:=]/.test(v))
195
+ return false;
196
+ return v.slice(1).split("/").every((s) => s !== "" && s !== "." && s !== "..");
197
+ }
198
+ /** Input names in the contract's order, title and instructions first, each once. */
199
+ function isInputList(v) {
200
+ if (!Array.isArray(v) || v.length < 2 || v.length > INPUTS.length || !v.every(isInput))
201
+ return false;
202
+ if (v[0] !== "title" || v[1] !== "instructions")
203
+ return false;
204
+ return v.every((x, i) => i === 0 || INPUTS.indexOf(x) > INPUTS.indexOf(v[i - 1]));
205
+ }
206
+ function parseCaps(v) {
207
+ if (!isObj(v) || !keysAre(v, Object.keys(CEILINGS)))
208
+ return fail("caps");
209
+ const { spend_micro_usd, run_time_ms, turns, output_tokens, max_tokens } = v;
210
+ if (!inRange(spend_micro_usd, 1, CEILINGS.spend_micro_usd))
211
+ return fail("caps.spend_micro_usd");
212
+ if (!inRange(run_time_ms, MIN_RUN_TIME_MS, CEILINGS.run_time_ms))
213
+ return fail("caps.run_time_ms");
214
+ if (!inRange(turns, 1, CEILINGS.turns))
215
+ return fail("caps.turns");
216
+ if (!inRange(output_tokens, 1, CEILINGS.output_tokens))
217
+ return fail("caps.output_tokens");
218
+ if (!inRange(max_tokens, 1, CEILINGS.max_tokens) || max_tokens > output_tokens)
219
+ return fail("caps.max_tokens");
220
+ return { ok: true, value: { spend_micro_usd, run_time_ms, turns, output_tokens, max_tokens } };
221
+ }
222
+ function parseRoom(v, ownerOrg) {
223
+ if (!isObj(v) || !keysAre(v, ["room_id", "allowed_orgs", "acknowledged"], ["mode", "tools", "network", "outputs", "repository"]))
224
+ return fail("rooms[]");
225
+ const roomId = own(v, "room_id");
226
+ if (!isId(roomId))
227
+ return fail("rooms[].room_id");
228
+ const mode = Object.hasOwn(v, "mode") ? v.mode : "ask";
229
+ if (mode !== "ask" && mode !== "unattended")
230
+ return fail("rooms[].mode");
231
+ const allowed = uniqueList(own(v, "allowed_orgs"), MAX_ORGS, isId);
232
+ if (!allowed || allowed.includes(ownerOrg))
233
+ return fail("rooms[].allowed_orgs");
234
+ const tools = Object.hasOwn(v, "tools") ? uniqueList(v.tools, TOOLS.length, isTool) : [...DEFAULT_TOOLS];
235
+ if (!tools)
236
+ return fail("rooms[].tools");
237
+ const network = Object.hasOwn(v, "network") ? uniqueList(v.network, MAX_HOSTS, isHost) : [];
238
+ if (!network)
239
+ return fail("rooms[].network");
240
+ const outputs = Object.hasOwn(v, "outputs") ? v.outputs : "hold";
241
+ if (outputs !== "hold" && outputs !== "share")
242
+ return fail("rooms[].outputs");
243
+ const ack = own(v, "acknowledged");
244
+ if (!isObj(ack) || !keysAre(ack, ["trust_statement", "public_room_warning"]))
245
+ return fail("rooms[].acknowledged");
246
+ const trust = own(ack, "trust_statement");
247
+ const warning = own(ack, "public_room_warning");
248
+ if (typeof trust !== "boolean" || typeof warning !== "boolean")
249
+ return fail("rooms[].acknowledged");
250
+ const given = Object.hasOwn(v, "repository") ? v.repository : null;
251
+ const repository = given === null ? null : parseRepoScope(given);
252
+ if (given !== null && repository === null)
253
+ return fail("rooms[].repository");
254
+ return { ok: true, value: { room_id: roomId, mode, allowed_orgs: allowed, tools, network, outputs, acknowledged: { trust_statement: trust, public_room_warning: warning }, repository } };
255
+ }
256
+ /**
257
+ * Whether a path is on a Windows drive as WSL2 mounts it by default (`/mnt/c`, `/mnt/d/…`): the Windows file system,
258
+ * where Linux file modes aren't enforced and access is slow (S-47, the architect's ruling of 2026-11-19). A distro that
259
+ * mounts its drives elsewhere is caught on the host by the mount's file system type (`platform.ts`), not here.
260
+ */
261
+ export function onWindowsDrive(path) {
262
+ return /^\/mnt\/[A-Za-z](\/|$)/.test(path);
263
+ }
264
+ /** Whether two plain absolute paths are the same or one holds the other. */
265
+ function overlaps(a, b) {
266
+ return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
267
+ }
268
+ /**
269
+ * Checks the owner's configuration whole. Anything missing, unknown or out of range refuses it: fail closed.
270
+ * `runner_home`, when given, is Runner's own home: a workspace root that holds it, or sits inside it, refuses the whole
271
+ * configuration, so no task folder is ever Runner's home, its Git folders or its keys' neighbours, and Runner's home is
272
+ * never inside a folder a container mounts (ruling 4 on #462). Runner's command line always gives it.
273
+ */
274
+ export function parsePolicyConfig(input, context = {}) {
275
+ try {
276
+ const home = copy(context);
277
+ const runnerHome = isObj(home) && Object.hasOwn(home, "runner_home") ? home.runner_home : undefined;
278
+ if (runnerHome !== undefined && !isRoot(runnerHome))
279
+ return fail("runner_home");
280
+ if (typeof runnerHome === "string" && onWindowsDrive(runnerHome))
281
+ return fail("runner_home_windows_drive");
282
+ const raw = copy(input);
283
+ if (!isObj(raw) || !keysAre(raw, ["version", "revision", "owner_org", "adapter", "workspace_root", "caps", "day_caps", "rooms"], ["max_active_tasks"]))
284
+ return fail("config");
285
+ const maxActive = Object.hasOwn(raw, "max_active_tasks") ? raw.max_active_tasks : 1;
286
+ if (!inRange(maxActive, 1, MAX_ACTIVE_TASKS_CEILING))
287
+ return fail("max_active_tasks");
288
+ if (raw.version !== POLICY_VERSION)
289
+ return fail("version");
290
+ const revision = raw.revision;
291
+ if (!inRange(revision, 1, Number.MAX_SAFE_INTEGER))
292
+ return fail("revision");
293
+ const ownerOrg = raw.owner_org;
294
+ if (!isId(ownerOrg))
295
+ return fail("owner_org");
296
+ const adapter = raw.adapter;
297
+ if (typeof adapter !== "string" || !ADAPTERS.includes(adapter))
298
+ return fail("adapter");
299
+ const root = raw.workspace_root;
300
+ if (!isRoot(root))
301
+ return fail("workspace_root");
302
+ if (onWindowsDrive(root))
303
+ return fail("workspace_root_windows_drive");
304
+ if (typeof runnerHome === "string" && overlaps(root, runnerHome))
305
+ return fail("workspace_root");
306
+ const caps = parseCaps(raw.caps);
307
+ if (!caps.ok)
308
+ return caps;
309
+ const day = raw.day_caps;
310
+ if (!isObj(day) || !keysAre(day, ["spend_micro_usd"]))
311
+ return fail("day_caps");
312
+ const daySpend = day.spend_micro_usd;
313
+ if (!inRange(daySpend, caps.value.spend_micro_usd, DAY_SPEND_CEILING_MICRO_USD))
314
+ return fail("day_caps.spend_micro_usd");
315
+ if (!Array.isArray(raw.rooms) || raw.rooms.length > MAX_ROOMS)
316
+ return fail("rooms");
317
+ const rooms = [];
318
+ for (const r of raw.rooms) {
319
+ const room = parseRoom(r, ownerOrg);
320
+ if (!room.ok)
321
+ return room;
322
+ if (rooms.some((x) => x.room_id === room.value.room_id))
323
+ return fail("rooms[].room_id");
324
+ rooms.push(room.value);
325
+ }
326
+ return { ok: true, value: { version: 1, revision, owner_org: ownerOrg, adapter: adapter, workspace_root: root, caps: caps.value, day_caps: { spend_micro_usd: daySpend }, rooms, max_active_tasks: maxActive } };
327
+ }
328
+ catch {
329
+ return fail("config");
330
+ }
331
+ }
332
+ const isOrg = (v) => v === null || isId(v);
333
+ function parseAuthor(v) {
334
+ if (!isObj(v) || !keysAre(v, ["id", "org", "external", "active", "written_at"]))
335
+ return null;
336
+ const { id, org, external, active } = v;
337
+ if (!(id === null || isActorId(id)) || !isOrg(org))
338
+ return null;
339
+ if (typeof external !== "boolean" || typeof active !== "boolean")
340
+ return null;
341
+ // A named author has a time; only the unknown author has none (L7 on #455's review).
342
+ if (id === null ? v.written_at !== null : !isCount(v.written_at))
343
+ return null;
344
+ return { id, org, external, active };
345
+ }
346
+ /** Checks `get_task`'s provenance against the contract's `TaskProvenance`, strictly. */
347
+ function parseProvenance(v) {
348
+ if (!isObj(v) || !keysAre(v, ["room_visibility", "requester", "inputs"]))
349
+ return null;
350
+ const visibility = v.room_visibility;
351
+ if (visibility !== "private" && visibility !== "public")
352
+ return null;
353
+ const r = v.requester;
354
+ if (!isObj(r) || !keysAre(r, ["id", "org", "external", "active"]))
355
+ return null;
356
+ const { id, org, external, active } = r;
357
+ if (!isActorId(id) || !isOrg(org) || typeof external !== "boolean" || typeof active !== "boolean")
358
+ return null;
359
+ if (!Array.isArray(v.inputs))
360
+ return null;
361
+ const inputs = [];
362
+ for (const i of v.inputs) {
363
+ if (!isObj(i) || !keysAre(i, ["input", "external", "authors"], ["event_id"]))
364
+ return null;
365
+ const name = i.input;
366
+ if (!isInput(name) || typeof i.external !== "boolean")
367
+ return null;
368
+ const hasEvent = Object.hasOwn(i, "event_id");
369
+ if (hasEvent && (name !== "change_request" || !(i.event_id === null || isId(i.event_id))))
370
+ return null;
371
+ if (!Array.isArray(i.authors) || i.authors.length < 1 || i.authors.length > MAX_AUTHORS)
372
+ return null;
373
+ const authors = [];
374
+ for (const a of i.authors) {
375
+ const author = parseAuthor(a);
376
+ if (!author)
377
+ return null;
378
+ authors.push(author);
379
+ }
380
+ inputs.push({ input: name, external: i.external, authors, event_id: hasEvent ? i.event_id : null });
381
+ }
382
+ if (!isInputList(inputs.map((i) => i.input)))
383
+ return null;
384
+ return { room_visibility: visibility, requester: { id, org, external, active }, inputs };
385
+ }
386
+ /** The prompt's inputs must be exactly provenance's, and its change request exactly the event provenance names. */
387
+ function promptMatches(v, prov) {
388
+ if (!isObj(v) || !keysAre(v, ["inputs", "change_request_event_id"]))
389
+ return null;
390
+ const names = v.inputs;
391
+ const event = v.change_request_event_id;
392
+ if (!isInputList(names) || names.length !== prov.inputs.length || !names.every((n, i) => n === prov.inputs[i].input))
393
+ return null;
394
+ const request = prov.inputs.find((i) => i.input === "change_request");
395
+ if (request === undefined)
396
+ return event === null ? { inputs: [...names], event: null } : null;
397
+ if (!isId(event) || request.event_id !== event)
398
+ return null;
399
+ return { inputs: [...names], event };
400
+ }
401
+ /** How Runner reads one actor against the owner's organization. The first that applies, in this order. */
402
+ function standing(a, ownerOrg) {
403
+ if (a.id === null || a.org === null)
404
+ return "unknown";
405
+ if (!a.active)
406
+ return "inactive";
407
+ if (a.org !== ownerOrg || a.external)
408
+ return "external";
409
+ return "internal";
410
+ }
411
+ const label = (a) => (a.id === null ? "?" : `${a.id}@${a.org ?? "?"}`);
412
+ export function evaluate(input) {
413
+ try {
414
+ return decide(input);
415
+ }
416
+ catch {
417
+ return { outcome: "refuse", reason: "config_invalid" };
418
+ }
419
+ }
420
+ function decide(input) {
421
+ const given = copy(input);
422
+ if (!isObj(given))
423
+ return { outcome: "refuse", reason: "config_invalid" };
424
+ const parsed = parsePolicyConfig(own(given, "config"), Object.hasOwn(given, "runner_home") ? { runner_home: given.runner_home } : {});
425
+ if (!parsed.ok)
426
+ return { outcome: "refuse", reason: "config_invalid" };
427
+ const config = parsed.value;
428
+ const now = own(given, "now");
429
+ if (!isCount(now))
430
+ return { outcome: "refuse", reason: "clock_invalid" };
431
+ const t = own(given, "task");
432
+ if (!isObj(t) || !isId(own(t, "id")) || !isId(own(t, "workspace_id")))
433
+ return { outcome: "refuse", reason: "task_invalid" };
434
+ const ids = { task_id: t.id, workspace_id: t.workspace_id };
435
+ if (own(given, "authority_fresh") !== true)
436
+ return { outcome: "refuse", reason: "authority_stale", ...ids };
437
+ const prov = parseProvenance(own(given, "provenance"));
438
+ if (!prov)
439
+ return { outcome: "refuse", reason: "provenance_invalid", ...ids };
440
+ const prompt = promptMatches(own(given, "prompt"), prov);
441
+ if (!prompt)
442
+ return { outcome: "refuse", reason: "prompt_mismatch", ...ids };
443
+ const b = own(given, "budget");
444
+ if (!isObj(b) || !keysAre(b, ["spent_today_micro_usd", "reserved_micro_usd"], ["own_reservation_micro_usd"]))
445
+ return { outcome: "refuse", reason: "budget_invalid", ...ids };
446
+ const spent = b.spent_today_micro_usd;
447
+ const reserved = b.reserved_micro_usd;
448
+ const ownReservation = Object.hasOwn(b, "own_reservation_micro_usd") ? b.own_reservation_micro_usd : 0;
449
+ if (!isCount(spent) || !isCount(reserved) || !isCount(ownReservation) || ownReservation > reserved)
450
+ return { outcome: "refuse", reason: "budget_invalid", ...ids };
451
+ const room = config.rooms.find((r) => r.room_id === ids.workspace_id);
452
+ if (!room)
453
+ return { outcome: "refuse", reason: "room_not_configured", ...ids };
454
+ const inScope = (a) => a.org === null || a.org === config.owner_org || room.allowed_orgs.includes(a.org);
455
+ if (!inScope(prov.requester))
456
+ return { outcome: "refuse", reason: "requester_out_of_scope", ...ids };
457
+ if (prov.inputs.some((i) => !i.authors.every(inScope)))
458
+ return { outcome: "refuse", reason: "author_out_of_scope", ...ids };
459
+ if (spent + (reserved - ownReservation) + config.caps.spend_micro_usd > config.day_caps.spend_micro_usd)
460
+ return { outcome: "refuse", reason: "day_budget_exhausted", ...ids };
461
+ const requesterStanding = standing(prov.requester, config.owner_org);
462
+ const authorStandings = prov.inputs.flatMap((i) => i.authors.map((a) => standing(a, config.owner_org)));
463
+ const allInternal = requesterStanding === "internal" && authorStandings.every((s) => s === "internal") && prov.inputs.every((i) => !i.external);
464
+ const isPublic = prov.room_visibility === "public";
465
+ const facts = {
466
+ adapter: config.adapter,
467
+ tools: [...room.tools],
468
+ shell: room.tools.includes("shell"),
469
+ network: [...room.network],
470
+ result_tool: RESULT_TOOL,
471
+ workspace_root: config.workspace_root,
472
+ task_folder: `${config.workspace_root}/${ids.workspace_id}/${ids.task_id}`,
473
+ caps: { ...config.caps },
474
+ outputs: room.outputs === "share" && allInternal && !isPublic ? "share" : "hold",
475
+ policy_revision: config.revision,
476
+ room_visibility: prov.room_visibility,
477
+ prompt_inputs: prompt.inputs,
478
+ change_request_event_id: prompt.event,
479
+ requester: label(prov.requester),
480
+ authors: prov.inputs.map((i) => ({ input: i.input, authors: i.authors.map(label) })),
481
+ repository: room.repository === null ? null : { ...room.repository, branch: `podster/${ids.task_id}` },
482
+ };
483
+ // The reservation left out of the day's count, so consume can hold it to the decision's own (L5, bound 2026-11-18).
484
+ const excluded = { excluded_reservation_micro_usd: ownReservation };
485
+ const ask = (reason) => ({ outcome: "ask", reason, ...ids, facts, ...excluded });
486
+ if (room.mode !== "unattended")
487
+ return ask("room_ask_first");
488
+ if (requesterStanding !== "internal")
489
+ return ask(`requester_${requesterStanding}`);
490
+ for (const i of prov.inputs) {
491
+ for (const a of i.authors) {
492
+ const s = standing(a, config.owner_org);
493
+ if (s !== "internal")
494
+ return ask(`author_${s}`);
495
+ }
496
+ }
497
+ // Every author reads as internal here, so only the server's own flag on an input is left: it wins too.
498
+ if (!allInternal)
499
+ return ask("author_external");
500
+ if (!room.acknowledged.trust_statement)
501
+ return ask("trust_statement_not_accepted");
502
+ if (isPublic && !room.acknowledged.public_room_warning)
503
+ return ask("public_warning_not_accepted");
504
+ return { outcome: "run", reason: "unattended_eligible", ...ids, facts, ...excluded };
505
+ }
506
+ /** One string for a value, its object keys sorted, so two equal fact sets always give the same form. */
507
+ function canonical(v) {
508
+ if (Array.isArray(v))
509
+ return `[${v.map(canonical).join(",")}]`;
510
+ if (typeof v === "object" && v !== null) {
511
+ const o = v;
512
+ return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;
513
+ }
514
+ return JSON.stringify(v) ?? "null";
515
+ }
516
+ /**
517
+ * The canonical form of a decision's facts, as a stored record's `facts_key` holds it, or null for a refusal. Step 8's
518
+ * check-in compares a fresh evaluation's facts with the consumed record's by this.
519
+ */
520
+ export function factsKey(decision) {
521
+ try {
522
+ const d = copy(decision);
523
+ return isDecision(d) ? canonical(d.facts) : null;
524
+ }
525
+ catch {
526
+ return null;
527
+ }
528
+ }
529
+ const BINDING_KEYS = ["task_id", "workspace_id", "task_version", "input_hash", "repository_id", "base_commit"];
530
+ /** A repository's ID in a binding: GitHub's numeric ID, as a string. */
531
+ const REPO_ID = /^[1-9][0-9]{0,15}$/;
532
+ /** `unpinned`: a binding with a repository may still lack its base, as at issue; everywhere else it must have one. */
533
+ function bindingOf(v, extra = [], unpinned = false) {
534
+ if (!isObj(v) || !keysAre(v, [...BINDING_KEYS, ...extra]))
535
+ return null;
536
+ const { task_id, workspace_id, task_version, input_hash, repository_id, base_commit } = v;
537
+ if (!isId(task_id) || !isId(workspace_id) || !isCount(task_version))
538
+ return null;
539
+ if (typeof input_hash !== "string" || !HEX64.test(input_hash))
540
+ return null;
541
+ if (repository_id === null) {
542
+ if (base_commit !== null)
543
+ return null;
544
+ }
545
+ else if (typeof repository_id !== "string" || !REPO_ID.test(repository_id))
546
+ return null;
547
+ else if (!(base_commit === null && unpinned) && (typeof base_commit !== "string" || !COMMIT.test(base_commit)))
548
+ return null;
549
+ return { task_id, workspace_id, task_version, input_hash, repository_id: repository_id, base_commit: base_commit };
550
+ }
551
+ const RECORD_KEYS = ["mode", "prompt_inputs", "change_request_event_id", "facts_key", "reserved_micro_usd", "issued_at", "expires_at", "consumed"];
552
+ /** A stored record, checked whole before anything compares it (L2 on #455's review). */
553
+ function parseRecord(raw) {
554
+ const v = copy(raw);
555
+ // A stored record may hold a repository whose base isn't pinned yet; consume refuses it until it is.
556
+ const binding = bindingOf(v, RECORD_KEYS, true);
557
+ if (!binding || !isObj(v))
558
+ return null;
559
+ const { mode, prompt_inputs, change_request_event_id, facts_key, reserved_micro_usd, issued_at, expires_at, consumed } = v;
560
+ if (mode !== "unattended" && mode !== "approved")
561
+ return null;
562
+ if (!isInputList(prompt_inputs))
563
+ return null;
564
+ if (prompt_inputs.includes("change_request") ? !isId(change_request_event_id) : change_request_event_id !== null)
565
+ return null;
566
+ if (typeof facts_key !== "string" || facts_key.length < 2 || facts_key.length > MAX_FACTS_KEY)
567
+ return null;
568
+ if (!inRange(reserved_micro_usd, 1, CEILINGS.spend_micro_usd))
569
+ return null;
570
+ if (!isCount(issued_at) || expires_at !== issued_at + DECISION_TTL_MS)
571
+ return null;
572
+ if (typeof consumed !== "boolean")
573
+ return null;
574
+ return { ...binding, mode, prompt_inputs: [...prompt_inputs], change_request_event_id: change_request_event_id, facts_key, reserved_micro_usd, issued_at, expires_at, consumed };
575
+ }
576
+ const isDecision = (d) => isObj(d) && (d.outcome === "ask" || d.outcome === "run") && isId(d.task_id) && isId(d.workspace_id) && isObj(d.facts) && isCount(d.excluded_reservation_micro_usd);
577
+ /**
578
+ * A run decision for a `run`, or for an `ask` the owner approved on this machine. Never for a refusal. Single-use, it
579
+ * expires `DECISION_TTL_MS` after `now`, and it reserves the task's spend cap against the day's.
580
+ */
581
+ export function issueRunDecision(decision, binding, now, opts = {}) {
582
+ try {
583
+ const d = copy(decision);
584
+ if (!isDecision(d))
585
+ return { ok: false, reason: "refused" };
586
+ const o = copy(opts);
587
+ const approved = isObj(o) && own(o, "approved_by_owner") === true;
588
+ if (d.outcome === "ask" && !approved)
589
+ return { ok: false, reason: "owner_approval_needed" };
590
+ // No own reservation exists before issue, so an evaluation that left one out skipped counting other runs.
591
+ if (d.excluded_reservation_micro_usd !== 0)
592
+ return { ok: false, reason: "reservation_excluded" };
593
+ if (!isCount(now))
594
+ return { ok: false, reason: "clock_invalid" };
595
+ const b = bindingOf(copy(binding), [], true);
596
+ if (!b || b.task_id !== d.task_id || b.workspace_id !== d.workspace_id)
597
+ return { ok: false, reason: "binding_invalid" };
598
+ const f = d.facts;
599
+ // The binding names the owner's repository for the room, or none when the room has none; and its base is pinned
600
+ // only later, against the verified checkout.
601
+ const repo = isObj(f.repository) ? f.repository : null;
602
+ if (b.repository_id !== (repo === null ? null : String(repo.provider_repo_id)))
603
+ return { ok: false, reason: "binding_invalid" };
604
+ if (b.base_commit !== null)
605
+ return { ok: false, reason: "binding_invalid" };
606
+ return {
607
+ ok: true,
608
+ record: {
609
+ ...b,
610
+ mode: d.outcome === "run" ? "unattended" : "approved",
611
+ prompt_inputs: [...f.prompt_inputs],
612
+ change_request_event_id: f.change_request_event_id,
613
+ facts_key: canonical(f),
614
+ reserved_micro_usd: f.caps.spend_micro_usd,
615
+ issued_at: now,
616
+ expires_at: now + DECISION_TTL_MS,
617
+ consumed: false,
618
+ },
619
+ };
620
+ }
621
+ catch {
622
+ return { ok: false, reason: "refused" };
623
+ }
624
+ }
625
+ /**
626
+ * Spends a run decision at the run's start, against a fresh `evaluate` on a fresh `get_task` (with this decision's own
627
+ * reservation passed as `own_reservation_micro_usd`) and the binding as it now stands: every run passes policy, not just
628
+ * the first. Any difference in the run facts, whatever the policy's revision says, or in the task, its version, input
629
+ * hash, repository or base, refuses it; so does an unattended decision whose fresh evaluation no longer says `run`.
630
+ * Returns the record marked consumed, for the caller to store before starting.
631
+ */
632
+ export function consumeRunDecision(stored, fresh, binding, now) {
633
+ try {
634
+ const record = parseRecord(stored);
635
+ if (!record)
636
+ return { ok: false, reason: "record_invalid" };
637
+ if (!isCount(now) || now < record.issued_at)
638
+ return { ok: false, reason: "clock_invalid" };
639
+ if (record.consumed)
640
+ return { ok: false, reason: "consumed" };
641
+ if (now > record.expires_at)
642
+ return { ok: false, reason: "expired" };
643
+ if (record.repository_id !== null && record.base_commit === null)
644
+ return { ok: false, reason: "base_unpinned" };
645
+ const d = copy(fresh);
646
+ if (!isDecision(d))
647
+ return { ok: false, reason: "refused" };
648
+ if (record.mode === "unattended" && d.outcome !== "run")
649
+ return { ok: false, reason: "no_longer_eligible" };
650
+ // The fresh evaluation may leave out this decision's own reservation, as the record holds it, and nothing else.
651
+ const excluded = d.excluded_reservation_micro_usd;
652
+ if (excluded !== 0 && excluded !== record.reserved_micro_usd)
653
+ return { ok: false, reason: "reservation_mismatch" };
654
+ const b = bindingOf(copy(binding));
655
+ if (!b)
656
+ return { ok: false, reason: "binding_changed" };
657
+ const same = BINDING_KEYS.every((k) => b[k] === record[k]) && d.task_id === record.task_id && d.workspace_id === record.workspace_id;
658
+ if (!same)
659
+ return { ok: false, reason: "binding_changed" };
660
+ if (canonical(d.facts) !== record.facts_key)
661
+ return { ok: false, reason: "facts_changed" };
662
+ return { ok: true, record: { ...record, consumed: true } };
663
+ }
664
+ catch {
665
+ return { ok: false, reason: "record_invalid" };
666
+ }
667
+ }
668
+ /**
669
+ * Pins the base of an issued, unspent decision for a room with a repository, exactly once: the commit Runner's fresh
670
+ * checkout was verified at, before the decision is consumed against that same checkout (M7 step 10). A decision with no
671
+ * repository, one pinned to another base, spent or expired, or a base that isn't a commit ID, is refused, so nothing can
672
+ * move a pinned base afterwards. The same base again answers the record as it is, for a restart between pin and consume.
673
+ */
674
+ export function pinRunBase(stored, base_commit, now) {
675
+ try {
676
+ const record = parseRecord(stored);
677
+ if (!record)
678
+ return { ok: false, reason: "record_invalid" };
679
+ if (!isCount(now) || now < record.issued_at)
680
+ return { ok: false, reason: "clock_invalid" };
681
+ if (record.consumed)
682
+ return { ok: false, reason: "consumed" };
683
+ if (now > record.expires_at)
684
+ return { ok: false, reason: "expired" };
685
+ if (record.repository_id === null)
686
+ return { ok: false, reason: "no_repository" };
687
+ if (typeof base_commit !== "string" || !COMMIT.test(base_commit))
688
+ return { ok: false, reason: "base_invalid" };
689
+ // A restart between the pin and the consume checks out again: the same commit is the pin already made (ruling 6).
690
+ if (record.base_commit === base_commit)
691
+ return { ok: true, record };
692
+ if (record.base_commit !== null)
693
+ return { ok: false, reason: "already_pinned" };
694
+ return { ok: true, record: { ...record, base_commit } };
695
+ }
696
+ catch {
697
+ return { ok: false, reason: "record_invalid" };
698
+ }
699
+ }
700
+ /**
701
+ * The repository facts a decision was made on, and the task's folder, read back from its canonical facts: what the run's
702
+ * publication must use, and nothing else. Null for a decision with no repository, or a record that doesn't hold valid ones.
703
+ */
704
+ export function repositoryOf(stored) {
705
+ try {
706
+ const record = parseRecord(stored);
707
+ if (!record || record.repository_id === null)
708
+ return null;
709
+ const facts = copy(JSON.parse(record.facts_key));
710
+ if (!isObj(facts) || !isObj(facts.repository) || !isRoot(facts.task_folder))
711
+ return null;
712
+ const r = facts.repository;
713
+ if (!keysAre(r, ["full_name", "provider_repo_id", "branch"]) || !isFullName(r.full_name) || !isCount(r.provider_repo_id))
714
+ return null;
715
+ if (String(r.provider_repo_id) !== record.repository_id || r.branch !== `podster/${record.task_id}`)
716
+ return null;
717
+ if (facts.task_folder !== `${facts.workspace_root}/${record.workspace_id}/${record.task_id}`)
718
+ return null;
719
+ return { repository: { full_name: r.full_name, provider_repo_id: r.provider_repo_id, branch: r.branch }, task_folder: facts.task_folder };
720
+ }
721
+ catch {
722
+ return null;
723
+ }
724
+ }
725
+ /**
726
+ * The output policy a stored decision was made on (M7 step 11): `share` only when the record is whole and its facts say
727
+ * so, which they do only for a room the owner set to share, every author internal and the room private. Anything else,
728
+ * a record that doesn't read included, is `hold`.
729
+ */
730
+ export function outputsOf(stored) {
731
+ try {
732
+ const record = parseRecord(stored);
733
+ if (!record)
734
+ return "hold";
735
+ const facts = copy(JSON.parse(record.facts_key));
736
+ return isObj(facts) && facts.outputs === "share" ? "share" : "hold";
737
+ }
738
+ catch {
739
+ return "hold";
740
+ }
741
+ }