@awebai/oats 0.69.24 → 0.70.1

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 (38) hide show
  1. package/bin/oats.mjs +62 -6
  2. package/docs/capabilities.md +374 -18
  3. package/docs/capability-manifest.schema.json +30 -0
  4. package/docs/design/2026-11-20-provider-home-lifecycle.md +3 -1
  5. package/docs/design/2026-11-21-human-ids-contract.md +342 -0
  6. package/docs/design/README.md +2 -0
  7. package/docs/desktop-cli-api.md +111 -4
  8. package/docs/execution-targets.md +24 -1
  9. package/docs/implementation.md +26 -3
  10. package/docs/release-notes/v0.70.0.md +155 -0
  11. package/docs/release-notes/v0.70.1.md +70 -0
  12. package/docs/schedules.md +42 -3
  13. package/docs/souls-and-instances.md +12 -0
  14. package/docs/trust-model.md +8 -1
  15. package/docs/upgrading.md +16 -5
  16. package/lib/automation-scope.mjs +1 -1
  17. package/lib/capability-show.mjs +10 -1
  18. package/lib/core.mjs +408 -66
  19. package/lib/home-integrity.mjs +329 -0
  20. package/lib/hook-env.mjs +2 -1
  21. package/lib/instance-events.mjs +32 -5
  22. package/lib/instance-git.mjs +9 -0
  23. package/lib/instance-inspect.mjs +64 -10
  24. package/lib/instance-listing.mjs +5 -1
  25. package/lib/instance-resolution.mjs +85 -2
  26. package/lib/instance-upgrade.mjs +170 -14
  27. package/lib/remote.mjs +33 -1
  28. package/lib/retire-admission.mjs +7 -0
  29. package/lib/sandbox-allowances.mjs +329 -0
  30. package/lib/schedule.mjs +6 -4
  31. package/lib/servers.mjs +10 -1
  32. package/lib/session-inspect.mjs +20 -75
  33. package/lib/session-providers.mjs +68 -19
  34. package/lib/session-receipt.mjs +93 -0
  35. package/lib/upgrade-state.mjs +6 -1
  36. package/lib/worktree-hooks.mjs +18 -2
  37. package/lib/worktree.mjs +21 -7
  38. package/package.json +1 -1
@@ -11,8 +11,9 @@
11
11
  * It is validated where a provider is used; a problem inside one provider disables that provider
12
12
  * only, a malformed top level every provider of the manifest.
13
13
  *
14
- * The wire. Each call runs the HOME'S OWN module copy (`node <home>/.oats/modules/<capability>/
15
- * <script> <args>`) with its working directory OUTSIDE the home (the filesystem root: a call is
14
+ * The wire. Each call runs the KERNEL'S copy of the home's module, kept outside the home
15
+ * (lib/home-integrity.mjs: `node <instances>/.oats-retirement/modules/…/<capability>/<script>
16
+ * <args>`; never the home's own copy), with its working directory OUTSIDE the home (the filesystem root: a call is
16
17
  * never one of the processes that "work in the home", which a resume and a retire look for; the
17
18
  * home is in the request), with the environment a lifecycle hook of that capability gets
18
19
  * there (lib/hook-env.mjs), `OATS_EVENT=session` and `OATS_BACKEND=<name>`; one JSON request on
@@ -29,6 +30,7 @@ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } fr
29
30
  import { canonicalJson, parseStrictJson } from "./canonical-json.mjs";
30
31
  import { oatsError } from "./errors.mjs";
31
32
  import { instanceSoulDir, lifecycleHookEnv } from "./hook-env.mjs";
33
+ import { capabilityRuntimeOf, moduleCopyProblem, providerHomeTrust, recordsModule, runDirOf } from "./home-integrity.mjs";
32
34
  import { BUILTIN_SESSION_BACKENDS, SESSION_PROVIDERS_FEATURE, SESSION_PROVIDER_NAME_RE } from "./kernel-features.mjs";
33
35
  import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
34
36
  import { dieAt, diesDuring } from "./provider-test-seams.mjs";
@@ -45,7 +47,20 @@ const RESERVED_NAMES = new Set(["tmux", SESSION_PROVIDER_ANY, "herdr"]);
45
47
  export const isSessionProviderName = (name) => typeof name === "string" && SESSION_PROVIDER_NAME_RE.test(name) && !RESERVED_NAMES.has(name);
46
48
  const REQUIRED_VERBS = ["launch", "inspect", "input", "stop"];
47
49
  const OPTIONAL_VERBS = ["inspectMany", "check"];
48
- const PROVIDER_KEYS = ["commands", "harnesses", "description"];
50
+ const PROVIDER_KEYS = ["commands", "harnesses", "description", "wire"];
51
+ /** The version of the wire this kernel speaks with a session provider (docs/capabilities.md "The
52
+ * call"). One version: a provider declares it (`sessionProviders.<name>.wire`), and one that
53
+ * declares none, or another, is never called (wireRefusal); every request carries it, so a
54
+ * provider can refuse a kernel that speaks another. */
55
+ export const SESSION_PROVIDER_WIRE = "1.3";
56
+ /** Why a provider is not called: it speaks another wire than this kernel → `{ code:
57
+ * "E_BACKEND_WIRE", message, details }` naming both versions, or null when they agree. A provider
58
+ * that declares no `wire` is one from before the key: wire 1.2. */
59
+ export function wireRefusal(capability, provider) {
60
+ if (provider.wire === SESSION_PROVIDER_WIRE) return null;
61
+ const theirs = provider.wire ?? "1.2 (it declares none)";
62
+ return { code: "E_BACKEND_WIRE", message: `${capability}'s session provider ${provider.name} speaks wire ${theirs}, and this kernel speaks ${SESSION_PROVIDER_WIRE}: they must be the same. Use the release of ${capability} that goes with this OATS`, details: { backend: provider.name, capability, wire: { provider: provider.wire ?? null, kernel: SESSION_PROVIDER_WIRE } } };
63
+ }
49
64
  const HARNESS_NAME_RE = /^[a-z][a-z0-9-]{0,39}$/;
