@awebai/oats 0.69.24 → 0.70.0

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.
package/lib/core.mjs CHANGED
@@ -59,6 +59,8 @@ import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, claimUnheld, claimWrite,
59
59
  import { captureLoginEnvironment } from "./login-environment.mjs";
60
60
  import { kernelNode } from "./stable-node.mjs";
61
61
  import { instanceSoulDir, kernelBin, lifecycleHookEnv, stableSoulId, teamEnv } from "./hook-env.mjs";
62
+ import { capabilityRuntimeOf, compositionOf, homeModulesProblem, kernelModuleDir, moduleCopyProblem, moduleCopyReport, providerHomeTrust, removeModulesStore, trustedCapability, trustedRecord } from "./home-integrity.mjs";
63
+ import { homeReceipt, legacyRetirementBaselinePath } from "./session-receipt.mjs";
62
64
  import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
63
65
 
64
66
  import { refuseHomeOfAnotherUser } from "./home-owner.mjs";
@@ -93,21 +95,22 @@ import { readPortableBytes } from "./bounded-read.mjs";
93
95
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
94
96
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
95
97
  import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
96
- import { assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
98
+ import { PROVIDER_TREE_GIT, assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
97
99
  import { retireGitReadsNoWorkTreeFile, retireSubcommandAt } from "./retire-git-forms.mjs";
98
100
  import { systemTool } from "./system-tools.mjs";
99
101
  import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
100
102
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
101
103
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
102
104
  import { PIN_FILE } from "./instance-pin.mjs";
105
+ import { SESSION_PROVIDER_ANY, launchSentOf, unsettledLaunchSaid, sessionProviderTimeout, recordsSessionProvider, launchReadinessRefusal, homeSessionProvider, inputProviderSession, inputWasRefused, sameEndpoint, inspectProviderSession, launchProviderSession, providerRuntimeRecord, selectSessionBackend, stopProviderSession, wireRefusal } from "./session-providers.mjs";
103
106
  import { dieAt } from "./provider-test-seams.mjs";
104
- import { SESSION_PROVIDER_ANY, launchSentOf, unsettledLaunchSaid, sessionProviderTimeout, recordsSessionProvider, launchReadinessRefusal, homeSessionProvider, inputProviderSession, inputWasRefused, sameEndpoint, inspectProviderSession, launchProviderSession, providerRuntimeRecord, selectSessionBackend, stopProviderSession } from "./session-providers.mjs";
105
107
  import { BOARD_FILE, BOARD_LOCK } from "./instance-board.mjs";
106
108
  import { RELATED_WORK_FILE, SAME_WORK_FILE, relatedWorkBinding, writeRelatedWork } from "./instance-related-work.mjs";
107
109
  import { HOST_STOP_REASON, lostReasonOf, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
108
110
  import { PROVIDER_RESUME_NOTICE, RESUME_QUIET_WAIT_MS, countProviderResume, resumeCountLock, resumeQuietWait } from "./provider-resume.mjs";
109
111
  import { withDirLock } from "./dir-lock.mjs";
110
112
  import { waitingHold } from "./instance-events.mjs";
113
+ import { ensureSandboxWritePaths, homeSandboxAllowances, sandboxAllowances, sandboxEventsDir, sandboxLaunchInput, sandboxWritePathsRefusal } from "./sandbox-allowances.mjs";
111
114
  import { thisBoot } from "./session-seen.mjs";
112
115
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
113
116
  import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
@@ -696,6 +699,20 @@ export function capabilityManifests(startDir) {
696
699
  if (m) add(m);
697
700
  return out;
698
701
  }
702
+ // A provider home's modules are the ones its receipt records, read from the KERNEL's copies of
703
+ // them, outside the home (lib/home-integrity.mjs): what the home's own record or its own copies
704
+ // say is not read (nor needed: a home whose `.oats/modules` or whose record of them is gone is
705
+ // read the same), and a module its record adds is no capability of it.
706
+ const providerHome = enclosingHome(startDir);
707
+ const trust = providerHome ? providerHomeTrust(providerHome) : null;
708
+ if (trust) {
709
+ for (const [name, rec] of Object.entries(trust.composition?.modules ?? {})) {
710
+ if (!PACKAGE_ID_RE.test(name) || name === "__proto__") continue;
711
+ const m = loadManifestAt(kernelModuleDir(providerHome, name, trust), `module:${providerHome}`);
712
+ if (m) { m._module = rec; add(m); }
713
+ }
714
+ return out;
715
+ }
699
716
  const modulesOf = instanceModulesRoot(startDir);
700
717
  if (modulesOf) {
701
718
  for (const [name, rec] of Object.entries(modulesOf.modules)) {
@@ -707,6 +724,19 @@ export function capabilityManifests(startDir) {
707
724
  }
708
725
  return out;
709
726
  }
727
+ /** The instance home `dir` is, or is inside: the nearest directory, `dir` included, that holds
728
+ * an instance.json (as instanceModulesRoot walks); null when there is none. */
729
+ function enclosingHome(dir) {
730
+ if (!dir) return null;
731
+ let cur = resolve(dir);
732
+ for (let i = 0; i < 6; i++) {
733
+ if (existsSync(join(cur, "instance.json"))) return cur;
734
+ const parent = dirname(cur);
735
+ if (parent === cur) break;
736
+ cur = parent;
737
+ }
738
+ return null;
739
+ }
710
740
  export function capabilityManifest(name, startDir) {
711
741
  return capabilityManifests(startDir)[name];
712
742
  }
@@ -911,7 +941,8 @@ export function resolvedFromHome(home, meta, { teams, defaultTeam, teamsSource }
911
941
  const messaging = (Array.isArray(meta?.capabilities) ? meta.capabilities : []).find((c) => c?.layer === "messaging")?.id ?? null;
912
942
  const t = Array.isArray(teams) ? { teams, defaultTeam: defaultTeam ?? null, teamsSource: teamsSource === "live" ? "live" : "recorded" } : { ...recordedTeams(meta), teamsSource: "recorded" };
913
943
  return {
914
- capabilities: Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : [],
944
+ // (A provider home's rows are its receipt's: lib/home-integrity.mjs.)
945
+ capabilities: capabilityRuntimeOf(home, meta),
915
946
  workspace: ws ? { ...ws, slots: { messaging } } : null,
916
947
  payloads: meta?.providers ?? {},
917
948
  ...t,
@@ -1393,10 +1424,17 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1393
1424
  // retire) gets the directory the home's spawn recorded.
1394
1425
  if (!soulDir && home) soulDir = instanceSoulDir(home);
1395
1426
  const envOwners = new Map();
1396
- const envDeclarations = new Map((resolved.capabilities || []).map((cap) => [cap.id, { names: new Set(cap.environment || []), namespaces: [...(cap.environmentNamespaces || [])] }]));
1397
- const caps = [...(resolved.capabilities || [])];
1427
+ // A provider home (lib/home-integrity.mjs): whatever rows the caller holds, each capability's
1428
+ // settings, hook commands and declarations are its receipt's, and the commands name the
1429
+ // kernel's own copy of the module, never the home's. A capability the receipt does not record,
1430
+ // or whose kernel copy is gone, is a failed required hook, which names the module: a launch is
1431
+ // refused, a retire goes on to the other capabilities' hooks and reports this one as not run.
1432
+ const trust = home ? providerHomeTrust(home) : null;
1433
+ const trusted = (resolved.capabilities || []).map((cap) => trustedCapability(home, cap, trust));
1434
+ const envDeclarations = new Map(trusted.map(({ cap }) => [cap.id, { names: new Set(cap.environment || []), namespaces: [...(cap.environmentNamespaces || [])] }]));
1435
+ const caps = [...trusted];
1398
1436
  if (event === "retire") caps.reverse();
1399
- for (const cap of caps) {
1437
+ for (const { cap, problem } of caps) {
1400
1438
  for (const miss of cap.missingRequires || []) {
1401
1439
  results.warnings.push(`${cap.id}${cap.layer ? ` (${cap.layer})` : ""}: required command "${miss.command}" not on PATH — ${miss.why || "needed by this capability"}${miss.install ? ` (install: ${miss.install})` : ""}`);
1402
1440
  }
@@ -1410,6 +1448,13 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1410
1448
  if (finished.get(cap.id) !== undefined) results.meta[cap.id] = finished.get(cap.id);
1411
1449
  continue;
1412
1450
  }
1451
+ const untrusted = trust ? problem ?? moduleCopyProblem(home, cap.id, trust) : null;
1452
+ if (untrusted) {
1453
+ results.warnings.push(`${cap.id} ${event} hook was NOT run: ${untrusted}`);
1454
+ results.failures.push({ capability: cap.id, event, message: untrusted, required: true, integrity: true });
1455
+ if (event === "spawn") return results;
1456
+ continue;
1457
+ }
1413
1458
  assertRoots?.();
1414
1459
  results.order.push(cap.id);
1415
1460
  if (event === "spawn" || event === "launch") results.dialogClaims[cap.id] = null;
@@ -1783,7 +1828,7 @@ const INSTANCE_IDENTITY_ENV = ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME
1783
1828
  const KERNEL_ENV_NAMES = new Set([...RESERVED_LAUNCH_ENV, "COLORFGBG", "TMUX", "TMUX_PANE",
1784
1829
  "OATS_CAPABILITY", "OATS_LAYER", "OATS_LEVEL", "OATS_META", "OATS_DEPLOYMENT", "OATS_RESOLUTION", "OATS_OPERATION",
1785
1830
  "OATS_REPO", "OATS_BRANCH", "OATS_WORK", "OATS_KIND", "OATS_TASK", "OATS_HARNESS", "OATS_PREVIOUS_HARNESS", "OATS_RUNTIME", "OATS_PREVIOUS_RUNTIME",
1786
- "OATS_BACKEND", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1831
+ "OATS_BACKEND", "OATS_PREVIOUS_BACKEND", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1787
1832
  "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_TEAMS", "OATS_TEAMS_SOURCE",
1788
1833
  "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY",
1789
1834
  // A worktree hook's tree (#796): never inherited by what such a hook starts.
@@ -3087,13 +3132,15 @@ function requirementsWithArgsMessage(harness, providers, config, backend = "tmux
3087
3132
  * collects every failed check into `preflight` instead of throwing. Launch
3088
3133
  * hooks of capabilities declaring `launchPreview` run here only as a preview
3089
3134
  * (OATS_LAUNCH_PREVIEW=1); the others run here for real when a start plans,
3090
- * and not at all for a preview. A home
3135
+ * and not at all for a preview. `noHooks` (with `preview`): no launch hook runs at all, the
3136
+ * recorded contributions stand for every capability: what a start asks its session provider's
3137
+ * readiness with, before any hook (the selection: harness, yolo, the configuration's arguments). A home
3091
3138
  * that records no launch recipe (an earlier kernel spawned it) is not planned:
3092
3139
  * E_LAUNCH_LEGACY, re-spawn it from the deployment. `pane`: the environment the launch's pane is
3093
3140
  * expected to have (paneEnvironment's shape, or a function giving it, called only when a check
3094
3141
  * needs a name the launch itself does not set); every check here reads it through the one answer
3095
3142
  * (launchEnvironment), and says so when it is not established. */
3096
- export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, assertRoots, reselect = null, pane }) {
3143
+ export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, noHooks = false, assertRoots, reselect = null, pane }) {
3097
3144
  assertRoots?.();
3098
3145
  const problems = [];
3099
3146
  const fail = (check, code, detail) => { if (!preview) throw oatsError(code, detail); problems.push({ check, ok: false, detail, code }); };
@@ -3168,7 +3215,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3168
3215
  // too (it runs them for real once its preflight passed); the others run
3169
3216
  // here for real on a start, and not at all for a preview.
3170
3217
  try {
3171
- hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: preview ? "preview" : "plan" });
3218
+ hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: noHooks ? "none" : preview ? "preview" : "plan" });
3172
3219
  const current = new Map((resolvedCfg?.capabilities || []).map((c) => [c.id, c]));
3173
3220
  const untrusted = hooks.contributions.filter((c) => c.capability && current.has(c.capability) && !current.get(c.capability).trust?.trusted).map((c) => c.capability);
3174
3221
  const inactive = hooks.contributions.filter((c) => c.capability && !current.has(c.capability)).map((c) => c.capability);
@@ -3342,7 +3389,32 @@ export function describeLaunchCommand(command) {
3342
3389
  * arguments for the harness; never the kernel's own flags, which are `model`, `yolo` and the
3343
3390
  * prompt (`promptFile`, the home's TASK.md). `previous`: the endpoint of the session this launch
3344
3391
  * replaces (a start, a restart), null for a home's first launch. */
3345
- function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null }) {
3392
+ /** The trees of a home, as a provider's launch (and its check) is handed them: `<home>/work`,
3393
+ * always and first, then every extra tree of the home by its name. An extra tree is what Git
3394
+ * itself says is one (extraWorktreesOf: a `.work-*` directory that is a registered linked
3395
+ * worktree of a repository outside the home), read with the kernel's hardened Git; nothing of
3396
+ * the home's own record (instance.json) names a tree. Absolute paths.
3397
+ *
3398
+ * A provider that sandboxes its harness keeps each tree's Git pointer, configuration and hooks
3399
+ * unwritable. A limit, for such a provider to know: the list of a repository's worktrees is in
3400
+ * its common Git directory, which a session that can write there can shorten; a tree taken off
3401
+ * that list is no longer sent. `<home>/work` always is. */
3402
+ function homeTrees(home) {
3403
+ return [join(home, "work"), ...extraWorktreesOf(home).map((tree) => tree.path)];
3404
+ }
3405
+ /** The kernel's own state for a home, as a provider's launch (and its check) is handed it:
3406
+ * directories a sandboxed agent must never write, and that a provider must not block reading or
3407
+ * executing. One entry: `<instances>/.oats-retirement/`, which holds the kernel's copies of the
3408
+ * home's modules (lib/home-integrity.mjs: what the kernel runs, and where the home's hooks point
3409
+ * the harness), the receipts, the claims and the provider calls in flight. Each is made here
3410
+ * when it is missing (a deployment's first home), so that a provider that refuses a launch for
3411
+ * a missing one refuses a fault and never a first launch. Never derived from the home's record. */
3412
+ function homeProtected(home) {
3413
+ const paths = [instancesRetirementRoot(dirname(canonicalHomePath(home)))];
3414
+ for (const path of paths) mkdirSync(path, { recursive: true, mode: 0o700 });
3415
+ return paths;
3416
+ }
3417
+ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null, sandbox }) {
3346
3418
  const env = [{ name: "OATS_INSTANCE", value: instance, source: "kernel" }, { name: "OATS_INSTANCE_HOME", value: home, source: "kernel" }];
3347
3419
  const hookEnv = recipe.hooks?.env || {};
3348
3420
  const owner = (name) => (recipe.hooks?.contributions || []).find((c) => (c.env || []).includes(name))?.capability ?? null;
@@ -3370,8 +3442,28 @@ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [
3370
3442
  home, instance, harness: recipe.harness, model: recipe.model ?? null, yolo: recipe.yolo ?? null,
3371
3443
  env, unset: [...removed], pathPrepend: [kernelShimDir(home)],
3372
3444
  args: [...(recipe.args || []), ...hookWords], promptFile: join(home, "TASK.md"), previous,
3445
+ // What the provider may widen its harness's sandbox by, and nothing else (lib/sandbox-allowances.mjs).
3446
+ ...(sandbox ? { sandbox } : {}),
3447
+ // The home's trees (homeTrees): what a provider that sandboxes protects the Git files of.
3448
+ trees: homeTrees(home),
3449
+ // The kernel's own state (homeProtected): never written by a sandboxed agent.
3450
+ protected: homeProtected(home),
3373
3451
  };
3374
3452
  }
3453
+ /** A home's record of its capabilities' runtime (`capabilityRuntime`), one row per capability of
3454
+ * the spawn's resolution. */
3455
+ const capabilityRuntimeRows = (resolvedCfg) => resolvedCfg.capabilities.map((cap) => ({
3456
+ id: cap.id, layer: cap.layer, level: cap.level, settings: cap.settings, settingsOrigins: cap.settingsOrigins ?? {},
3457
+ hooks: cap.hooks, requiredHooks: cap.requiredHooks, environment: cap.environment, environmentNamespaces: cap.environmentNamespaces,
3458
+ missingRequires: cap.missingRequires, trust: cap.trust,
3459
+ executable: cap.executable,
3460
+ }));
3461
+ /** The launch that is planned, as a provider's `check` is handed it BEFORE any hook runs:
3462
+ * `{ harness, yolo, args, sandbox, trees, protected }`. `args` are the launch configuration's own: the
3463
+ * arguments a capability's hooks contribute are not known yet, and reach the launch input only.
3464
+ * `trees` and `protected` are the launch input's (homeTrees, homeProtected): a provider that
3465
+ * would refuse a launch for either refuses it here, before a restart stops anything. */
3466
+ const plannedLaunch = ({ home, harness, yolo, args, sandbox }) => ({ harness, yolo: yolo ?? null, args: [...(args || [])], ...(sandbox ? { sandbox } : {}), trees: homeTrees(home), protected: homeProtected(home) });
3375
3467
  /** A home's independent session receipt, read to be written again with another `runtime` → `{ path,
3376
3468
  * baseline }`. Refused as every writer of it refuses: E_RUNTIME_ENDPOINT_UNKNOWN for a receipt that
3377
3469
  * is missing, unreadable, of another home, or that authorises nothing. */
@@ -3769,6 +3861,29 @@ function* spawnBody(root, agent, o = {}) {
3769
3861
  provider = selected.backend === "tmux" ? null : selected;
3770
3862
  if (provider && launchConfig?.executable) throw Object.assign(oatsError("E_BACKEND_LAUNCH_ARG", `launch configuration ${launchConfig.name} declares an executable (${launchConfig.executable}), and session backend ${backend} runs the harness itself: no executable can be handed to it; use a configuration without one; nothing was created`), { details: { backend, launchConfig: launchConfig.name, field: "executable" } });
3771
3863
  } catch (e) { previewPreflightBudget = null; throw e; }
3864
+ // The Git settings of this spawn's own tree: for a home on a session provider, no hook and no
3865
+ // file monitor of the repository (lib/instance-git.mjs PROVIDER_TREE_GIT); none for a tmux home.
3866
+ const treeGit = provider ? PROVIDER_TREE_GIT : [];
3867
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
3868
+ // deployment's own resolution: refused here, before anything is created, when a capability
3869
+ // asks for a host it may not ask for. A tmux launch has none.
3870
+ let sandbox = null;
3871
+ if (provider) {
3872
+ try {
3873
+ const deployment = o.prepared.deployment || workspaceOf(root), eventsDir = sandboxEventsDir(deployment);
3874
+ sandbox = sandboxAllowances({
3875
+ modules: (o.prepared.resolution?.modules || []).map((m) => ({ name: m.name, manifest: m.manifest })),
3876
+ slots: o.prepared.resolution?.slots ?? {}, payloads: o.prepared.resolution?.payloads ?? {}, origins: o.prepared.resolution?.payloadOrigins ?? {},
3877
+ teams: (o.prepared.resolution?.teams ?? []).map((row) => row.team).filter((team) => typeof team === "string"),
3878
+ defaultTeam: typeof o.prepared.resolution?.defaultTeam?.team === "string" ? o.prepared.resolution.defaultTeam.team : null,
3879
+ eventsDir, deployment, outside: [root, eventsDir],
3880
+ });
3881
+ // The paths it names exist, and are what they must be, before anything of the spawn is
3882
+ // created. A preview creates nothing, and refuses what the apply would refuse of them.
3883
+ if (o.preview !== true) ensureSandboxWritePaths(sandbox.write);
3884
+ else { const refused = sandboxWritePathsRefusal(sandbox.write); if (refused) throw refused; }
3885
+ } catch (e) { previewPreflightBudget = null; throw e; }
3886
+ }
3772
3887
  // Instance homes belong in the soul-owning repo's PRIMARY checkout, never in a
3773
3888
  // linked worktree (see canonicalDeploymentPath). The CLI resolves this through
3774
3889
  // ensureRoot, but the kernel is its own validation boundary — the desktop
@@ -4322,6 +4437,9 @@ function* spawnBody(root, agent, o = {}) {
4322
4437
  // A session provider is one of the instance's own modules: there to launch. Whether its
4323
4438
  // service is ready is its readiness check's answer (`oats readiness`), not this field's.
4324
4439
  backendStatus: launch ? { name: backend, installed: provider ? true : !!which(backend), started: false } : null,
4440
+ // What a session provider may widen its harness's sandbox by: each host with the capability
4441
+ // and the setting that asked for it, each path with its reason. Absent for tmux.
4442
+ ...(sandbox ? { sandbox } : {}),
4325
4443
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4326
4444
  background, ...(backgroundFrom ? { backgroundFrom } : {}),
4327
4445
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
@@ -4361,6 +4479,7 @@ function* spawnBody(root, agent, o = {}) {
4361
4479
  if (e?.code === "EEXIST") throw Object.assign(oatsError("E_PLACEMENT_TAKEN", `${instance} already exists at ${home} (a concurrent spawn won the placement); nothing was created by this call`), { instance, home });
4362
4480
  throw e;
4363
4481
  }
4482
+ removeStaleReceipt(home);
4364
4483
  const createdHomeIdentity = directoryIdentity(home);
4365
4484
  // Names are deployment-wide, but the reservation above is per soul: a concurrent
4366
4485
  // spawn of ANOTHER soul under the same name reserves its own directory. Re-check
@@ -4612,7 +4731,8 @@ function* spawnBody(root, agent, o = {}) {
4612
4731
  }
4613
4732
  let added = false;
4614
4733
  try {
4615
- execFileSync("git", [...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4734
+ // (A provider home's tree: no hook of the repository runs, here or in the rollback: PROVIDER_TREE_GIT.)
4735
+ execFileSync("git", [...treeGit, ...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4616
4736
  { stdio: ["ignore", "pipe", "pipe"] });
4617
4737
  added = true;
4618
4738
  // Git registers a canonical path. Retain it now: compensation hooks can
@@ -4626,7 +4746,7 @@ function* spawnBody(root, agent, o = {}) {
4626
4746
  // Capture every failure and verify Git effects; because canonical
4627
4747
  // identity was unavailable, never claim confirmed worktree absence.
4628
4748
  const run = (argv) => {
4629
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4749
+ try { return { ok: true, out: execFileSync(argv[0], [...treeGit, ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4630
4750
  // With encoding:"utf8" a silent command yields stderr === "" — FALSY — so
4631
4751
  // `e2.stderr || e2.message` fell through to "Command failed: …" and made
4632
4752
  // every clean probe look like a failed one. `git rev-parse --verify
@@ -4644,7 +4764,7 @@ function* spawnBody(root, agent, o = {}) {
4644
4764
  else incomplete.push(`git worktree ${wt}: could not verify removal (canonical path unavailable after add)`);
4645
4765
  incomplete.push(...deleteBranchAsCreated(run, repoAbs, branch, plannedBase.oid));
4646
4766
  }
4647
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4767
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4648
4768
  const note = incomplete.length ? ` — rollback INCOMPLETE — clean up manually: ${incomplete.join("; ")}` : "";
4649
4769
  const error = new Error(`git worktree add/canonicalization failed: ${original}${note}`);
4650
4770
  throw incomplete.length ? unconfirmedSpawn(error) : error;
@@ -4684,6 +4804,13 @@ function* spawnBody(root, agent, o = {}) {
4684
4804
  // (A provider home's names its provider from the first: a spawn killed after its planned record
4685
4805
  // then leaves a receipt that agrees with it.)
4686
4806
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: { backend, provider: provider.capability } } : { launched: false });
4807
+ } else if (provider) {
4808
+ // A provider home, in every other work mode too: its receipt, and with it the kernel's own
4809
+ // copies of its modules (lib/home-integrity.mjs), are made HERE, before the provider's check
4810
+ // and before any hook of the spawn. So the spawn's own hooks run from the kernel's copies as
4811
+ // every later hook does, and a path one of them hands the harness is the kernel's. (The
4812
+ // spawn writes the receipt again later, with what it then knows; the composition is kept.)
4813
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: { backend, provider: provider.capability } });
4687
4814
  }
4688
4815
 
4689
4816
  // Capability lifecycle hooks (spawn) — the knowledge integration scaffolds instance
@@ -4750,6 +4877,28 @@ function* spawnBody(root, agent, o = {}) {
4750
4877
  rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4751
4878
  inProgressMarker = false;
4752
4879
  };
4880
+ // The provider's own readiness, with the launch that is planned, BEFORE any hook runs: a launch a
4881
+ // backend says it cannot take (one it would sandbox, without what it needs) is refused with no
4882
+ // hook run, so nothing a hook registers outside the home has to be undone. It needs nothing a
4883
+ // hook produces: the harness, yolo and the allowances are the plan's, and the arguments are the
4884
+ // launch configuration's own (a hook's reach the launch input, not this).
4885
+ let refusedBeforeHooks = null;
4886
+ if (launch && provider) {
4887
+ // (The record is not written yet: the binding is made from what it will hold of the soul, the
4888
+ // capabilities' rows and the workspace, so this call has the environment every later one has.)
4889
+ const planned = { agent: agent.name, instance, home, soulDir: homeSoulTarget, harness, capabilityRuntime: capabilityRuntimeRows(resolvedCfg), ...workspaceRecord };
4890
+ const bound = homeSessionProvider(home, planned, provider.capability, backend);
4891
+ if (bound.binding) bound.binding.soulId = preparedSoulId;
4892
+ const notReady = bound.problem ? null : launchReadinessRefusal(bound.binding, { launch: plannedLaunch({ home, harness, yolo, args: launchConfig?.args, sandbox: sandboxLaunchInput(sandbox) }) });
4893
+ if (bound.problem) refusedBeforeHooks = oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${bound.problem}`);
4894
+ else if (notReady) refusedBeforeHooks = Object.assign(oatsError(notReady.code, `${instance} was not launched: ${notReady.message}`), { details: { backend, capability: provider.capability } });
4895
+ }
4896
+ dieAt("spawn:hooks");
4897
+ if (refusedBeforeHooks) {
4898
+ // No hook runs for a spawn its backend refused: the spawn is undone below as one whose hooks
4899
+ // never ran (the home and its work are removed; nothing was registered outside them).
4900
+ hookRes = { meta: {}, briefs: [], warnings: [], order: [], launch: {}, env: {}, failures: [], contributions: [], volatileEnv: {}, dialogClaims: {} };
4901
+ } else {
4753
4902
  // Write-ahead: what a retire needs to run the retire hooks (the repository they come from, the
4754
4903
  // capabilities, the soul) is on disk before the first spawn hook runs. Until the final record
4755
4904
  // is written, instance.json is the stub lib/materialize.mjs wrote, which names none of it: a
@@ -4764,6 +4913,7 @@ function* spawnBody(root, agent, o = {}) {
4764
4913
  // name), also for a spawn that launches nothing: it is what a later start launches on.
4765
4914
  extraEnv: { OATS_TASK: task, OATS_REPO: repoAbs, OATS_BRANCH: branch || "", OATS_WORK: work, OATS_HARNESS: harness, OATS_BACKEND: backend, ...harnessExecutableHanded, OATS_RUNTIME: harness, OATS_KIND: agent.kind || "persistent", ...(triggerEventFile ? { OATS_TRIGGER_EVENT_FILE: triggerEventFile } : {}), ...(spawnedBy ? { OATS_SPAWNER_HOME: spawnedBy.home } : {}) },
4766
4915
  });
4916
+ }
4767
4917
  // The spawn hooks' receipt (their `meta`), on disk as soon as there is one: a retire after a kill
4768
4918
  // from here on hands it to the retire hooks.
4769
4919
  if (inProgressMarker) {
@@ -4826,7 +4976,7 @@ function* spawnBody(root, agent, o = {}) {
4826
4976
  : [{ capability: "oats.kernel", event: "spawn" }];
4827
4977
  const incomplete = [...ancillaryCleanup];
4828
4978
  const probe = (argv) => {
4829
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4979
+ try { return { ok: true, out: execFileSync(argv[0], [...(argv[0] === "git" ? treeGit : []), ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4830
4980
  // An absent ref exits 1 with empty stderr; preserve that distinction.
4831
4981
  catch (e2) { return { ok: false, status: e2.status, err: String(e2.stderr ?? e2.message ?? "").trim() }; }
4832
4982
  };
@@ -4906,6 +5056,8 @@ function* spawnBody(root, agent, o = {}) {
4906
5056
  home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete, failed, outstandingHooks, outstandingGit,
4907
5057
  repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {}, compensationMeta,
4908
5058
  launched: false, directoryPreservation: true, directoryHome: homeReal,
5059
+ // (A provider home stays one in its receipt: its composition is what its cleanup runs by.)
5060
+ ...(provider ? { session: { backend, provider: provider.capability } } : {}),
4909
5061
  recordRetirementBaseline: true,
4910
5062
  });
4911
5063
  return { unconfirmed: true, note: `${note}${directoryRecoveries.length ? `; prior work recovery: ${directoryRecoveries.join(", ")}` : ""}` };
@@ -4924,7 +5076,8 @@ function* spawnBody(root, agent, o = {}) {
4924
5076
  try { preserveDirectory(); }
4925
5077
  catch (e) { return retainDirectory(e); }
4926
5078
  try {
4927
- const comp = runLifecycleHooks("retire", {
5079
+ // (A spawn refused before any of its hooks ran has nothing for a retire hook to undo.)
5080
+ const comp = refusedBeforeHooks ? { failures: [], meta: {} } : runLifecycleHooks("retire", {
4928
5081
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4929
5082
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4930
5083
  priorMeta: hookRes.meta || {},
@@ -4988,7 +5141,7 @@ function* spawnBody(root, agent, o = {}) {
4988
5141
  directoryHome: homeReal, recordRetirementBaseline: true,
4989
5142
  });
4990
5143
  } else {
4991
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
5144
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4992
5145
  if (existsSync(home) && !incomplete.some((m) => m.startsWith("instance home"))) incomplete.push(`instance home ${home}: still present`);
4993
5146
  note = incomplete.length ? ` — rollback INCOMPLETE, clean up manually: ${incomplete.join("; ")}` : " — spawn rolled back";
4994
5147
  }
@@ -4996,6 +5149,7 @@ function* spawnBody(root, agent, o = {}) {
4996
5149
  };
4997
5150
 
4998
5151
  try {
5152
+ if (refusedBeforeHooks) throw refusedBeforeHooks;
4999
5153
  if (requiredFailures.length) {
5000
5154
  const detail = requiredFailures.map((f) => ` ${f.capability} ${f.event} ${f.contract === "environment" ? "environment contract" : "hook (declared required)"}: ${f.message}`).join("\n");
5001
5155
  const code = requiredFailures.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED";
@@ -5190,12 +5344,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5190
5344
  skillAlias: { path: join(home, ".claude", "skills"), target: join("..", ".agents", "skills") },
5191
5345
  },
5192
5346
  },
5193
- capabilityRuntime: resolvedCfg.capabilities.map((cap) => ({
5194
- id: cap.id, layer: cap.layer, level: cap.level, settings: cap.settings, settingsOrigins: cap.settingsOrigins ?? {},
5195
- hooks: cap.hooks, requiredHooks: cap.requiredHooks, environment: cap.environment, environmentNamespaces: cap.environmentNamespaces,
5196
- missingRequires: cap.missingRequires, trust: cap.trust,
5197
- executable: cap.executable,
5198
- })),
5347
+ capabilityRuntime: capabilityRuntimeRows(resolvedCfg),
5199
5348
  // The session's endpoint, as the receipt authorises it: tmux's planned names, or a session
5200
5349
  // provider's backend and capability (its endpoint is the provider's answer to the launch).
5201
5350
  ...(provider ? { backend, session: { provider: provider.capability, endpoint: null } } : { tmux: { session, window: instance } }),
@@ -5234,11 +5383,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5234
5383
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession });
5235
5384
  const found = homeSessionProvider(home, meta, provider.capability, backend);
5236
5385
  if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${found.problem}`);
5237
- const input = providerLaunchInput({ home, instance, recipe, env: process.env, removed: removedEnv, previous: null });
5238
- // The provider's own readiness first, where it declares one: a launch is never sent to a
5239
- // backend that says it cannot take it.
5240
- const notReady = launchReadinessRefusal(found.binding);
5241
- if (notReady) throw Object.assign(oatsError(notReady.code, `${instance} was not launched: ${notReady.message}`), { details: { backend, capability: provider.capability } });
5386
+ // (The provider's readiness was asked before the spawn's hooks ran.)
5387
+ const input = providerLaunchInput({ home, instance, recipe, env: process.env, removed: removedEnv, previous: null, sandbox: sandboxLaunchInput(sandbox) });
5242
5388
  assertHostRunAdmission();
5243
5389
  // From here a session may exist: the spawn's compensation stops it before anything is removed.
5244
5390
  // And a spawn that ends here without doing so (killed, its host stopped) leaves its word in
@@ -6603,9 +6749,29 @@ export function rebaseUpgradeRetirementBaseline(home, { homeChangedSinceSpawn }
6603
6749
  writeJsonAtomic(path, { ...baseline, homeFingerprint }, 0o600);
6604
6750
  }
6605
6751
 
6752
+ /** A spawn's first act on the home it has just made: take away the receipt an earlier home left
6753
+ * at this path. A retire keeps a home's receipt, by the home's path, and a spawn writes its own
6754
+ * only later (in most work modes after its spawn hooks), so until then every reader of "this
6755
+ * home's receipt" would read the retired home's: its backend, and for a provider home its
6756
+ * composition, by which this spawn's hooks would be run. The home was made by this spawn a
6757
+ * moment ago (an exclusive mkdir), so whatever receipt is at its path is not its own. */
6758
+ function removeStaleReceipt(home) {
6759
+ for (const path of new Set([retirementBaselinePath(home), legacyRetirementBaselinePath(home)])) rmSync(path, { force: true });
6760
+ // (And the kernel's copies of that home's modules, by the same key.)
6761
+ removeModulesStore(home);
6762
+ }
6763
+
6606
6764
  /** Project transaction-owned temporary files out of this baseline only. Later
6607
6765
  * fingerprints still hold them: a stale mutex is work to preserve, not invisible state. */
6608
6766
  export function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding, transientHomePaths = [] } = {}) {
6767
+ // A receipt that names a session provider is never rewritten as one that names none: a caller
6768
+ // that hands no session (a rollback that knows only that nothing is launched) keeps the home's
6769
+ // backend and provider, and with them its composition. Without them the home would read as a
6770
+ // tmux home, whose own copies and own record the kernel runs.
6771
+ const standing = homeReceipt(home)?.runtime;
6772
+ if (!runtime?.session && isPlainObject(standing) && typeof standing.provider === "string" && typeof standing.backend === "string") {
6773
+ runtime = { launched: false, session: { backend: standing.backend, provider: standing.provider } };
6774
+ }
6609
6775
  const transientFiles = retirementTransientFiles(home, transientHomePaths);
6610
6776
  if (mode === "directory") assertDirectoryRoots(home);
6611
6777
  const isWorktree = mode === "worktree";
@@ -6622,6 +6788,15 @@ export function writeRetirementBaseline(home, work, mode, capabilities, runtime,
6622
6788
  disposableReceipts,
6623
6789
  disposableHome,
6624
6790
  generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
6791
+ // A provider home's composition (lib/home-integrity.mjs): the store that holds the kernel's
6792
+ // own copies of the home's modules, made here from the copies this spawn materialised, and
6793
+ // the capability rows it resolved from the deployment. For such a home the kernel runs its
6794
+ // own copy of a module, and reads a capability's settings and hook commands from this record,
6795
+ // never from the home. A kernel from before it ignores the key.
6796
+ // Taken ONCE: a receipt that holds one keeps it (a spawn's later writes, its rollback's, a
6797
+ // retire's quarantine), so nothing is copied again from a home its agent could have written. The spawn removed any receipt an earlier home left at this path
6798
+ // (removeStaleReceipt), so the one found here is this home's own.
6799
+ ...(runtime?.session ? { composition: providerHomeTrust(home)?.composition ?? compositionOf(home, capabilityRuntimeRows({ capabilities })) } : {}),
6625
6800
  // `runtime.session`: a home on a session provider (lib/session-providers.mjs): its backend and the
6626
6801
  // capability that supplies it, and once launched the endpoint and whether OATS stopped it.
6627
6802
  runtime: runtime?.session
@@ -6832,6 +7007,7 @@ function stopSessionClaimed(home, o) {
6832
7007
  // A launch that was sent to the home's provider and never recorded: the provider stops whatever
6833
7008
  // it started before anything else is answered. Never "not launched" while that is not known.
6834
7009
  const sent = s.unsettled;
7010
+ if (sent) refuseOtherWire(realHome, s.meta, sent, "stopped", "nothing was stopped");
6835
7011
  if (sent && s.session) {
6836
7012
  // A home launched before: the one stop rule first (stopProviderHome: `stoppedAt` and the stop
6837
7013
  // receipt before the provider is called, the recorded session stopped, a host's stop
@@ -6909,6 +7085,17 @@ function stopProviderSessionRecorded(home, meta, session, { withHost = false, gr
6909
7085
  const unconfirmed = providerStopUnconfirmed(home, meta, session, session.endpoint, graceMs, io, null, { outlasted });
6910
7086
  return { unconfirmed, waitedMs: Date.now() - started };
6911
7087
  }
7088
+ /** A home whose provider speaks another wire than this kernel is refused by name, E_BACKEND_WIRE,
7089
+ * before a verb records or asks anything: a start, a stop (the host's too) and an input. Its
7090
+ * sessions read unavailable and are never recorded as stopped by a provider that was not asked.
7091
+ * (A retire keeps its own rule: it cannot ask that provider, and goes on when no process works in
7092
+ * the home, with the warning that names the provider's own tooling.) `recorded`: `{ backend,
7093
+ * provider }`; `what`: the verb's participle; `nothing`: what did not happen. */
7094
+ function refuseOtherWire(home, meta, recorded, what, nothing) {
7095
+ const found = homeSessionProvider(home, meta, recorded.provider, recorded.backend);
7096
+ const wire = found.problem ? null : wireRefusal(recorded.provider, found.binding.provider);
7097
+ if (wire) throw Object.assign(oatsError(wire.code, `${meta.instance || basename(home)} was not ${what}: ${wire.message}; ${nothing}`), { details: wire.details });
7098
+ }
6912
7099
  /** The stop of a home on a session provider (lib/session-providers.mjs), under the home's claim.
6913
7100
  * Kernel-owned: the receipt records `stoppedAt` BEFORE the provider is called, so from that
6914
7101
  * instant inspect answers stopped and input is refused, whatever the provider then does; a start
@@ -6924,6 +7111,8 @@ function stopProviderHome(realHome, s, o) {
6924
7111
  const { backend, stoppedAt } = s.session;
6925
7112
  const withHost = o.withHost === true;
6926
7113
  const idle = { home: s.home, backend, stopped: false, alreadyIdle: true, state: "stopped", receipt: null };
7114
+ // (The host's shutdown asks nothing of a home that is stopped already: it has no provider to refuse.)
7115
+ if (!(stoppedAt !== null && withHost)) refuseOtherWire(realHome, s.meta, s.session, "stopped", "nothing was stopped");
6927
7116
  if (stoppedAt !== null) {
6928
7117
  // The host's shutdown changes nothing of a home that is stopped already.
6929
7118
  if (withHost) return idle;
@@ -7029,6 +7218,9 @@ function inputProviderHome(s, text) {
7029
7218
  if (s.unsettled) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${unsettledLaunchSaid(name, backend, s.unsettled.launchSent)}; nothing was sent`);
7030
7219
  const found = homeSessionProvider(s.home, s.meta, provider, backend);
7031
7220
  if (found.problem) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${found.problem}`);
7221
+ // A provider that speaks another wire is never called: refused by name (refuseOtherWire's rule).
7222
+ const wire = wireRefusal(provider, found.binding.provider);
7223
+ if (wire) throw Object.assign(oatsError(wire.code, `${name} was not sent the input: ${wire.message}; nothing was sent`), { details: wire.details });
7032
7224
  const inspected = inspectProviderSession(found.binding, endpoint);
7033
7225
  if (inspected.unavailable) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: whether ${name}'s session is there could not be established (${inspected.unavailable}); nothing was sent`);
7034
7226
  const resume = inspected.observed.present ? null : resumeLostSession(s.home, name, { waitMs: 0 });
@@ -7084,7 +7276,7 @@ function inputProviderHome(s, text) {
7084
7276
  if (crossing) {
7085
7277
  // (Recorded as a call, as every stop is; no drain: an input does not wait for another.)
7086
7278
  const again = crossing.sameLocator ? null : trackedProviderStop(s.home, found.binding, endpoint, 20);
7087
- throw oatsError("E_SESSION_NOT_RUNNING", `${name} was ${crossing.what} by OATS while this input was being sent${again ? `; its ${backend} session was asked to stop again${again.failed ? `, which it did not confirm (${again.failed}): stop it with oats instance stop ${name}` : ""}` : ""}, and the input is not delivered`);
7279
+ throw oatsError("E_SESSION_NOT_RUNNING", `${name} was ${crossing.what} by OATS while this input was being sent${again ? `; its ${backend} session was asked to stop again${again.failed ? `, which it did not confirm (${again.failed}): stop it in the stop's two steps (oats instance stop ${name} --plan, then --apply --plan-revision <rev> --idempotency-key <key>, which the plan prints)` : ""}` : ""}, and the input is not delivered`);
7088
7280
  }
7089
7281
  if (failure) throw failure;
7090
7282
  // No endpoint here: it is on inspect, spawn and start answers only.
@@ -7396,6 +7588,16 @@ export function capturedProviders(meta, frozen) {
7396
7588
  /** The session backend a home launches on, as its record says: a session provider's name, else tmux.
7397
7589
  * A launch hook's OATS_BACKEND (a spawn hook's is the spawn's own choice). */
7398
7590
  const homeBackendOf = (meta) => (recordsSessionProvider(meta) ? meta.backend : "tmux");
7591
+ /** The backend a home was last launched on, as the kernel recorded it OUTSIDE the home (its session
7592
+ * receipt): a session provider's name, or `tmux`; undefined for a home that was never launched,
7593
+ * and for one whose receipt is missing or says nothing this kernel reads. Never the home's own
7594
+ * record (instance.json), which the home's agent can write. A launch hook's OATS_PREVIOUS_BACKEND:
7595
+ * a capability that wrote files of its own for one backend reads here whether they are its to
7596
+ * remove, and removes nothing when the variable is absent. */
7597
+ function previousBackendOf(home) {
7598
+ const authority = runtimeAuthorityOf(homeReceipt(home));
7599
+ return authority?.session ? authority.session.backend : authority?.tmux ? "tmux" : undefined;
7600
+ }
7399
7601
  /** Capability contributions for a start of an existing home: the recorded
7400
7602
  * ones, refreshed by any capability that declares a `launch` hook (asked
7401
7603
  * for the target harness; spawn hooks are never re-run). A harness change
@@ -7441,13 +7643,15 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
7441
7643
  }
7442
7644
  const aware = withLaunchHook.filter((c) => c.manifest.launchPreview === true);
7443
7645
  const unaware = withLaunchHook.filter((c) => c.manifest.launchPreview !== true);
7444
- const runs = (pass === "real" ? [[aware, false]] : pass === "preview" ? [[aware, true]] : [[unaware, false], [aware, true]]).filter(([caps]) => caps.length);
7445
- const notRun = pass === "preview" ? unaware.map((c) => c.id) : [];
7646
+ // (`none`: no hook runs, whether it previews or not; every recorded contribution stands.)
7647
+ const runs = (pass === "none" ? [] : pass === "real" ? [[aware, false]] : pass === "preview" ? [[aware, true]] : [[unaware, false], [aware, true]]).filter(([caps]) => caps.length);
7648
+ const notRun = pass === "none" ? withLaunchHook.map((c) => c.id) : pass === "preview" ? unaware.map((c) => c.id) : [];
7446
7649
  const previewed = runs.filter(([, asPreview]) => asPreview).flatMap(([caps]) => caps.map((c) => c.id));
7447
7650
  const volatileEnv = [];
7448
7651
  let hookDialogClaims;
7449
7652
  if (runs.length) {
7450
- const results = runs.map(([caps, asPreview]) => ({ asPreview, res: runLifecycleHooks("launch", { assertRoots, home, instance: meta.instance, agentName: meta.agent, soulDir: instanceSoulDir(home, meta), contextDir: ctx, rootDir: dirname(dirname(dirname(home))), resolved: { ...(resolvedCfg || {}), capabilities: caps }, priorMeta: meta.capabilityMeta || {}, extraEnv: { OATS_HARNESS: harness, OATS_PREVIOUS_HARNESS: frozen.harness || "", OATS_RUNTIME: harness, OATS_PREVIOUS_RUNTIME: frozen.harness || "", OATS_BACKEND: homeBackendOf(meta), ...(asPreview ? { OATS_LAUNCH_PREVIEW: "1" } : {}), ...extraEnv } }) }));
7653
+ const previousBackend = previousBackendOf(home);
7654
+ const results = runs.map(([caps, asPreview]) => ({ asPreview, res: runLifecycleHooks("launch", { assertRoots, home, instance: meta.instance, agentName: meta.agent, soulDir: instanceSoulDir(home, meta), contextDir: ctx, rootDir: dirname(dirname(dirname(home))), resolved: { ...(resolvedCfg || {}), capabilities: caps }, priorMeta: meta.capabilityMeta || {}, extraEnv: { OATS_HARNESS: harness, OATS_PREVIOUS_HARNESS: frozen.harness || "", OATS_RUNTIME: harness, OATS_PREVIOUS_RUNTIME: frozen.harness || "", OATS_BACKEND: homeBackendOf(meta), ...(previousBackend ? { OATS_PREVIOUS_BACKEND: previousBackend } : {}), ...(asPreview ? { OATS_LAUNCH_PREVIEW: "1" } : {}), ...extraEnv } }) }));
7451
7655
  const failed = results.flatMap(({ res }) => res.failures || []).map((f) => `${f.capability}: ${f.message}`);
7452
7656
  if (failed.length) throw oatsError("E_LAUNCH_PREPARATION", `a capability could not prepare the ${harness} launch:\n ${failed.join("\n ")}`);
7453
7657
  const fresh = results.flatMap(({ res }) => res.contributions || []);
@@ -7832,7 +8036,8 @@ function startSession(home, o) {
7832
8036
  const receipt = instanceSessionTarget(realHome);
7833
8037
  const meta = readMeta();
7834
8038
  // A home on a session provider has no window, pane or pending receipt: its start is its own.
7835
- if (providerHomeOf(receipt)) return startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, cleanupWarnings });
8039
+ // (Its capability rows are its receipt's, never its own record's: lib/home-integrity.mjs.)
8040
+ if (providerHomeOf(receipt)) return startProviderSession(realHome, o, { receipt, meta: trustedRecord(meta, providerHomeTrust(realHome)), checkRoots, drift, cleanupWarnings });
7836
8041
  const harness = meta.harness;
7837
8042
  if (!["pi", "claude", "codex"].includes(harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${meta.instance || realHome} records harness ${JSON.stringify(harness)}, which this kernel cannot relaunch`);
7838
8043
  let command = meta.command;
@@ -8272,6 +8477,9 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8272
8477
  const session = receipt.session ?? null;
8273
8478
  const name = meta.instance || basename(realHome);
8274
8479
  if (!LAUNCH_HARNESSES.includes(meta.harness)) throw oatsError("E_LAUNCH_COMMAND_UNSUPPORTED", `instance ${name} records harness ${JSON.stringify(meta.harness)}, which this kernel cannot relaunch`);
8480
+ // 0. A provider that speaks another wire than this kernel is never called: refused by name,
8481
+ // before its session is read, resumed, stopped or launched.
8482
+ refuseOtherWire(realHome, meta, { backend, provider }, "started", "nothing was stopped or started");
8275
8483
  if (o.resume === true) {
8276
8484
  // A launch that was sent and never recorded, on a home launched before or not: unknown, nothing is resumed.
8277
8485
  if (receipt.unsettled) throw oatsError("E_SESSION_UNKNOWN", `${unsettledLaunchSaid(name, backend, receipt.unsettled.launchSent)}; nothing was resumed`);
@@ -8289,7 +8497,7 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8289
8497
  if (inspected.observed.present) {
8290
8498
  if (!o.restart) {
8291
8499
  if (inspected.observed.running === true) throw oatsError("E_SESSION_RUNNING", `${name} is running (${inspected.observed.state}); nothing was started`);
8292
- throw oatsError("E_SESSION_UNKNOWN", `${name} has a session on ${backend} that OATS did not stop, and whether it runs cannot be told (${inspected.observed.state}); nothing was started. Stop it first (oats instance stop ${name}), or use oats session restart --home ${realHome}`);
8500
+ throw oatsError("E_SESSION_UNKNOWN", `${name} has a session on ${backend} that OATS did not stop, and whether it runs cannot be told (${inspected.observed.state}); nothing was started. Stop it first, in the stop's two steps (oats instance stop ${name} --plan, then --apply --plan-revision <rev> --idempotency-key <key>, which the plan prints), or use oats session restart --home ${realHome}`);
8293
8501
  }
8294
8502
  replaced = true;
8295
8503
  }
@@ -8300,7 +8508,51 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8300
8508
  let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
8301
8509
  const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
8302
8510
  if (reselect?.needsOffered && o.launchConfig === undefined && o.harness === undefined) throw oatsError("E_BAD_ARGS", `--reselect-launch of ${name} needs a read of the workspace's souls: oats-local.yaml souls.launch holds a key besides "*" and this home's soul has no entry of its own (the caller passes that read as launchOffered: lib/instance-resolution.mjs homeSoulsOffered)`);
8303
- const plan = planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots, pane: NO_PANE });
8511
+ // 1a. The provider's own readiness, with the launch that is planned, BEFORE any launch hook runs
8512
+ // and before anything is stopped: a restart never trades a session that runs for a backend that
8513
+ // says it cannot launch one, and a refused start runs no hook. What it is asked with is the
8514
+ // SELECTION, which needs no hook: the harness, yolo and the launch configuration's own
8515
+ // arguments (a hook's arguments reach the launch input, not this), taken from a plan made with no
8516
+ // hook run at all. It is asked whatever else that plan says (its preflight reads the recorded
8517
+ // contributions, which the real plan refreshes), and, should that plan give no selection, right
8518
+ // after the real one: a launch is never sent, nor a session stopped, with the check not asked.
8519
+ const planOf = (how = {}) => planLaunch({ home: realHome, instance: meta.instance, meta, contextDir: context, agentLike: agent || { harness: meta.harness, model: meta.model, yolo: meta.yolo }, selection: { launchConfig: o.launchConfig, harness: o.harness, model: o.model, yolo: o.yolo }, reselect, resolvedCfg, env: o.env || process.env, assertRoots: checkRoots, pane: NO_PANE, ...how });
8520
+ // The kernel holds its copy of every module of the home (lib/home-integrity.mjs), before any of
8521
+ // their manifests is read for the plan: a launch is made of all of them.
8522
+ const untrusted = homeModulesProblem(realHome);
8523
+ if (untrusted) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${untrusted}; nothing was stopped or started`);
8524
+ const bound0 = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8525
+ if (bound0.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${bound0.problem}`);
8526
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
8527
+ // deployment's configuration as it is now, which an async caller resolved (`o.sandboxSource`:
8528
+ // lib/instance-resolution.mjs homeSandboxSource, which takes the deployment and the soul from
8529
+ // where this home is, never from what is in it). Only for capabilities that are also this
8530
+ // home's modules: the rest are named, and add nothing. Refused here (E_BACKEND_SANDBOX_HOST),
8531
+ // before any hook runs and before anything is stopped.
8532
+ let sandbox, sandboxAnswer;
8533
+ const sandboxWarnings = [];
8534
+ if (!o.sandboxSource || o.sandboxSource.unavailable) sandbox = { unavailable: o.sandboxSource?.unavailable ?? "this start did not resolve the deployment's configuration" };
8535
+ else {
8536
+ const allowed = homeSandboxAllowances({ source: o.sandboxSource, home: realHome, moduleNames: Object.keys(isPlainObject(meta.modules) ? meta.modules : {}) });
8537
+ sandboxAnswer = allowed;
8538
+ for (const { capability, reason } of allowed.skipped ?? []) sandboxWarnings.push(`sandbox allowances: ${capability} adds no host: ${reason}`);
8539
+ sandbox = sandboxLaunchInput(allowed);
8540
+ // The paths it names exist, and are what they must be, before anything is stopped.
8541
+ ensureSandboxWritePaths(sandbox.write);
8542
+ }
8543
+ let checkAsked = false;
8544
+ const askCheck = (planned) => {
8545
+ checkAsked = true;
8546
+ const notReady = launchReadinessRefusal(bound0.binding, { io: o.io, launch: plannedLaunch({ home: realHome, harness: planned.harness, yolo: planned.recipe.yolo, args: planned.recipe.args, sandbox }) });
8547
+ if (notReady) throw Object.assign(oatsError(notReady.code, `${name} was not started: ${notReady.message}; nothing was stopped or started`), { details: { backend, capability: provider } });
8548
+ };
8549
+ {
8550
+ let selected = null;
8551
+ try { selected = planOf({ preview: true, noHooks: true }); } catch { /* the real plan, below, says what this could not plan */ }
8552
+ if (selected?.recipe) askCheck(selected);
8553
+ }
8554
+ const plan = planOf();
8555
+ if (!checkAsked) askCheck(plan);
8304
8556
  let recipe = plan.recipe, hookMeta = plan.hookMeta, hookDialogClaims = plan.hookDialogClaims;
8305
8557
  let warnings = [...plan.warnings];
8306
8558
  for (const message of plan.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
@@ -8317,13 +8569,11 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8317
8569
  }
8318
8570
  const removed = removedLaunchEnv({ declared: plan.declaredEnv, hooksEnv: recipe.hooks?.env, configEnv: recipe.env });
8319
8571
  if (kernelNode().warning) warnings.push(kernelNode().warning);
8572
+ // (The binding after the launch hooks: what they left of the home's module copy is what launches.)
8320
8573
  const found = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8321
8574
  if (found.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${found.problem}`);
8322
- const input = providerLaunchInput({ home: realHome, instance: meta.instance, recipe, env: o.env || process.env, removed, previous: session?.endpoint ?? null });
8323
- // The provider's own readiness, before anything is stopped: a restart never trades a session
8324
- // that runs for a backend that says it cannot launch one.
8325
- const notReady = launchReadinessRefusal(found.binding, { io: o.io });
8326
- if (notReady) throw Object.assign(oatsError(notReady.code, `${name} was not started: ${notReady.message}; nothing was stopped or started`), { details: { backend, capability: provider } });
8575
+ for (const message of sandboxWarnings) { warnings.push(message); appendEvent(realHome, { kind: "launch-warning", data: { message } }); }
8576
+ const input = providerLaunchInput({ home: realHome, instance: meta.instance, recipe, env: o.env || process.env, removed, previous: session?.endpoint ?? null, sandbox });
8327
8577
  checkRoots();
8328
8578
  // 2. A launch that an earlier spawn or start sent and never recorded (launchSentOf): settled
8329
8579
  // first. The provider stops whatever that launch started, and the home is then planned, or
@@ -8411,7 +8661,12 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8411
8661
  if (!outcomeRecordFailures.has(e)) throw unrecorded(e);
8412
8662
  throw oatsError("E_SESSION_START_INCOMPLETE", `${name} was started on ${backend} and its receipt records the session, but the rest of its outcome could not be recorded: ${e.message}; its launch stays marked as sent, so the home reads as unknown: a stop or a start settles it (the backend is asked to stop that session first)`); }
8413
8663
  // `target` is a tmux session's: null here, so a reader of a start's answer finds every key it knows.
8414
- return { ...answerBase(), harness: next.harness, backend, model: plan.model ?? null, launchConfig: recipe.launchConfig ?? null, yolo: next.yolo ?? null, target: null, session: { provider, endpoint: answered.endpoint }, startedAt, restartCount: next.restartCount, reused: "new", warnings: [...cleanupWarnings, ...warnings], ...(stop ? { stop } : {}) };
8664
+ // (`moduleCopy`, as the home's status row carries it: which copy of its modules ran, and whether
8665
+ // the home's own record of them is the receipt's. The home's record is read as a row reads it
8666
+ // (readHomeRecord: a regular file only), since the session that could exchange it now runs.)
8667
+ let startedModuleCopy;
8668
+ try { startedModuleCopy = moduleCopyReport(readHomeRecord(realHome).meta, providerHomeTrust(realHome)); } catch { startedModuleCopy = undefined; }
8669
+ return { ...answerBase(), harness: next.harness, backend, model: plan.model ?? null, launchConfig: recipe.launchConfig ?? null, yolo: next.yolo ?? null, target: null, sandbox: sandboxAnswer ?? sandbox, ...(startedModuleCopy ? { moduleCopy: startedModuleCopy } : {}), session: { provider, endpoint: answered.endpoint }, startedAt, restartCount: next.restartCount, reused: "new", warnings: [...cleanupWarnings, ...warnings], ...(stop ? { stop } : {}) };
8415
8670
  }
8416
8671
  /** `session start --resume` of a home on a session provider, and what the machine sweep runs for it
8417
8672
  * (lib/session-resume.mjs): the session continues in its own conversation, through the provider's
@@ -11740,6 +11995,8 @@ function retireSteps(root, name, o, found, at) {
11740
11995
  at.lead = () => `${name}: the directory at ${found.home} could not be removed`;
11741
11996
  rmSync(found.home, { recursive: true, force: true });
11742
11997
  at.lead = () => `${name}: its home was removed, and a file the retire leaves beside it could not be`;
11998
+ // (The kernel's own copies of a provider home's modules go with the home.)
11999
+ removeModulesStore(found.home);
11743
12000
  rmSync(directoryFallbackPath, { force: true });
11744
12001
  // The owed retirement is paid: clear the pending marker, and the failed
11745
12002
  // outcome an earlier deferred attempt may have left beside the home; a