50
65
  const MAX_PROVIDERS = 16, MAX_HARNESSES = 16, DESCRIPTION_MAX = 200;
51
66
  /** An endpoint is a JSON object of at most this many bytes of canonical JSON (4 KiB). */
@@ -73,6 +88,8 @@ function checkProvider(manifest, name, decl, problems) {
73
88
  if (!isObject(decl)) { bad(at(), "must be an object { commands, harnesses, description? }"); return null; }
74
89
  for (const k of Object.keys(decl)) if (!PROVIDER_KEYS.includes(k)) bad(at(k), `unknown key ${JSON.stringify(k)} (allowed: ${PROVIDER_KEYS.join(", ")})`);
75
90
  if (decl.description !== undefined && !oneLine(decl.description, DESCRIPTION_MAX)) bad(at("description"), `description must be one line of at most ${DESCRIPTION_MAX} characters`);
91
+ // Any version is a sound declaration: one that is not this kernel's is refused where the provider is used (wireRefusal).
92
+ if (decl.wire !== undefined && !(typeof decl.wire === "string" && /^[0-9]{1,3}\.[0-9]{1,3}$/.test(decl.wire))) bad(at("wire"), 'wire must be the wire version the provider speaks, as "<major>.<minor>"');
76
93
 
77
94
  const harnesses = decl.harnesses;
78
95
  if (!Array.isArray(harnesses) || harnesses.length < 1 || harnesses.length > MAX_HARNESSES) bad(at("harnesses"), `harnesses must list 1 to ${MAX_HARNESSES} harness names`);
@@ -96,7 +113,7 @@ function checkProvider(manifest, name, decl, problems) {
96
113
  }
97
114
  }
98
115
  if (problems.length > sound) return null;
99
- return { name, description: decl.description ?? null, harnesses: [...harnesses], commands };
116
+ return { name, description: decl.description ?? null, harnesses: [...harnesses], commands, wire: decl.wire ?? null };
100
117
  }
101
118
 
102
119
  /** A manifest's session providers, validated where they are used. Never throws, whatever `manifest`
@@ -154,8 +171,11 @@ export function selectSessionBackend(name, capabilities, harness, nothing = "not
154
171
  throw Object.assign(oatsError("E_BACKEND_UNKNOWN", safeText(`unknown session backend ${JSON.stringify(name)}: ${broken ? `capability ${broken.capability} declares it malformed: ${broken.message} (at ${broken.pointer})` : "no capability of this instance declares it as a session provider"}; the backends available here: ${available.join(", ")}; ${nothing}`, 2000)), { details: { backend: String(name).slice(0, 80), available } });
155
172
  }
156
173
  const [match] = matches;
174
+ const provider = sessionProvidersOf((capabilities || []).find((c) => c.id === match.capability).manifest).providers[name];
175
+ const wire = wireRefusal(match.capability, provider);
176
+ if (wire) throw Object.assign(oatsError(wire.code, `${wire.message}; ${nothing}`), { details: wire.details });
157
177
  if (harness !== undefined && !match.harnesses.includes(harness)) throw Object.assign(oatsError("E_BACKEND_HARNESS", `session backend ${name} (${match.capability}) does not run the ${harness} harness; it runs ${match.harnesses.join(", ")}; ${nothing}`), { details: { backend: name, capability: match.capability, harness, harnesses: match.harnesses } });
158
- return { backend: name, capability: match.capability, provider: sessionProvidersOf((capabilities || []).find((c) => c.id === match.capability).manifest).providers[name] };
178
+ return { backend: name, capability: match.capability, provider };
159
179
  }
160
180
 
161
181
  // --------------------------------------------------------------------------------------- the records
@@ -238,13 +258,27 @@ export function sessionProviderTimeout(verb, { graceSeconds = 0 } = {}) {
238
258
  * or the manifest no longer declares the provider soundly. `meta`: the home's record (instance.json)
239
259
  * as the caller holds it; `capability` and `name` come from the receipt, never from the record alone.
240
260
  * binding: `{ home, meta, capability, name, provider, moduleDir, cap, digest }`: `cap` the
241
- * capability's runtime row (its captured settings), `digest` its module copy's recorded digest. */
261
+ * capability's runtime row (its captured settings), `digest` what tells its module copy from
262
+ * another home's (for a provider home, the module's source as its receipt records it).
263
+ *
264
+ * A home whose receipt names a session provider is bound from that receipt
265
+ * (lib/home-integrity.mjs): `moduleDir` is the KERNEL's copy of the capability, outside the home,
266
+ * whose manifest is read and whose commands are run, never the home's own copy; with no such
267
+ * copy `{ problem }` names the module (a read then shows the home unavailable, never stopped);
268
+ * and `cap` is the receipt's row, never the home's own record's. A home with no receipt yet (a
269
+ * spawn, before it writes one) is bound from its own fresh copy and the rows the spawn holds. */
242
270
  export function homeSessionProvider(home, meta, capability, name) {
243
271
  if (typeof capability !== "string" || !CAPABILITY_ID_RE.test(capability)) return { problem: `the session provider's capability id ${JSON.stringify(capability)} is not a capability id` };
244
- const moduleDir = join(home, ".oats", "modules", capability);
272
+ const trust = providerHomeTrust(home);
273
+ const moduleDir = runDirOf(home, capability, trust);
274
+ const gone = () => `capability ${capability}, which supplies this home's session backend ${name}, is not among the home's modules (${moduleDir}); respawn the instance from a deployment that composes it`;
275
+ // (A capability an upgrade removed: the receipt records no copy of it any more.)
276
+ if (trust?.composition && !recordsModule(trust, capability)) return { problem: gone() };
277
+ const untrusted = moduleCopyProblem(home, capability, trust);
278
+ if (untrusted) return { problem: untrusted };
245
279
  let manifest;
246
280
  try { manifest = parseStrictJson(readFileSync(join(moduleDir, "oats.json")), WIRE_LIMITS); }
247
- catch (e) { return { problem: e?.code === "ENOENT" ? `capability ${capability}, which supplies this home's session backend ${name}, is not among the home's modules (${moduleDir}); respawn the instance from a deployment that composes it` : `the manifest of capability ${capability} in ${moduleDir} cannot be read (${safeText(e?.message ?? e, 200)})` }; }
281
+ catch (e) { return { problem: e?.code === "ENOENT" ? gone() : `the manifest of capability ${capability} in ${moduleDir} cannot be read (${safeText(e?.message ?? e, 200)})` }; }
248
282
  if (!isObject(manifest) || manifest.capability !== capability) return { problem: `${join(moduleDir, "oats.json")} is not the manifest of capability ${capability}` };
249
283
  const { providers, problems } = sessionProvidersOf(manifest);
250
284
  const provider = Object.hasOwn(providers, name) ? providers[name] : null;
@@ -252,10 +286,15 @@ export function homeSessionProvider(home, meta, capability, name) {
252
286
  const broken = problems.find((p) => p.provider === name || p.provider === null);
253
287
  return { problem: safeText(broken ? `capability ${capability} declares session provider ${name} malformed: ${broken.message} (at ${broken.pointer})` : `capability ${capability} no longer declares session provider ${name}`, 1000) };
254
288
  }
255
- const row = (Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : []).find((c) => c?.id === capability);
256
- const settings = isObject(row?.settings) ? row.settings : isObject(meta?.providers?.[capability]) ? meta.providers[capability] : {};
289
+ const row = capabilityRuntimeOf(home, meta, trust).find((c) => c?.id === capability);
290
+ // (`providers`: what a home from before `capabilityRuntime` recorded; never read for a provider home.)
291
+ const settings = isObject(row?.settings) ? row.settings : !trust && isObject(meta?.providers?.[capability]) ? meta.providers[capability] : {};
257
292
  const cap = { id: capability, layer: row?.layer ?? manifest.layer ?? "", level: row?.level ?? "", settings, settingsOrigins: isObject(row?.settingsOrigins) ? row.settingsOrigins : {} };
258
- const digest = typeof meta?.modules?.[capability]?.digest === "string" ? meta.modules[capability].digest : null;
293
+ // (`digest`: what tells two homes' copies of a provider apart, for one inspectMany call. For a
294
+ // provider home, whose own record is not read: the module's source, and with none recorded the
295
+ // store of the kernel's copy, which is this home's alone.)
296
+ const source = trust ? trust.composition.modules[capability] : null;
297
+ const digest = trust ? (source.from || source.commit ? canonicalJson(source) : `store:${trust.composition.store}`) : typeof meta?.modules?.[capability]?.digest === "string" ? meta.modules[capability].digest : null;
259
298
  return { binding: { home, meta: meta ?? {}, capability, name, provider, moduleDir, cap, digest } };
260
299
  }
261
300
 
@@ -271,11 +310,12 @@ function moduleExecutable(dir, script) {
271
310
 
272
311
  /** The environment a provider's command runs with in its home: a lifecycle hook's (lib/hook-env.mjs),
273
312
  * as the home's launch hooks get it, with OATS_EVENT=session and OATS_BACKEND. */
274
- function providerEnvironment({ home, meta, cap, name }) {
313
+ function providerEnvironment({ home, meta, cap, name, soulId }) {
275
314
  const workspace = isObject(meta.workspace) ? meta.workspace : null;
276
315
  return lifecycleHookEnv("session", cap, {
277
316
  home, instance: typeof meta.instance === "string" ? meta.instance : basename(home), agentName: typeof meta.agent === "string" ? meta.agent : "",
278
- soulDir: instanceSoulDir(home, meta), contextDir: home, rootDir: dirname(dirname(dirname(home))),
317
+ // (`soulId`: a spawn's, for a call it makes before the home's record names its soul.)
318
+ soulDir: instanceSoulDir(home, meta), ...(typeof soulId === "string" && soulId ? { soulId } : {}), contextDir: home, rootDir: dirname(dirname(dirname(home))),
279
319
  resolved: { workspace, ...recordedTeams(meta), teamsSource: "recorded" },
280
320
  priorMeta: isObject(meta.capabilityMeta) ? meta.capabilityMeta : {},
281
321
  extraEnv: { OATS_BACKEND: name, ...(typeof meta.harness === "string" ? { OATS_HARNESS: meta.harness } : {}) },
@@ -305,11 +345,14 @@ export function callSessionProvider(binding, verb, input, { timeoutMs = sessionP
305
345
  // `binding.home` is null, with `binding.env`, for a soul's readiness check: no home exists yet.
306
346
  const { capability, name, provider, moduleDir, home } = binding;
307
347
  const said = `${capability}'s session provider ${name}`;
348
+ // A provider that speaks another wire is never called: every read of its session is unavailable.
349
+ const wire = wireRefusal(capability, provider);
350
+ if (wire) return { ok: false, failed: wire.message };
308
351
  const declared = provider.commands[verb];
309
352
  if (!declared) return { ok: false, failed: `${said} declares no ${verb} command` };
310
353
  const file = moduleExecutable(moduleDir, declared.script);
311
354
  if (!file) return { ok: false, failed: `${said}: the ${verb} command ${declared.command} (${declared.script}) is not a file inside ${home ? "the home's" : "this"} copy of ${capability}` };
312
- const request = { schemaVersion: 1, phase: "session", capability, provider: name, verb, input };
355
+ const request = { schemaVersion: 1, wire: SESSION_PROVIDER_WIRE, phase: "session", capability, provider: name, verb, input };
313
356
  let r;
314
357
  try {
315
358
  // (SIGTERM at the timeout: the group's leader answers it by ending the whole group, by SIGKILL.)
@@ -459,7 +502,8 @@ const codeMessages = (list) => Array.isArray(list) && list.every((x) => exactKey
459
502
  export function checkProviderSession(binding, input, { io, timeoutMs = sessionProviderTimeout("check") } = {}) {
460
503
  if (!binding.provider.commands.check) return null;
461
504
  const answer = callSessionProvider(binding, "check", input, { io, timeoutMs });
462
- if (!answer.ok) return { unavailable: providerSaid(answer) };
505
+ // (`timedOut`: it did not answer in the time it was given, which a preview counts against its budget.)
506
+ if (!answer.ok) return { unavailable: providerSaid(answer), ...(answer.timedOut ? { timedOut: true } : {}) };
463
507
  const r = answer.result;
464
508
  const sound = exactKeys(r, ["status", "problems"], ["warnings"]) && CHECK_STATUSES.includes(r.status) && codeMessages(r.problems) && (r.warnings === undefined || codeMessages(r.warnings)) && !(r.status === "ready" && r.problems.length);
465
509
  if (!sound) return { unavailable: `${binding.capability}'s session provider ${binding.name} answered check with a result that is not { status, problems, warnings? } in the readiness words` };
@@ -470,12 +514,17 @@ export function checkProviderSession(binding, input, { io, timeoutMs = sessionPr
470
514
  * the kernel asks a provider's readiness for the home right before every launch, so a launch is
471
515
  * never sent to a backend that says it cannot take it. `{ code, message }`: the first problem's
472
516
  * own code when it is an E_BACKEND_* one, else E_BACKEND_NOT_READY; the message carries every
473
- * problem the provider named, or why its readiness could not be read. */
474
- export function launchReadinessRefusal(binding, { io } = {}) {
475
- const checked = checkProviderSession(binding, { home: binding.home, soul: null, settings: binding.cap.settings }, { io });
517
+ * problem the provider named, or why its readiness could not be read. `launch`: the launch that
518
+ * is planned, `{ harness, yolo, args, sandbox }` as its launch input will carry them, so a provider
519
+ * can refuse HERE what it would refuse at the launch (a session it would sandbox whose allowances
520
+ * are `unavailable` or have `missing` entries: only it knows its mode), before a restart stops
521
+ * anything. `timeoutMs`: a preview's, what is left of its budget; the refusal of a provider that
522
+ * did not answer in time carries `timedOut`. */
523
+ export function launchReadinessRefusal(binding, { io, launch, timeoutMs } = {}) {
524
+ const checked = checkProviderSession(binding, { home: binding.home, soul: null, settings: binding.cap.settings, ...(launch ? { launch } : {}) }, { io, ...(timeoutMs === undefined ? {} : { timeoutMs }) });
476
525
  if (checked === null || checked.result?.status === "ready") return null;
477
526
  const said = `${binding.capability}'s session provider ${binding.name}`;
478
- if (checked.unavailable) return { code: "E_BACKEND_NOT_READY", message: `${said} is not ready: its readiness could not be read (${checked.unavailable})` };
527
+ if (checked.unavailable) return { code: "E_BACKEND_NOT_READY", message: `${said} is not ready: its readiness could not be read (${checked.unavailable})`, ...(checked.timedOut ? { timedOut: true } : {}) };
479
528
  const own = checked.result.problems.find((x) => /^E_BACKEND_[A-Z0-9_]{1,50}$/.test(x.code));
480
529
  return { code: own?.code ?? "E_BACKEND_NOT_READY", message: `${said} is not ready (${checked.result.status})${checked.result.problems.length ? `: ${checked.result.problems.map((x) => `${x.code}: ${x.message}`).join("; ")}` : ""}` };
481
530
  }
@@ -0,0 +1,93 @@
1
+ /** A home's independent receipt (its retirement baseline, which is also its session receipt): where
2
+ * it is kept, outside the home, and how a home is told from another. A leaf, with nothing of the
3
+ * kernel above it, so that whatever must read a receipt can (lib/session-inspect.mjs reads a
4
+ * home's session by it; lib/home-integrity.mjs reads what a provider home may run). */
5
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
6
+ import { basename, dirname, join } from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
9
+
10
+ /** A home's receipt, read and found to be this home's and of this kernel's version → the
11
+ * receipt, or undefined when there is none, it cannot be read, or it is another home's. */
12
+ export function homeReceipt(home) {
13
+ const baseline = readJsonOrUndefined(findRetirementBaseline(home));
14
+ return baseline?.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) ? baseline : undefined;
15
+ }
16
+ export function isPlainObject(v) { return !!v && typeof v === "object" && !Array.isArray(v); }
17
+ export function readJsonOrUndefined(path) { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return undefined; } }
18
+
19
+ // The stored digests are versioned apart (`digestVersion`, BASELINE_DIGEST_VERSION): this version
20
+ // also gates runtime, directory-home and provider-exclusion authority, so a bump would refuse them all.
21
+ export const RETIRE_BASELINE_VERSION = 2;
22
+
23
+ export function retirementStateRoot(home) {
24
+ // Independent of the bytes it authenticates, but colocated with the agent's
25
+ // already instance-owned storage rather than the source repository or user
26
+ // config home. Retiring <instances>/<name> never removes this sibling.
27
+ return instancesRetirementRoot(dirname(home));
28
+ }
29
+ /** The retirement state of the homes in the instances directory `instances`. */
30
+ export function instancesRetirementRoot(instances) {
31
+ return join(instances, ".oats-retirement");
32
+ }
33
+
34
+ /** A home's identity as a receipt records it: its on-disk spelling, own name included. A home that
35
+ * is a symlink is not followed: its parent's on-disk spelling and its name as given (a home
36
+ * exchanged for a symlink is not the home it points at). */
37
+ export function receiptHomeIdentity(home) {
38
+ let st;
39
+ try { st = lstatSync(home); } catch { /* not there: spelled as the nearest existing ancestor */ }
40
+ return st && !st.isSymbolicLink() ? canonicalHomePath(home) : join(canonicalHomePath(dirname(home)), basename(home));
41
+ }
42
+
43
+ /** Whether a receipt's recorded home is this home, whatever spelling either was written in.
44
+ * `current` is the home as the caller resolves it for the comparison. */
45
+ export function receiptRecordsHome(baseline, current) {
46
+ return typeof baseline?.home === "string" && receiptHomeIdentity(baseline.home) === current;
47
+ }
48
+
49
+ export function retirementBaselineFile(identity) {
50
+ return join(retirementStateRoot(identity), "baselines", `${createHash("sha256").update(identity).digest("hex")}.json`);
51
+ }
52
+
53
+ /** Where the kernel keeps its own copies of a provider home's modules (lib/home-integrity.mjs):
54
+ * beside the receipts, keyed as the home's receipt is. */
55
+ export function homeModulesStore(home) {
56
+ const identity = receiptHomeIdentity(home);
57
+ return join(retirementStateRoot(identity), "modules", createHash("sha256").update(identity).digest("hex"));
58
+ }
59
+
60
+ /** Where a spawn writes a home's receipt: keyed by its canonical identity. */
61
+ export function retirementBaselinePath(home) {
62
+ return retirementBaselineFile(receiptHomeIdentity(home));
63
+ }
64
+
65
+ /** Where a kernel before 0.49.0 wrote it: keyed by the parent's realpath in the spawn's own
66
+ * spelling, which on a case-insensitive filesystem need not be the on-disk one. */
67
+ export function legacyRetirementBaselinePath(home) {
68
+ return retirementBaselineFile(join(realPathOrNearest(dirname(home)), basename(home)));
69
+ }
70
+
71
+ /** The receipt every reader uses: the canonical one if it exists, else one an earlier kernel left
72
+ * under this caller's spelling, else the canonical path (absent). Read-only: a receipt found at the
73
+ * legacy key is used where it is, never moved, copied or rewritten elsewhere.
74
+ *
75
+ * Limits. A legacy receipt written under spelling S is found only from S, or from the canonical
76
+ * spelling when that is S: a third spelling of such a home misses it (address the home as
77
+ * `oats status` prints it, the spawn's spelling). Receipts outlive retire, so a reused name can
78
+ * leave an earlier incarnation's receipt behind; the canonical one wins, which is right for every
79
+ * home spawned from 0.49.0 on. It is wrong in one case: two incarnations of the same name, both
80
+ * spawned by a kernel before 0.49.0 under different spellings, the earlier one under the canonical
81
+ * spelling. The later home then reads the earlier one's receipt. Its stale endpoint disagrees with
82
+ * instance.json (E_RUNTIME_AUTHORITY_MISMATCH) unless the later incarnation sits at the same
83
+ * endpoint, where session control already targets the right session. Retire finds the home
84
+ * fingerprint changed and preserves the home, less the stale receipt's disposable roots; a
85
+ * directory-work disagreement is E_WORK_INSPECTION_FAILED; and a start's record rewrites the stale
86
+ * file, as a kernel before 0.49.0 already does when a caller's spelling matches an earlier
87
+ * incarnation's. */
88
+ export function findRetirementBaseline(home) {
89
+ const canonical = retirementBaselinePath(home);
90
+ if (existsSync(canonical)) return canonical;
91
+ const legacy = legacyRetirementBaselinePath(home);
92
+ return legacy !== canonical && existsSync(legacy) ? legacy : canonical;
93
+ }
@@ -8,6 +8,7 @@ import { driftOf } from "./materialize.mjs";
8
8
  import { parseStrictJson } from "./canonical-json.mjs";
9
9
  import { readPortableBytes } from "./bounded-read.mjs";
10
10
  import { canonicalHomePath } from "./real-path.mjs";
11
+ import { providerHomeTrust } from "./home-integrity.mjs";
11
12
 
12
13
  export const UPGRADE_RECEIPT_NAME_RE = /^upgrade-receipt\.[A-Za-z0-9][A-Za-z0-9._:-]{0,127}\.json$/;
13
14
  const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -73,7 +74,11 @@ export function assertNoPartialUpgrade(home) {
73
74
  for (const { path, receipt } of readUpgradeReceipts(home)) {
74
75
  if (receipt.status !== "partial") continue;
75
76
  const { instance, command } = retryFor(home, receipt);
76
- throw Object.assign(oatsError("E_UPGRADE_PARTIAL", `the package upgrade of ${instance} is partial (${path}); nothing was stopped or started. Retry ${command} to finish it; if it cannot finish, respawn the instance`), {
77
+ // (A provider home's upgrade is not resumed, its journal being in the home: lib/instance-upgrade.mjs.)
78
+ const trust = providerHomeTrust(home);
79
+ // (With no composition in its receipt, the home's retire hooks cannot be identified: only --force removes it.)
80
+ const remedy = trust ? `${instance} is on a session provider, whose interrupted upgrade is not resumed: retire the instance (oats retire ${instance}${trust.problem ? " --force" : ""}) and spawn it again` : `Retry ${command} to finish it; if it cannot finish, respawn the instance`;
81
+ throw Object.assign(oatsError("E_UPGRADE_PARTIAL", `the package upgrade of ${instance} is partial (${path}); nothing was stopped or started. ${remedy}`), {
77
82
  details: { home, receipt: path, instance, idempotencyKey: receipt.idempotencyKey },
78
83
  });
79
84
  }
@@ -19,6 +19,8 @@ import { spawn as spawnProcess, execFileSync } from "node:child_process";
19
19
  import { closeSync, fchmodSync, mkdirSync, openSync, realpathSync, writeSync } from "node:fs";
20
20
  import { dirname, join } from "node:path";
21
21
  import { terminateGroup, watchGroup, TERM_GRACE_MS } from "./process-group.mjs";
22
+ import { moduleCopyProblem, providerHomeTrust, trustedCapability } from "./home-integrity.mjs";
23
+ import { PROVIDER_TREE_GIT } from "./instance-git.mjs";
22
24
  import { isStartToken, processLiveness, processStart, processStartToken } from "../packages/record/lib/process-identity.mjs";
23
25
 
24
26
  export { PS_ENV, isStartToken, processLiveness, processStart, processStartToken, runPs } from "../packages/record/lib/process-identity.mjs";
@@ -203,8 +205,20 @@ export async function runWorktreeHooks(hooks, { envFor, cwd, home, purpose, stre
203
205
  try {
204
206
  for (const hook of hooks) {
205
207
  if (guard?.signal) { out.interrupted = guard.signal; break; }
208
+ // A provider home's hook runs only from the kernel's own copy of its module, by the
209
+ // receipt's row for it (lib/home-integrity.mjs), whatever row and command the caller holds:
210
+ // with no such row or copy it is a failed required hook.
211
+ const trust = home ? providerHomeTrust(home) : null;
212
+ const trusted = trust ? trustedCapability(home, hook.cap ?? { id: hook.id }, trust) : null;
213
+ const untrusted = trust ? trusted.problem ?? (typeof trusted.cap.hooks?.worktree === "string" ? moduleCopyProblem(home, hook.id, trust) : `capability ${hook.id} has no worktree hook in the home's receipt`) : null;
214
+ if (untrusted) {
215
+ out.receipt.push({ capability: hook.id, ok: false, required: true, log: null });
216
+ out.failures.push({ capability: hook.id, event: "worktree", message: untrusted, required: true, integrity: true });
217
+ continue;
218
+ }
219
+ const run = trust ? { ...hook, command: trusted.cap.hooks.worktree, cap: trusted.cap } : hook;
206
220
  const log = worktreeHookLogPath(home, purpose, hook.id);
207
- const one = await runOne(hook, { env: envFor(hook.cap), cwd, log, sink, closed, guard, onStart, timeoutMs });
221
+ const one = await runOne(run, { env: envFor(run.cap), cwd, log, sink, closed, guard, onStart, timeoutMs });
208
222
  out.receipt.push({ capability: hook.id, ok: one.ok, required: hook.required, log, ...one.facts });
209
223
  out.warnings.push(...one.warnings);
210
224
  if (!one.ok) {
@@ -299,7 +313,9 @@ function runOne(hook, { env, cwd, log, sink, closed, guard, onStart, timeoutMs }
299
313
 
300
314
  // ---------- git facts about a tree and its clone ----------
301
315
 
302
- const gitOut = (argv) => { try { return execFileSync("git", argv, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 30_000 }).trim(); } catch { return null; } };
316
+ // (No hook and no file monitor of the repository: these reads may be of a provider home's tree,
317
+ // lib/instance-git.mjs PROVIDER_TREE_GIT; they read no index, so nothing changes for any home.)
318
+ const gitOut = (argv) => { try { return execFileSync("git", [...PROVIDER_TREE_GIT, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 30_000 }).trim(); } catch { return null; } };
303
319
 
304
320
  /** The clone's `origin` URL, scrubbed (scrubRemoteUrl); "" when it has no `origin`. */
305
321
  export function originRemoteOf(clone) {
package/lib/worktree.mjs CHANGED
@@ -33,7 +33,9 @@ import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
33
33
  import { terminateGroup, watchGroup } from "./process-group.mjs";
34
34
  import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
35
35
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
36
- import { NO_FILE_MONITOR, workTreeOverrides } from "./instance-git.mjs";
36
+ import { AsyncLocalStorage } from "node:async_hooks";
37
+ import { NO_FILE_MONITOR, PROVIDER_TREE_GIT, workTreeOverrides } from "./instance-git.mjs";
38
+ import { providerHomeTrust, trustedRecord } from "./home-integrity.mjs";
37
39
  import {
38
40
  cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
39
41
  refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
@@ -55,9 +57,17 @@ export function worktreeFetchTimeoutMs(env = process.env) {
55
57
  }
56
58
  /** The git environment of every step: the invoker's, never prompting for credentials. */
57
59
  const gitEnv = () => ({ ...process.env, GIT_TERMINAL_PROMPT: "0" });
60
+ /** The Git settings every command of one `oats worktree` verb runs with, for the home it acts
61
+ * on: PROVIDER_TREE_GIT for a home on a session provider (no hook, no file monitor), none for any
62
+ * other. Held for the verb's own calls (and what they await), so that no call site can leave them
63
+ * out, and two verbs in one process do not share them. */
64
+ const treeGit = new AsyncLocalStorage();
65
+ const treeGitFor = (home) => { try { return providerHomeTrust(home) ? PROVIDER_TREE_GIT : []; } catch { return []; } };
66
+ const withTreeGit = (home, verb) => treeGit.run(treeGitFor(home), verb);
67
+ const treeArgv = (argv) => [...(treeGit.getStore() ?? []), ...argv];
58
68
  /** Run git → { ok, out, err, status }. Never a shell. */
59
69
  function git(argv, { timeout = 120_000, env = {}, input } = {}) {
60
- const r = spawnSync("git", argv, { encoding: "utf8", stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, env: { ...gitEnv(), ...env }, timeout, maxBuffer: 64 * 1024 * 1024 });
70
+ const r = spawnSync("git", treeArgv(argv), { encoding: "utf8", stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, env: { ...gitEnv(), ...env }, timeout, maxBuffer: 64 * 1024 * 1024 });
61
71
  return { ok: r.status === 0 && !r.error, out: String(r.stdout ?? ""), err: String(r.stderr ?? "").trim() || r.error?.message || "", status: r.status };
62
72
  }
63
73
  /** Run a git step that changes something (a tree, a ref, the worktree list) as a recorded child:
@@ -74,7 +84,7 @@ export function trackedGit(argv, { track, timeout = 120_000 }) {
74
84
  return new Promise((resolve, fail) => {
75
85
  let child;
76
86
  try {
77
- child = spawnChild("/bin/sh", ["-c", 'read _ || exit 125; exec git "$@"', "oats-git", ...argv], { detached: true, stdio: ["pipe", "pipe", "pipe"], env: gitEnv() });
87
+ child = spawnChild("/bin/sh", ["-c", 'read _ || exit 125; exec git "$@"', "oats-git", ...treeArgv(argv)], { detached: true, stdio: ["pipe", "pipe", "pipe"], env: gitEnv() });
78
88
  } catch (e) { resolve({ ok: false, out: "", err: `git could not be started: ${e.message}`, status: null }); return; }
79
89
  watchGroup(child);
80
90
  let out = "", err = "", tracked = false, timedOut = false, settled = false;
@@ -174,7 +184,8 @@ export function readTreeHome(home) {
174
184
  // A retire in flight holds the home's lifecycle claim. Read, never taken: an add runs hooks for
175
185
  // minutes and has its purpose's claim.
176
186
  refuseBesideRetire("worktree add", home);
177
- return { home, meta };
187
+ // (A provider home's capability rows, its worktree hooks among them, are its receipt's: lib/home-integrity.mjs.)
188
+ return { home, meta: trustedRecord(meta, providerHomeTrust(home)) };
178
189
  }
179
190
 
180
191
  // ---------- the clone ----------
@@ -302,7 +313,8 @@ function addCreatedBranch(rec, tree) {
302
313
  * → { owed, warnings, branchDeleted, branchKept, branchKeptReason? }: `owed` is [] when all of
303
314
  * that is verified, else what is still owed (the record is then kept, so the next add or remove
304
315
  * tries again); a branch kept on purpose is not owed. `branchKept`: the branch exists afterwards. */
305
- export async function rollbackTree(home, rec, { track }) {
316
+ export function rollbackTree(home, rec, o) { return withTreeGit(home, () => rollbackTreeOf(home, rec, o)); }
317
+ async function rollbackTreeOf(home, rec, { track }) {
306
318
  const owed = [], warnings = [];
307
319
  const tree = extraTreePath(home, rec.purpose);
308
320
  const otherwise = leftoverRemedy(treeRecordPath(home, rec.purpose), tree, rec);
@@ -496,7 +508,8 @@ const publicReceipt = (rec, extra = {}) => ({
496
508
 
497
509
  /** `oats worktree add`. `o`: { purpose, branch, base, repo?, preview?, stream? }.
498
510
  * → the receipt ({ ..., resumed }) or, with preview, the plan. Throws typed errors. */
499
- export async function worktreeAdd(homeArg, o = {}) {
511
+ export function worktreeAdd(homeArg, o = {}) { return withTreeGit(homeArg, () => worktreeAddOf(homeArg, o)); }
512
+ async function worktreeAddOf(homeArg, o) {
500
513
  validateTreeArgs(o);
501
514
  const { home, meta } = readTreeHome(homeArg);
502
515
  const { purpose, branch, base } = o;
@@ -742,7 +755,8 @@ function removeWritableResidue(tree) {
742
755
  * nobody, and no flag removes anyway. An attached instance whose session is stopped does not
743
756
  * refuse: the tree is removed, and the answer's `warnings` name it, since its link then points at
744
757
  * a path that is gone. A tree that is already gone is removed under nobody: no one is looked at. */
745
- export async function worktreeRemove(homeArg, o = {}) {
758
+ export function worktreeRemove(homeArg, o = {}) { return withTreeGit(homeArg, () => worktreeRemoveOf(homeArg, o)); }
759
+ async function worktreeRemoveOf(homeArg, o) {
746
760
  validateTreeArgs(o, { forRemove: true });
747
761
  const home = homeArg;
748
762
  if (typeof home !== "string" || !isAbsolute(home) || !existsSync(join(home, "instance.json"))) throw badArgs("oats worktree runs from an instance home (in the home, or with $OATS_INSTANCE_HOME set to it)");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.69.24",
3
+ "version": "0.70.1",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",