@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
package/lib/core.mjs CHANGED
@@ -59,15 +59,50 @@ 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";
65
67
  import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isDefect, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
66
68
  import { envRows, recordedTeams } from "./teams.mjs";
69
+ import { safeText } from "./refused-text.mjs";
67
70
  import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
68
71
  import { shq, shellWord } from "./shell-word.mjs";
69
72
  import { CONFIG_DIR_VAR, HARNESS_FOLDER_VAR, claudeTrusts, codexTrustsRoot, harnessConfigFile, harnessTrustWarning, launchConfigFolder } from "./harness-trust.mjs";
70
73
  async function materializePreparedDefault(prepared, home) { const m = await import("./instance-resolution.mjs"); return m.materializePrepared(prepared, home); }
74
+ /** What a home's record says of the workspace and the teams, from the prepared resolution: the
75
+ * final record's, the spawn-in-progress marker's, and a preview's question to a session provider. */
76
+ const workspaceRecordOf = (prepared) => (prepared ? {
77
+ workspace: { key: prepared.discovery?.key ?? null, name: prepared.discovery?.workspace?.name ?? null, deployment: prepared.deployment ?? null, commit: prepared.discovery?.commit ?? null, resolution: prepared.resolution.revision, standalone: prepared.discovery?.standalone === true, soul: { id: preparedSoulIdOf(prepared.soulEntry), repoKey: prepared.soulEntry.repoKey, commit: prepared.soulEntry.commit, ...(typeof prepared.soulEntry.package === "string" ? { name: prepared.soulEntry.name, qualifiedName: prepared.soulEntry.qualifiedName, package: { id: prepared.soulEntry.package, version: prepared.soulEntry.version, commit: prepared.soulEntry.commit, digest: prepared.soulEntry.digest, path: prepared.soulEntry.path } } : {}) }, layers: layerRows(prepared.resolution) },
78
+ teams: envRows(prepared.resolution.teams ?? []),
79
+ defaultTeam: structuredClone(prepared.resolution.defaultTeam ?? null),
80
+ } : {});
81
+ /** The soul directory a home records and its hooks and provider calls are handed (OATS_SOUL): for
82
+ * a workspace soul its commit's directory in the per-commit cache, by real path, never the
83
+ * swappable `agents/<name>/soul` pointer; else what that pointer shows now; else `soulDir`.
84
+ * `planned` (a spawn's preview, which may have read the soul from a temporary copy): the
85
+ * per-commit directory the apply will record, though it is not fetched there yet. */
86
+ function homeSoulTargetOf(agent, prepared, soulDir, { planned = false } = {}) {
87
+ if (prepared?.soulEntry?.commit) {
88
+ const perCommit = join(agent._dir, "souls", String(prepared.soulEntry.commit).slice(0, 12));
89
+ if (existsSync(join(perCommit, "soul.yaml"))) return realpathSync(perCommit);
90
+ if (planned) return realPathOrNearest(perCommit);
91
+ }
92
+ // Not prepared (or the cache entry is absent): still never link a swappable pointer —
93
+ // when agents/<name>/soul is the kernel's pointer into souls/, link what it shows now.
94
+ try {
95
+ if (lstatSync(soulDir).isSymbolicLink()) {
96
+ const real = realpathSync(soulDir), soulsReal = realpathSync(join(dirname(soulDir), "souls"));
97
+ const rel = relative(soulsReal, real);
98
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel) && !rel.includes(sep)) return real;
99
+ }
100
+ } catch { /* absent souls/ or unreadable link: record the soul dir itself */ }
101
+ return soulDir;
102
+ }
103
+ /** The verified tree of a package module in the deployment's module store (lib/operator-dispatch.mjs
104
+ * ensureModuleTree), for a spawn preview's question to a session provider: no home holds it yet. */
105
+ async function providerTreeDefault(prepared, module) { const m = await import("./operator-dispatch.mjs"); return m.ensureModuleTree(prepared.deployment, module, prepared.lock, { remoteOptions: prepared.remoteOptions }); }
71
106
  async function plannedSkillsDefault(prepared) { const m = await import("./instance-resolution.mjs"); return m.plannedPreparedSkills(prepared); }
72
107
  // Capability rows for a PREPARED spawn (workspace model): the one function that
73
108
  // turns a Resolution's modules into the row shape hooks/environment/requirements/
@@ -93,21 +128,22 @@ import { readPortableBytes } from "./bounded-read.mjs";
93
128
  import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
94
129
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
95
130
  import { hashFile, readFilePieces, readFileUpTo } from "./file-pieces.mjs";
96
- import { assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
131
+ import { PROVIDER_TREE_GIT, assertSameWorktreeHead, filterOverrides, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, workTreeOverrides, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
97
132
  import { retireGitReadsNoWorkTreeFile, retireSubcommandAt } from "./retire-git-forms.mjs";
98
133
  import { systemTool } from "./system-tools.mjs";
99
134
  import { SCOPE_ENV_NAMES, agentScope, agentScopeArgv, agentScopeUnit, creatorPlacement, serverScopePlan, serverScopeUnit, serverScopeWarning } from "./tmux-server-scope.mjs";
100
135
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
101
136
  import { readInstanceBackground, writeInstanceBackground } from "./instance-background.mjs";
102
137
  import { PIN_FILE } from "./instance-pin.mjs";
138
+ import { SESSION_PROVIDER_ANY, launchSentOf, unsettledLaunchSaid, sessionProviderTimeout, recordsSessionProvider, launchReadinessRefusal, homeSessionProvider, inputProviderSession, inputWasRefused, sameEndpoint, inspectProviderSession, launchProviderSession, providerRuntimeRecord, selectSessionBackend, stopProviderSession, wireRefusal } from "./session-providers.mjs";
103
139
  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
140
  import { BOARD_FILE, BOARD_LOCK } from "./instance-board.mjs";
106
141
  import { RELATED_WORK_FILE, SAME_WORK_FILE, relatedWorkBinding, writeRelatedWork } from "./instance-related-work.mjs";
107
142
  import { HOST_STOP_REASON, lostReasonOf, readStartExited, sessionEndOf, START_EXITED_FILE, STOP_RECEIPT_FILE } from "./session-end.mjs";
108
143
  import { PROVIDER_RESUME_NOTICE, RESUME_QUIET_WAIT_MS, countProviderResume, resumeCountLock, resumeQuietWait } from "./provider-resume.mjs";
109
144
  import { withDirLock } from "./dir-lock.mjs";
110
145
  import { waitingHold } from "./instance-events.mjs";
146
+ import { ensureSandboxWritePaths, homeSandboxAllowances, sandboxAllowances, sandboxEventsDir, sandboxLaunchInput, sandboxWritePathsRefusal } from "./sandbox-allowances.mjs";
111
147
  import { thisBoot } from "./session-seen.mjs";
112
148
  import { FRESH_REASON, RESUME_WAITING, SESSION_END } from "./session-resume-contract.mjs";
113
149
  import { START_ENV_FILE, START_ENV_KEY_FILE, START_ENV_TMP, checkStartEnv, launchEnvChangedMessage, launchEnvMissingMessage, launchEnvUnverifiedWarning, recordStartEnv } from "./start-env.mjs";
@@ -696,6 +732,20 @@ export function capabilityManifests(startDir) {
696
732
  if (m) add(m);
697
733
  return out;
698
734
  }
735
+ // A provider home's modules are the ones its receipt records, read from the KERNEL's copies of
736
+ // them, outside the home (lib/home-integrity.mjs): what the home's own record or its own copies
737
+ // say is not read (nor needed: a home whose `.oats/modules` or whose record of them is gone is
738
+ // read the same), and a module its record adds is no capability of it.
739
+ const providerHome = enclosingHome(startDir);
740
+ const trust = providerHome ? providerHomeTrust(providerHome) : null;
741
+ if (trust) {
742
+ for (const [name, rec] of Object.entries(trust.composition?.modules ?? {})) {
743
+ if (!PACKAGE_ID_RE.test(name) || name === "__proto__") continue;
744
+ const m = loadManifestAt(kernelModuleDir(providerHome, name, trust), `module:${providerHome}`);
745
+ if (m) { m._module = rec; add(m); }
746
+ }
747
+ return out;
748
+ }
699
749
  const modulesOf = instanceModulesRoot(startDir);
700
750
  if (modulesOf) {
701
751
  for (const [name, rec] of Object.entries(modulesOf.modules)) {
@@ -707,6 +757,19 @@ export function capabilityManifests(startDir) {
707
757
  }
708
758
  return out;
709
759
  }
760
+ /** The instance home `dir` is, or is inside: the nearest directory, `dir` included, that holds
761
+ * an instance.json (as instanceModulesRoot walks); null when there is none. */
762
+ function enclosingHome(dir) {
763
+ if (!dir) return null;
764
+ let cur = resolve(dir);
765
+ for (let i = 0; i < 6; i++) {
766
+ if (existsSync(join(cur, "instance.json"))) return cur;
767
+ const parent = dirname(cur);
768
+ if (parent === cur) break;
769
+ cur = parent;
770
+ }
771
+ return null;
772
+ }
710
773
  export function capabilityManifest(name, startDir) {
711
774
  return capabilityManifests(startDir)[name];
712
775
  }
@@ -911,7 +974,8 @@ export function resolvedFromHome(home, meta, { teams, defaultTeam, teamsSource }
911
974
  const messaging = (Array.isArray(meta?.capabilities) ? meta.capabilities : []).find((c) => c?.layer === "messaging")?.id ?? null;
912
975
  const t = Array.isArray(teams) ? { teams, defaultTeam: defaultTeam ?? null, teamsSource: teamsSource === "live" ? "live" : "recorded" } : { ...recordedTeams(meta), teamsSource: "recorded" };
913
976
  return {
914
- capabilities: Array.isArray(meta?.capabilityRuntime) ? meta.capabilityRuntime : [],
977
+ // (A provider home's rows are its receipt's: lib/home-integrity.mjs.)
978
+ capabilities: capabilityRuntimeOf(home, meta),
915
979
  workspace: ws ? { ...ws, slots: { messaging } } : null,
916
980
  payloads: meta?.providers ?? {},
917
981
  ...t,
@@ -1393,10 +1457,17 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1393
1457
  // retire) gets the directory the home's spawn recorded.
1394
1458
  if (!soulDir && home) soulDir = instanceSoulDir(home);
1395
1459
  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 || [])];
1460
+ // A provider home (lib/home-integrity.mjs): whatever rows the caller holds, each capability's
1461
+ // settings, hook commands and declarations are its receipt's, and the commands name the
1462
+ // kernel's own copy of the module, never the home's. A capability the receipt does not record,
1463
+ // or whose kernel copy is gone, is a failed required hook, which names the module: a launch is
1464
+ // refused, a retire goes on to the other capabilities' hooks and reports this one as not run.
1465
+ const trust = home ? providerHomeTrust(home) : null;
1466
+ const trusted = (resolved.capabilities || []).map((cap) => trustedCapability(home, cap, trust));
1467
+ const envDeclarations = new Map(trusted.map(({ cap }) => [cap.id, { names: new Set(cap.environment || []), namespaces: [...(cap.environmentNamespaces || [])] }]));
1468
+ const caps = [...trusted];
1398
1469
  if (event === "retire") caps.reverse();
1399
- for (const cap of caps) {
1470
+ for (const { cap, problem } of caps) {
1400
1471
  for (const miss of cap.missingRequires || []) {
1401
1472
  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
1473
  }
@@ -1410,6 +1481,13 @@ export function runLifecycleHooks(event, { home, instance, agentName, soulDir, s
1410
1481
  if (finished.get(cap.id) !== undefined) results.meta[cap.id] = finished.get(cap.id);
1411
1482
  continue;
1412
1483
  }
1484
+ const untrusted = trust ? problem ?? moduleCopyProblem(home, cap.id, trust) : null;
1485
+ if (untrusted) {
1486
+ results.warnings.push(`${cap.id} ${event} hook was NOT run: ${untrusted}`);
1487
+ results.failures.push({ capability: cap.id, event, message: untrusted, required: true, integrity: true });
1488
+ if (event === "spawn") return results;
1489
+ continue;
1490
+ }
1413
1491
  assertRoots?.();
1414
1492
  results.order.push(cap.id);
1415
1493
  if (event === "spawn" || event === "launch") results.dialogClaims[cap.id] = null;
@@ -1783,7 +1861,7 @@ const INSTANCE_IDENTITY_ENV = ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME
1783
1861
  const KERNEL_ENV_NAMES = new Set([...RESERVED_LAUNCH_ENV, "COLORFGBG", "TMUX", "TMUX_PANE",
1784
1862
  "OATS_CAPABILITY", "OATS_LAYER", "OATS_LEVEL", "OATS_META", "OATS_DEPLOYMENT", "OATS_RESOLUTION", "OATS_OPERATION",
1785
1863
  "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",
1864
+ "OATS_BACKEND", "OATS_PREVIOUS_BACKEND", "OATS_LAUNCH_PREVIEW", "OATS_RETIRE_INTENT", "OATS_TRIGGER_EVENT_FILE",
1787
1865
  "OATS_TEAM_NAME", "OATS_TEAM_SCOPE", "OATS_TEAM_ID", "OATS_TEAM_LABEL", "OATS_TEAM_LABELS", "OATS_TEAMS", "OATS_TEAMS_SOURCE",
1788
1866
  "OATS_DEFAULT_TEAM", "OATS_DEFAULT_TEAM_ID", "OATS_DEFAULT_TEAM_FROM", "OATS_WORKSPACE_NAME", "OATS_WORKSPACE_KEY",
1789
1867
  // A worktree hook's tree (#796): never inherited by what such a hook starts.
@@ -3087,15 +3165,19 @@ function requirementsWithArgsMessage(harness, providers, config, backend = "tmux
3087
3165
  * collects every failed check into `preflight` instead of throwing. Launch
3088
3166
  * hooks of capabilities declaring `launchPreview` run here only as a preview
3089
3167
  * (OATS_LAUNCH_PREVIEW=1); the others run here for real when a start plans,
3090
- * and not at all for a preview. A home
3168
+ * and not at all for a preview. `noHooks` (with `preview`): no launch hook runs at all, the
3169
+ * recorded contributions stand for every capability: what a start asks its session provider's
3170
+ * readiness with, before any hook (the selection: harness, yolo, the configuration's arguments). A home
3091
3171
  * that records no launch recipe (an earlier kernel spawned it) is not planned:
3092
3172
  * E_LAUNCH_LEGACY, re-spawn it from the deployment. `pane`: the environment the launch's pane is
3093
3173
  * expected to have (paneEnvironment's shape, or a function giving it, called only when a check
3094
3174
  * needs a name the launch itself does not set); every check here reads it through the one answer
3095
3175
  * (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 }) {
3176
+ export function planLaunch({ home, instance, meta, contextDir, agentLike, selection = {}, launchConfigs, resolvedCfg, env = process.env, preview = false, noHooks = false, assertRoots, reselect = null, pane, providerCheck = null }) {
3097
3177
  assertRoots?.();
3098
3178
  const problems = [];
3179
+ // (The home's session provider as it is bound below, for the preview's question to it.)
3180
+ let providerBound = null;
3099
3181
  const fail = (check, code, detail) => { if (!preview) throw oatsError(code, detail); problems.push({ check, ok: false, detail, code }); };
3100
3182
  // A recorded recipe is validated before anything is observed. A home without
3101
3183
  // one predates recipes: there is nothing this kernel plans from.
@@ -3139,7 +3221,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3139
3221
  // The provider's own rules for this launch: the harness is one it runs, and no executable is named.
3140
3222
  // The home's modules as they are now, under the spawn's own selection: one name has one
3141
3223
  // meaning (E_BACKEND_AMBIGUOUS), and the harness is one the provider runs (E_BACKEND_HARNESS).
3142
- const bound = homeSessionProvider(home, meta, sessionProvider.capability, sessionProvider.backend);
3224
+ const bound = providerBound = homeSessionProvider(home, meta, sessionProvider.capability, sessionProvider.backend);
3143
3225
  let refusal = null;
3144
3226
  if (!bound.problem) { try { selectSessionBackend(sessionProvider.backend, Object.values(capabilityManifests(home)).map((m) => ({ id: m.capability, manifest: m })), harness, "nothing was stopped or started"); } catch (e) { if (!isKernelCode(e?.code)) throw e; refusal = e; } }
3145
3227
  if (bound.problem) fail("backend", "E_SESSION_START_FAILED", `${meta?.instance || instance || basename(home)} cannot be launched on session backend ${sessionProvider.backend}: ${bound.problem}; nothing was stopped or started`);
@@ -3168,7 +3250,7 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3168
3250
  // too (it runs them for real once its preflight passed); the others run
3169
3251
  // here for real on a start, and not at all for a preview.
3170
3252
  try {
3171
- hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: preview ? "preview" : "plan" });
3253
+ hooks = prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, contextDir, extraEnv: harnessExecutableEnv(executable.path, executablePaneSide), assertRoots, pass: noHooks ? "none" : preview ? "preview" : "plan" });
3172
3254
  const current = new Map((resolvedCfg?.capabilities || []).map((c) => [c.id, c]));
3173
3255
  const untrusted = hooks.contributions.filter((c) => c.capability && current.has(c.capability) && !current.get(c.capability).trust?.trusted).map((c) => c.capability);
3174
3256
  const inactive = hooks.contributions.filter((c) => c.capability && !current.has(c.capability)).map((c) => c.capability);
@@ -3246,9 +3328,35 @@ export function planLaunch({ home, instance, meta, contextDir, agentLike, select
3246
3328
  const { trustHome } = sessionProvider ? { trustHome: false } : launchFolderTrust({ harness, home, meta, yolo: recipe.yolo, launch: trustLaunch, env, configEnv, launchConfig: config?.name });
3247
3329
  const command = sessionProvider ? undefined : renderLaunchRecipe(recipe, { home, instance: instance || meta?.instance || basename(home), trustHome });
3248
3330
  const selectionSource = frozen ? (config?.frozen || (!config && !selection.launchConfig && !selection.harness) ? "frozen" : "config") : "config";
3331
+ // A preview of a launch on a session provider asks the provider what the start will ask it
3332
+ // (startProviderSession's askCheck): its `check`, with the launch that is planned, so a launch the
3333
+ // provider would refuse reads refused here and not ready. `check` only reads. `providerCheck`:
3334
+ // `{ sandboxSource }`, the caller's reading of the deployment's configuration (as a start's), from
3335
+ // the command that previews a launch; never from the start's own preview pass, which asks once
3336
+ // itself. Nothing is created: the allowances' paths are not made, nor the kernel's directory.
3337
+ const providerWarnings = [];
3338
+ if (preview && providerCheck && sessionProvider && providerBound?.binding && problems.every((c) => c.ok)) {
3339
+ try {
3340
+ const source = providerCheck.sandboxSource;
3341
+ let sandbox = { unavailable: source?.unavailable ?? "this preview did not resolve the deployment's configuration" };
3342
+ if (source && !source.unavailable) {
3343
+ const allowed = homeSandboxAllowances({ source, home: canonicalHomePath(home), moduleNames: Object.keys(isPlainObject(meta?.modules) ? meta.modules : {}) });
3344
+ for (const { capability, reason } of allowed.skipped ?? []) providerWarnings.push(`sandbox allowances: ${capability} adds no host: ${reason}`);
3345
+ sandbox = sandboxLaunchInput(allowed);
3346
+ // What the start refuses of the paths it would make (E_BACKEND_SANDBOX_HOST): refused here, with nothing made.
3347
+ const refused = sandboxWritePathsRefusal(sandbox.write);
3348
+ if (refused) throw refused;
3349
+ }
3350
+ const notReady = launchReadinessRefusal(providerBound.binding, { launch: plannedLaunch({ home: canonicalHomePath(home), harness, yolo: recipe.yolo, args: recipe.args, sandbox, preview: true }) });
3351
+ if (notReady) problems.push({ check: "backend", ok: false, detail: notReady.message, code: notReady.code });
3352
+ } catch (e) {
3353
+ if (!isKernelCode(e?.code)) throw e;
3354
+ problems.push({ check: "backend", ok: false, detail: e.message, code: e.code });
3355
+ }
3356
+ }
3249
3357
  // A preview states what the start will do; the start states it in its own output.
3250
3358
  const previewNotices = preview && !sessionProvider ? launchStartNotices(dirname(dirname(dirname(dirname(home)))), harness, command) : [];
3251
- return { recipe, command, trustHome, declaredEnv, removedEnv, harness, model: model || undefined, modelSource, yolo, config, executable, executablePaneSide, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}), ...(hooks.dialogClaims ? { hookDialogClaims: hooks.dialogClaims } : {}) };
3359
+ return { recipe, command, trustHome, declaredEnv, removedEnv, harness, model: model || undefined, modelSource, yolo, config, executable, executablePaneSide, preflight: problems, ok: problems.every((c) => c.ok), selectionSource, frozen, launchChoice, warnings: [...(hooks.warnings || []), ...previewNotices, ...providerWarnings], previewedHooks: hooks.previewed || [], volatileEnv: hooks.volatileEnv || [], ...(hooks.meta ? { hookMeta: hooks.meta } : {}), ...(hooks.dialogClaims ? { hookDialogClaims: hooks.dialogClaims } : {}) };
3252
3360
  }
3253
3361
  /** The names a package probe of `harness` depends on: where its program is found and runs, the
3254
3362
  * home directory, and that harness's own selector. */
@@ -3342,7 +3450,33 @@ export function describeLaunchCommand(command) {
3342
3450
  * arguments for the harness; never the kernel's own flags, which are `model`, `yolo` and the
3343
3451
  * prompt (`promptFile`, the home's TASK.md). `previous`: the endpoint of the session this launch
3344
3452
  * replaces (a start, a restart), null for a home's first launch. */
3345
- function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null }) {
3453
+ /** The trees of a home, as a provider's launch (and its check) is handed them: `<home>/work`,
3454
+ * always and first, then every extra tree of the home by its name. An extra tree is what Git
3455
+ * itself says is one (extraWorktreesOf: a `.work-*` directory that is a registered linked
3456
+ * worktree of a repository outside the home), read with the kernel's hardened Git; nothing of
3457
+ * the home's own record (instance.json) names a tree. Absolute paths.
3458
+ *
3459
+ * A provider that sandboxes its harness keeps each tree's Git pointer, configuration and hooks
3460
+ * unwritable. A limit, for such a provider to know: the list of a repository's worktrees is in
3461
+ * its common Git directory, which a session that can write there can shorten; a tree taken off
3462
+ * that list is no longer sent. `<home>/work` always is. */
3463
+ function homeTrees(home) {
3464
+ return [join(home, "work"), ...extraWorktreesOf(home).map((tree) => tree.path)];
3465
+ }
3466
+ /** The kernel's own state for a home, as a provider's launch (and its check) is handed it:
3467
+ * directories a sandboxed agent must never write, and that a provider must not block reading or
3468
+ * executing. One entry: `<instances>/.oats-retirement/`, which holds the kernel's copies of the
3469
+ * home's modules (lib/home-integrity.mjs: what the kernel runs, and where the home's hooks point
3470
+ * the harness), the receipts, the claims and the provider calls in flight. Each is made here
3471
+ * when it is missing (a deployment's first home), so that a provider that refuses a launch for
3472
+ * a missing one refuses a fault and never a first launch. Never derived from the home's record.
3473
+ * `create: false`: a preview's, which names the same directory and makes nothing. */
3474
+ function homeProtected(home, { create = true } = {}) {
3475
+ const paths = [instancesRetirementRoot(dirname(canonicalHomePath(home)))];
3476
+ if (create) for (const path of paths) mkdirSync(path, { recursive: true, mode: 0o700 });
3477
+ return paths;
3478
+ }
3479
+ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [], previous = null, sandbox }) {
3346
3480
  const env = [{ name: "OATS_INSTANCE", value: instance, source: "kernel" }, { name: "OATS_INSTANCE_HOME", value: home, source: "kernel" }];
3347
3481
  const hookEnv = recipe.hooks?.env || {};
3348
3482
  const owner = (name) => (recipe.hooks?.contributions || []).find((c) => (c.env || []).includes(name))?.capability ?? null;
@@ -3370,8 +3504,32 @@ function providerLaunchInput({ home, instance, recipe, env: hostEnv, removed = [
3370
3504
  home, instance, harness: recipe.harness, model: recipe.model ?? null, yolo: recipe.yolo ?? null,
3371
3505
  env, unset: [...removed], pathPrepend: [kernelShimDir(home)],
3372
3506
  args: [...(recipe.args || []), ...hookWords], promptFile: join(home, "TASK.md"), previous,
3507
+ // What the provider may widen its harness's sandbox by, and nothing else (lib/sandbox-allowances.mjs).
3508
+ ...(sandbox ? { sandbox } : {}),
3509
+ // The home's trees (homeTrees): what a provider that sandboxes protects the Git files of.
3510
+ trees: homeTrees(home),
3511
+ // The kernel's own state (homeProtected): never written by a sandboxed agent.
3512
+ protected: homeProtected(home),
3373
3513
  };
3374
3514
  }
3515
+ /** A home's record of its capabilities' runtime (`capabilityRuntime`), one row per capability of
3516
+ * the spawn's resolution. */
3517
+ const capabilityRuntimeRows = (resolvedCfg) => resolvedCfg.capabilities.map((cap) => ({
3518
+ id: cap.id, layer: cap.layer, level: cap.level, settings: cap.settings, settingsOrigins: cap.settingsOrigins ?? {},
3519
+ hooks: cap.hooks, requiredHooks: cap.requiredHooks, environment: cap.environment, environmentNamespaces: cap.environmentNamespaces,
3520
+ missingRequires: cap.missingRequires, trust: cap.trust,
3521
+ executable: cap.executable,
3522
+ }));
3523
+ /** The launch that is planned, as a provider's `check` is handed it BEFORE any hook runs:
3524
+ * `{ harness, yolo, args, sandbox, trees, protected }`. `args` are the launch configuration's own: the
3525
+ * arguments a capability's hooks contribute are not known yet, and reach the launch input only.
3526
+ * `trees` and `protected` are the launch input's (homeTrees, homeProtected): a provider that
3527
+ * would refuse a launch for either refuses it here, before a restart stops anything.
3528
+ * `preview`: asked by a command that creates nothing (a spawn's preview, whose home does not
3529
+ * exist yet; a launch's): the same paths, with nothing made, and for a home that is not there
3530
+ * the one tree every home has. */
3531
+ const plannedLaunch = ({ home, harness, yolo, args, sandbox, preview = false }) => ({ harness, yolo: yolo ?? null, args: [...(args || [])], ...(sandbox ? { sandbox } : {}),
3532
+ trees: preview && !existsSync(home) ? [join(home, "work")] : homeTrees(home), protected: homeProtected(home, { create: !preview }) });
3375
3533
  /** A home's independent session receipt, read to be written again with another `runtime` → `{ path,
3376
3534
  * baseline }`. Refused as every writer of it refuses: E_RUNTIME_ENDPOINT_UNKNOWN for a receipt that
3377
3535
  * is missing, unreadable, of another home, or that authorises nothing. */
@@ -3682,7 +3840,7 @@ export async function spawnInstanceAsync(root, agent, o = {}) {
3682
3840
  const it = spawnBody(root, agent, o);
3683
3841
  let step = it.next();
3684
3842
  while (!step.done) {
3685
- // The single yield hands back a promise-producing thunk; await it and feed the
3843
+ // Each yield hands back a promise-producing thunk; await it and feed the
3686
3844
  // result (or throw the failure) back into the body.
3687
3845
  try { const value = await step.value(); step = it.next(value); }
3688
3846
  catch (e) { step = it.throw(e); }
@@ -3769,6 +3927,29 @@ function* spawnBody(root, agent, o = {}) {
3769
3927
  provider = selected.backend === "tmux" ? null : selected;
3770
3928
  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
3929
  } catch (e) { previewPreflightBudget = null; throw e; }
3930
+ // The Git settings of this spawn's own tree: for a home on a session provider, no hook and no
3931
+ // file monitor of the repository (lib/instance-git.mjs PROVIDER_TREE_GIT); none for a tmux home.
3932
+ const treeGit = provider ? PROVIDER_TREE_GIT : [];
3933
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
3934
+ // deployment's own resolution: refused here, before anything is created, when a capability
3935
+ // asks for a host it may not ask for. A tmux launch has none.
3936
+ let sandbox = null;
3937
+ if (provider) {
3938
+ try {
3939
+ const deployment = o.prepared.deployment || workspaceOf(root), eventsDir = sandboxEventsDir(deployment);
3940
+ sandbox = sandboxAllowances({
3941
+ modules: (o.prepared.resolution?.modules || []).map((m) => ({ name: m.name, manifest: m.manifest })),
3942
+ slots: o.prepared.resolution?.slots ?? {}, payloads: o.prepared.resolution?.payloads ?? {}, origins: o.prepared.resolution?.payloadOrigins ?? {},
3943
+ teams: (o.prepared.resolution?.teams ?? []).map((row) => row.team).filter((team) => typeof team === "string"),
3944
+ defaultTeam: typeof o.prepared.resolution?.defaultTeam?.team === "string" ? o.prepared.resolution.defaultTeam.team : null,
3945
+ eventsDir, deployment, outside: [root, eventsDir],
3946
+ });
3947
+ // The paths it names exist, and are what they must be, before anything of the spawn is
3948
+ // created. A preview creates nothing, and refuses what the apply would refuse of them.
3949
+ if (o.preview !== true) ensureSandboxWritePaths(sandbox.write);
3950
+ else { const refused = sandboxWritePathsRefusal(sandbox.write); if (refused) throw refused; }
3951
+ } catch (e) { previewPreflightBudget = null; throw e; }
3952
+ }
3772
3953
  // Instance homes belong in the soul-owning repo's PRIMARY checkout, never in a
3773
3954
  // linked worktree (see canonicalDeploymentPath). The CLI resolves this through
3774
3955
  // ensureRoot, but the kernel is its own validation boundary — the desktop
@@ -4239,6 +4420,44 @@ function* spawnBody(root, agent, o = {}) {
4239
4420
  if (suggesting) paneCwd = home;
4240
4421
 
4241
4422
  if (existsSync(directoryRollbackPath(homeReal))) throw oatsError("E_WORK_INSPECTION_FAILED", `directory cleanup is still owed for ${home}; restore and retire the retained home before reusing its name`);
4423
+ // A preview of a spawn on a session provider asks the provider what the apply will ask it before
4424
+ // any hook runs (below, `refusedBeforeHooks`): its `check`, with the launch that is planned. A
4425
+ // launch the provider would refuse fails the preview with the apply's own code, as every other
4426
+ // refusal of a backend does; nothing is created. `check` only reads.
4427
+ // - The home does not exist yet: the check is handed its planned path, and the kernel's
4428
+ // directory (`protected`) by name, not made.
4429
+ // - The provider's script runs from its package's verified tree in the deployment's module
4430
+ // store (as `oats readiness --soul` runs it), fetched there when it is absent. A provider in
4431
+ // a member module runs only from a spawned home: the preview says it was not asked.
4432
+ // - It runs within what is left of the preview's one budget; a provider that does not answer
4433
+ // in it leaves the preflight a `timeout`.
4434
+ // A provider that declares no check has nothing to be asked, here as at the apply.
4435
+ let previewCheckWarning = null;
4436
+ if (o.preview === true && launch && provider && provider.provider?.commands?.check) {
4437
+ const said = `${provider.capability}'s session provider ${backend}`, notAsked = (why) => `${said} was not asked whether it can take this launch (${why}): the spawn asks it before any hook runs, and refuses what it refuses`;
4438
+ const module = (o.prepared.resolution?.modules || []).find((m) => m.name === provider.capability);
4439
+ let dir = null, unread = null;
4440
+ if (module?.from?.kind === "package") { try { dir = yield () => (o.providerTree ?? providerTreeDefault)(o.prepared, module); } catch (e) { unread = safeText(e?.message ?? e, 300); } }
4441
+ const left = preflightStarted + preflightBudgetMs - Date.now();
4442
+ if (module?.from?.kind !== "package") previewCheckWarning = notAsked("a provider in a member module runs only from a spawned home");
4443
+ else if (!dir) previewCheckWarning = notAsked(`its package's tree could not be read${unread ? `: ${unread}` : ""}`);
4444
+ else if (left <= 0) preflight.status = "timeout";
4445
+ else {
4446
+ const rows = capabilityRuntimeRows(resolvedCfg), row = rows.find((c) => c.id === provider.capability);
4447
+ // The provider's environment is the apply's: the soul directory the home will record (not a
4448
+ // preview's temporary copy of the soul), and the capability's level, which is the home.
4449
+ const planned = { agent: agent.name, instance, home, soulDir: homeSoulTargetOf(agent, o.prepared, soulDir, { planned: true }), harness, capabilityRuntime: rows, ...workspaceRecordOf(o.prepared) };
4450
+ const binding = { home, meta: planned, capability: provider.capability, name: backend, provider: provider.provider, moduleDir: dir, digest: null, soulId: preparedSoulIdOf(o.prepared.soulEntry),
4451
+ cap: { id: provider.capability, layer: row?.layer ?? "", level: row?.level ?? home, settings: isPlainObject(row?.settings) ? row.settings : {}, settingsOrigins: isPlainObject(row?.settingsOrigins) ? row.settingsOrigins : {} } };
4452
+ // (Never longer than the apply gives it: a check slower than its own limit is refused there.)
4453
+ const own = sessionProviderTimeout("check");
4454
+ const notReady = launchReadinessRefusal(binding, { timeoutMs: Math.min(left, own), launch: plannedLaunch({ home, harness, yolo, args: launchConfig?.args, sandbox: sandboxLaunchInput(sandbox), preview: true }) });
4455
+ // Ended by the budget: the preflight did not finish. Ended by its own limit: the apply's refusal.
4456
+ if (notReady?.timedOut && left <= own) preflight.status = "timeout";
4457
+ else if (notReady) throw Object.assign(oatsError(notReady.code, `${instance} would not be launched: ${notReady.message}; nothing was created`), { details: { backend, capability: provider.capability } });
4458
+ }
4459
+ preflight.elapsedMs = Date.now() - preflightStarted;
4460
+ }
4242
4461
  // K6: everything a spawn decides is decided by here — and nothing has been
4243
4462
  // touched. Branch/base for a worktree are named now (not after mkdir) so the
4244
4463
  // preview and the apply agree on them; `o.baseRef` selects the start point.
@@ -4310,7 +4529,7 @@ function* spawnBody(root, agent, o = {}) {
4310
4529
  const preparedSettingsOrigins = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloadOrigins?.[m.name] ?? {})]));
4311
4530
  // The preview's warnings are strings: the launchPromptAnswers notice, then what a module declares and this kernel ignores.
4312
4531
  // The development-channel statement is the apply's: no launch hook runs here, so the argv is unknown.
4313
- const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution)), ...[previewReadWarning()].filter(Boolean)];
4532
+ const previewWarnings = [...(launchPromptNotice ? [launchPromptNotice] : []), ...contractWarningMessages(resolutionContractWarnings(o.prepared.resolution)), ...[previewReadWarning(), previewCheckWarning].filter(Boolean)];
4314
4533
  const preparedSettings = Object.fromEntries(o.prepared.resolution.modules.map((m) => [m.name, structuredClone(o.prepared.resolution.payloads?.[m.name] && typeof o.prepared.resolution.payloads[m.name] === "object" ? o.prepared.resolution.payloads[m.name] : {})]));
4315
4534
  return deliver({
4316
4535
  // Team model v2: the soul's teams here (unmapped rows included) and its default — the choice a
@@ -4322,6 +4541,9 @@ function* spawnBody(root, agent, o = {}) {
4322
4541
  // A session provider is one of the instance's own modules: there to launch. Whether its
4323
4542
  // service is ready is its readiness check's answer (`oats readiness`), not this field's.
4324
4543
  backendStatus: launch ? { name: backend, installed: provider ? true : !!which(backend), started: false } : null,
4544
+ // What a session provider may widen its harness's sandbox by: each host with the capability
4545
+ // and the setting that asked for it, each path with its reason. Absent for tmux.
4546
+ ...(sandbox ? { sandbox } : {}),
4325
4547
  harness, model: model || null, modelSource: launchSelection.modelSource ?? null, launchConfig: launchConfig?.name ?? null, launchConfigSource: launchConfig?.source ?? null, launchConfigDefault: launchConfig?.harnessDefault === true, yolo, backend,
4326
4548
  background, ...(backgroundFrom ? { backgroundFrom } : {}),
4327
4549
  launch: launchReport({ declared: launchChoice.declared, harness, model, launchConfig: launchConfig?.name, from: launchChoice.from, at: launchChoice.at }),
@@ -4361,6 +4583,7 @@ function* spawnBody(root, agent, o = {}) {
4361
4583
  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
4584
  throw e;
4363
4585
  }
4586
+ removeStaleReceipt(home);
4364
4587
  const createdHomeIdentity = directoryIdentity(home);
4365
4588
  // Names are deployment-wide, but the reservation above is per soul: a concurrent
4366
4589
  // spawn of ANOTHER soul under the same name reserves its own directory. Re-check
@@ -4487,22 +4710,7 @@ function* spawnBody(root, agent, o = {}) {
4487
4710
  // including a preview's). The record names ITS commit's directory by realpath — never
4488
4711
  // the pointer — so a later fetch can move "current" without changing what a running
4489
4712
  // instance's hooks see (decision 7); the OKF hook's owner pin stays valid.
4490
- let homeSoulTarget = soulDir;
4491
- if (o.prepared?.soulEntry?.commit) {
4492
- const perCommit = join(agent._dir, "souls", String(o.prepared.soulEntry.commit).slice(0, 12));
4493
- if (existsSync(join(perCommit, "soul.yaml"))) homeSoulTarget = realpathSync(perCommit);
4494
- }
4495
- if (homeSoulTarget === soulDir) {
4496
- // Not prepared (or the cache entry is absent): still never link a swappable pointer —
4497
- // when agents/<name>/soul is the kernel's pointer into souls/, link what it shows now.
4498
- try {
4499
- if (lstatSync(soulDir).isSymbolicLink()) {
4500
- const real = realpathSync(soulDir), soulsReal = realpathSync(join(dirname(soulDir), "souls"));
4501
- const rel = relative(soulsReal, real);
4502
- if (rel && !rel.startsWith("..") && !isAbsolute(rel) && !rel.includes(sep)) homeSoulTarget = real;
4503
- }
4504
- } catch { /* absent souls/ or unreadable link: record the soul dir itself */ }
4505
- }
4713
+ const homeSoulTarget = homeSoulTargetOf(agent, o.prepared, soulDir);
4506
4714
  if (!existsSync(join(home, "CLAUDE.md"))) symlinkSync("AGENTS.md", join(home, "CLAUDE.md"));
4507
4715
 
4508
4716
  // Skills: module skills were copied WHOLE and FLAT into <home>/.agents/skills/<skill>/
@@ -4612,7 +4820,8 @@ function* spawnBody(root, agent, o = {}) {
4612
4820
  }
4613
4821
  let added = false;
4614
4822
  try {
4615
- execFileSync("git", [...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4823
+ // (A provider home's tree: no hook of the repository runs, here or in the rollback: PROVIDER_TREE_GIT.)
4824
+ execFileSync("git", [...treeGit, ...filters.args, "-C", repoAbs, "worktree", "add", wt, "-b", branch, plannedBase.oid],
4616
4825
  { stdio: ["ignore", "pipe", "pipe"] });
4617
4826
  added = true;
4618
4827
  // Git registers a canonical path. Retain it now: compensation hooks can
@@ -4626,7 +4835,7 @@ function* spawnBody(root, agent, o = {}) {
4626
4835
  // Capture every failure and verify Git effects; because canonical
4627
4836
  // identity was unavailable, never claim confirmed worktree absence.
4628
4837
  const run = (argv) => {
4629
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4838
+ try { return { ok: true, out: execFileSync(argv[0], [...treeGit, ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4630
4839
  // With encoding:"utf8" a silent command yields stderr === "" — FALSY — so
4631
4840
  // `e2.stderr || e2.message` fell through to "Command failed: …" and made
4632
4841
  // every clean probe look like a failed one. `git rev-parse --verify
@@ -4644,7 +4853,7 @@ function* spawnBody(root, agent, o = {}) {
4644
4853
  else incomplete.push(`git worktree ${wt}: could not verify removal (canonical path unavailable after add)`);
4645
4854
  incomplete.push(...deleteBranchAsCreated(run, repoAbs, branch, plannedBase.oid));
4646
4855
  }
4647
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4856
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4648
4857
  const note = incomplete.length ? ` — rollback INCOMPLETE — clean up manually: ${incomplete.join("; ")}` : "";
4649
4858
  const error = new Error(`git worktree add/canonicalization failed: ${original}${note}`);
4650
4859
  throw incomplete.length ? unconfirmedSpawn(error) : error;
@@ -4684,6 +4893,13 @@ function* spawnBody(root, agent, o = {}) {
4684
4893
  // (A provider home's names its provider from the first: a spawn killed after its planned record
4685
4894
  // then leaves a receipt that agrees with it.)
4686
4895
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, provider ? { launched: false, session: { backend, provider: provider.capability } } : { launched: false });
4896
+ } else if (provider) {
4897
+ // A provider home, in every other work mode too: its receipt, and with it the kernel's own
4898
+ // copies of its modules (lib/home-integrity.mjs), are made HERE, before the provider's check
4899
+ // and before any hook of the spawn. So the spawn's own hooks run from the kernel's copies as
4900
+ // every later hook does, and a path one of them hands the harness is the kernel's. (The
4901
+ // spawn writes the receipt again later, with what it then knows; the composition is kept.)
4902
+ writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: { backend, provider: provider.capability } });
4687
4903
  }
4688
4904
 
4689
4905
  // Capability lifecycle hooks (spawn) — the knowledge integration scaffolds instance
@@ -4710,11 +4926,7 @@ function* spawnBody(root, agent, o = {}) {
4710
4926
  // rows only) and the default, recorded as EVIDENCE beside `providers` (never inside that
4711
4927
  // capability-keyed map). A home's hooks and operations get the LIVE set (liveTeams); this is
4712
4928
  // what they fall back to when the workspace cannot answer.
4713
- const workspaceRecord = o.prepared ? {
4714
- workspace: { key: o.prepared.discovery?.key ?? null, name: o.prepared.discovery?.workspace?.name ?? null, deployment: o.prepared.deployment ?? null, commit: o.prepared.discovery?.commit ?? null, resolution: o.prepared.resolution.revision, standalone: o.prepared.discovery?.standalone === true, soul: { id: preparedSoulIdOf(o.prepared.soulEntry), repoKey: o.prepared.soulEntry.repoKey, commit: o.prepared.soulEntry.commit, ...(typeof o.prepared.soulEntry.package === "string" ? { name: o.prepared.soulEntry.name, qualifiedName: o.prepared.soulEntry.qualifiedName, package: { id: o.prepared.soulEntry.package, version: o.prepared.soulEntry.version, commit: o.prepared.soulEntry.commit, digest: o.prepared.soulEntry.digest, path: o.prepared.soulEntry.path } } : {}) }, layers: layerRows(o.prepared.resolution) },
4715
- teams: envRows(o.prepared.resolution.teams ?? []),
4716
- defaultTeam: structuredClone(o.prepared.resolution.defaultTeam ?? null),
4717
- } : {};
4929
+ const workspaceRecord = workspaceRecordOf(o.prepared);
4718
4930
  // #796: the `worktree` hooks this spawn fires (work: worktree only), their run, and the
4719
4931
  // in-progress marker that covers a parent killed while its spawn or worktree hooks run.
4720
4932
  const treeHooks = work === "worktree" ? worktreeHooksOf(resolvedCfg.capabilities) : [];
@@ -4750,6 +4962,28 @@ function* spawnBody(root, agent, o = {}) {
4750
4962
  rmSync(join(home, ".oats-rollback-incomplete.json"), { force: true });
4751
4963
  inProgressMarker = false;
4752
4964
  };
4965
+ // The provider's own readiness, with the launch that is planned, BEFORE any hook runs: a launch a
4966
+ // backend says it cannot take (one it would sandbox, without what it needs) is refused with no
4967
+ // hook run, so nothing a hook registers outside the home has to be undone. It needs nothing a
4968
+ // hook produces: the harness, yolo and the allowances are the plan's, and the arguments are the
4969
+ // launch configuration's own (a hook's reach the launch input, not this).
4970
+ let refusedBeforeHooks = null;
4971
+ if (launch && provider) {
4972
+ // (The record is not written yet: the binding is made from what it will hold of the soul, the
4973
+ // capabilities' rows and the workspace, so this call has the environment every later one has.)
4974
+ const planned = { agent: agent.name, instance, home, soulDir: homeSoulTarget, harness, capabilityRuntime: capabilityRuntimeRows(resolvedCfg), ...workspaceRecord };
4975
+ const bound = homeSessionProvider(home, planned, provider.capability, backend);
4976
+ if (bound.binding) bound.binding.soulId = preparedSoulId;
4977
+ const notReady = bound.problem ? null : launchReadinessRefusal(bound.binding, { launch: plannedLaunch({ home, harness, yolo, args: launchConfig?.args, sandbox: sandboxLaunchInput(sandbox) }) });
4978
+ if (bound.problem) refusedBeforeHooks = oatsError("E_SESSION_START_FAILED", `${instance} was not launched: ${bound.problem}`);
4979
+ else if (notReady) refusedBeforeHooks = Object.assign(oatsError(notReady.code, `${instance} was not launched: ${notReady.message}`), { details: { backend, capability: provider.capability } });
4980
+ }
4981
+ dieAt("spawn:hooks");
4982
+ if (refusedBeforeHooks) {
4983
+ // No hook runs for a spawn its backend refused: the spawn is undone below as one whose hooks
4984
+ // never ran (the home and its work are removed; nothing was registered outside them).
4985
+ hookRes = { meta: {}, briefs: [], warnings: [], order: [], launch: {}, env: {}, failures: [], contributions: [], volatileEnv: {}, dialogClaims: {} };
4986
+ } else {
4753
4987
  // Write-ahead: what a retire needs to run the retire hooks (the repository they come from, the
4754
4988
  // capabilities, the soul) is on disk before the first spawn hook runs. Until the final record
4755
4989
  // is written, instance.json is the stub lib/materialize.mjs wrote, which names none of it: a
@@ -4764,6 +4998,7 @@ function* spawnBody(root, agent, o = {}) {
4764
4998
  // name), also for a spawn that launches nothing: it is what a later start launches on.
4765
4999
  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
5000
  });
5001
+ }
4767
5002
  // The spawn hooks' receipt (their `meta`), on disk as soon as there is one: a retire after a kill
4768
5003
  // from here on hands it to the retire hooks.
4769
5004
  if (inProgressMarker) {
@@ -4826,7 +5061,7 @@ function* spawnBody(root, agent, o = {}) {
4826
5061
  : [{ capability: "oats.kernel", event: "spawn" }];
4827
5062
  const incomplete = [...ancillaryCleanup];
4828
5063
  const probe = (argv) => {
4829
- try { return { ok: true, out: execFileSync(argv[0], argv.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
5064
+ try { return { ok: true, out: execFileSync(argv[0], [...(argv[0] === "git" ? treeGit : []), ...argv.slice(1)], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) }; }
4830
5065
  // An absent ref exits 1 with empty stderr; preserve that distinction.
4831
5066
  catch (e2) { return { ok: false, status: e2.status, err: String(e2.stderr ?? e2.message ?? "").trim() }; }
4832
5067
  };
@@ -4906,6 +5141,8 @@ function* spawnBody(root, agent, o = {}) {
4906
5141
  home, instance, agent, soulDir: homeSoulTarget, soulId: preparedSoulId, incomplete, failed, outstandingHooks, outstandingGit,
4907
5142
  repoAbs, work, branch, resolvedCfg, hookMeta: hookRes.meta || {}, compensationMeta,
4908
5143
  launched: false, directoryPreservation: true, directoryHome: homeReal,
5144
+ // (A provider home stays one in its receipt: its composition is what its cleanup runs by.)
5145
+ ...(provider ? { session: { backend, provider: provider.capability } } : {}),
4909
5146
  recordRetirementBaseline: true,
4910
5147
  });
4911
5148
  return { unconfirmed: true, note: `${note}${directoryRecoveries.length ? `; prior work recovery: ${directoryRecoveries.join(", ")}` : ""}` };
@@ -4924,7 +5161,8 @@ function* spawnBody(root, agent, o = {}) {
4924
5161
  try { preserveDirectory(); }
4925
5162
  catch (e) { return retainDirectory(e); }
4926
5163
  try {
4927
- const comp = runLifecycleHooks("retire", {
5164
+ // (A spawn refused before any of its hooks ran has nothing for a retire hook to undo.)
5165
+ const comp = refusedBeforeHooks ? { failures: [], meta: {} } : runLifecycleHooks("retire", {
4928
5166
  home, instance, agentName: agent.name, soulDir: homeSoulTarget, soulId: preparedSoulId, contextDir: repoAbs,
4929
5167
  workspaceDir: workspaceOf(root), rootDir: root, resolved: resolvedCfg,
4930
5168
  priorMeta: hookRes.meta || {},
@@ -4988,7 +5226,7 @@ function* spawnBody(root, agent, o = {}) {
4988
5226
  directoryHome: homeReal, recordRetirementBaseline: true,
4989
5227
  });
4990
5228
  } else {
4991
- try { rmSync(home, { recursive: true, force: true }); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
5229
+ try { rmSync(home, { recursive: true, force: true }); removeModulesStore(home); } catch (e2) { incomplete.push(`instance home ${home}: ${e2.message}`); }
4992
5230
  if (existsSync(home) && !incomplete.some((m) => m.startsWith("instance home"))) incomplete.push(`instance home ${home}: still present`);
4993
5231
  note = incomplete.length ? ` — rollback INCOMPLETE, clean up manually: ${incomplete.join("; ")}` : " — spawn rolled back";
4994
5232
  }
@@ -4996,6 +5234,7 @@ function* spawnBody(root, agent, o = {}) {
4996
5234
  };
4997
5235
 
4998
5236
  try {
5237
+ if (refusedBeforeHooks) throw refusedBeforeHooks;
4999
5238
  if (requiredFailures.length) {
5000
5239
  const detail = requiredFailures.map((f) => ` ${f.capability} ${f.event} ${f.contract === "environment" ? "environment contract" : "hook (declared required)"}: ${f.message}`).join("\n");
5001
5240
  const code = requiredFailures.some((f) => f.contract === "environment") ? "E_HOOK_ENVIRONMENT_CONTRACT" : "E_REQUIRED_HOOK_FAILED";
@@ -5190,12 +5429,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5190
5429
  skillAlias: { path: join(home, ".claude", "skills"), target: join("..", ".agents", "skills") },
5191
5430
  },
5192
5431
  },
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
- })),
5432
+ capabilityRuntime: capabilityRuntimeRows(resolvedCfg),
5199
5433
  // The session's endpoint, as the receipt authorises it: tmux's planned names, or a session
5200
5434
  // provider's backend and capability (its endpoint is the provider's answer to the launch).
5201
5435
  ...(provider ? { backend, session: { provider: provider.capability, endpoint: null } } : { tmux: { session, window: instance } }),
@@ -5234,11 +5468,8 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5234
5468
  writeRetirementBaseline(home, join(home, "work"), work, resolvedCfg.capabilities, { launched: false, session: plannedSession });
5235
5469
  const found = homeSessionProvider(home, meta, provider.capability, backend);
5236
5470
  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 } });
5471
+ // (The provider's readiness was asked before the spawn's hooks ran.)
5472
+ const input = providerLaunchInput({ home, instance, recipe, env: process.env, removed: removedEnv, previous: null, sandbox: sandboxLaunchInput(sandbox) });
5242
5473
  assertHostRunAdmission();
5243
5474
  // From here a session may exist: the spawn's compensation stops it before anything is removed.
5244
5475
  // And a spawn that ends here without doing so (killed, its host stopped) leaves its word in
@@ -6603,9 +6834,29 @@ export function rebaseUpgradeRetirementBaseline(home, { homeChangedSinceSpawn }
6603
6834
  writeJsonAtomic(path, { ...baseline, homeFingerprint }, 0o600);
6604
6835
  }
6605
6836
 
6837
+ /** A spawn's first act on the home it has just made: take away the receipt an earlier home left
6838
+ * at this path. A retire keeps a home's receipt, by the home's path, and a spawn writes its own
6839
+ * only later (in most work modes after its spawn hooks), so until then every reader of "this
6840
+ * home's receipt" would read the retired home's: its backend, and for a provider home its
6841
+ * composition, by which this spawn's hooks would be run. The home was made by this spawn a
6842
+ * moment ago (an exclusive mkdir), so whatever receipt is at its path is not its own. */
6843
+ function removeStaleReceipt(home) {
6844
+ for (const path of new Set([retirementBaselinePath(home), legacyRetirementBaselinePath(home)])) rmSync(path, { force: true });
6845
+ // (And the kernel's copies of that home's modules, by the same key.)
6846
+ removeModulesStore(home);
6847
+ }
6848
+
6606
6849
  /** Project transaction-owned temporary files out of this baseline only. Later
6607
6850
  * fingerprints still hold them: a stale mutex is work to preserve, not invisible state. */
6608
6851
  export function writeRetirementBaseline(home, work, mode, capabilities, runtime, { exclusive = false, incarnationId, executionBinding, transientHomePaths = [] } = {}) {
6852
+ // A receipt that names a session provider is never rewritten as one that names none: a caller
6853
+ // that hands no session (a rollback that knows only that nothing is launched) keeps the home's
6854
+ // backend and provider, and with them its composition. Without them the home would read as a
6855
+ // tmux home, whose own copies and own record the kernel runs.
6856
+ const standing = homeReceipt(home)?.runtime;
6857
+ if (!runtime?.session && isPlainObject(standing) && typeof standing.provider === "string" && typeof standing.backend === "string") {
6858
+ runtime = { launched: false, session: { backend: standing.backend, provider: standing.provider } };
6859
+ }
6609
6860
  const transientFiles = retirementTransientFiles(home, transientHomePaths);
6610
6861
  if (mode === "directory") assertDirectoryRoots(home);
6611
6862
  const isWorktree = mode === "worktree";
@@ -6622,6 +6873,15 @@ export function writeRetirementBaseline(home, work, mode, capabilities, runtime,
6622
6873
  disposableReceipts,
6623
6874
  disposableHome,
6624
6875
  generatedWorkFingerprint: isWorktree ? generatedWorkDigest(work, statusBytes, disposableReceipts.map((r) => r.root)) : undefined,
6876
+ // A provider home's composition (lib/home-integrity.mjs): the store that holds the kernel's
6877
+ // own copies of the home's modules, made here from the copies this spawn materialised, and
6878
+ // the capability rows it resolved from the deployment. For such a home the kernel runs its
6879
+ // own copy of a module, and reads a capability's settings and hook commands from this record,
6880
+ // never from the home. A kernel from before it ignores the key.
6881
+ // Taken ONCE: a receipt that holds one keeps it (a spawn's later writes, its rollback's, a
6882
+ // 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
6883
+ // (removeStaleReceipt), so the one found here is this home's own.
6884
+ ...(runtime?.session ? { composition: providerHomeTrust(home)?.composition ?? compositionOf(home, capabilityRuntimeRows({ capabilities })) } : {}),
6625
6885
  // `runtime.session`: a home on a session provider (lib/session-providers.mjs): its backend and the
6626
6886
  // capability that supplies it, and once launched the endpoint and whether OATS stopped it.
6627
6887
  runtime: runtime?.session
@@ -6832,6 +7092,7 @@ function stopSessionClaimed(home, o) {
6832
7092
  // A launch that was sent to the home's provider and never recorded: the provider stops whatever
6833
7093
  // it started before anything else is answered. Never "not launched" while that is not known.
6834
7094
  const sent = s.unsettled;
7095
+ if (sent) refuseOtherWire(realHome, s.meta, sent, "stopped", "nothing was stopped");
6835
7096
  if (sent && s.session) {
6836
7097
  // A home launched before: the one stop rule first (stopProviderHome: `stoppedAt` and the stop
6837
7098
  // receipt before the provider is called, the recorded session stopped, a host's stop
@@ -6909,6 +7170,17 @@ function stopProviderSessionRecorded(home, meta, session, { withHost = false, gr
6909
7170
  const unconfirmed = providerStopUnconfirmed(home, meta, session, session.endpoint, graceMs, io, null, { outlasted });
6910
7171
  return { unconfirmed, waitedMs: Date.now() - started };
6911
7172
  }
7173
+ /** A home whose provider speaks another wire than this kernel is refused by name, E_BACKEND_WIRE,
7174
+ * before a verb records or asks anything: a start, a stop (the host's too) and an input. Its
7175
+ * sessions read unavailable and are never recorded as stopped by a provider that was not asked.
7176
+ * (A retire keeps its own rule: it cannot ask that provider, and goes on when no process works in
7177
+ * the home, with the warning that names the provider's own tooling.) `recorded`: `{ backend,
7178
+ * provider }`; `what`: the verb's participle; `nothing`: what did not happen. */
7179
+ function refuseOtherWire(home, meta, recorded, what, nothing) {
7180
+ const found = homeSessionProvider(home, meta, recorded.provider, recorded.backend);
7181
+ const wire = found.problem ? null : wireRefusal(recorded.provider, found.binding.provider);
7182
+ if (wire) throw Object.assign(oatsError(wire.code, `${meta.instance || basename(home)} was not ${what}: ${wire.message}; ${nothing}`), { details: wire.details });
7183
+ }
6912
7184
  /** The stop of a home on a session provider (lib/session-providers.mjs), under the home's claim.
6913
7185
  * Kernel-owned: the receipt records `stoppedAt` BEFORE the provider is called, so from that
6914
7186
  * instant inspect answers stopped and input is refused, whatever the provider then does; a start
@@ -6924,6 +7196,8 @@ function stopProviderHome(realHome, s, o) {
6924
7196
  const { backend, stoppedAt } = s.session;
6925
7197
  const withHost = o.withHost === true;
6926
7198
  const idle = { home: s.home, backend, stopped: false, alreadyIdle: true, state: "stopped", receipt: null };
7199
+ // (The host's shutdown asks nothing of a home that is stopped already: it has no provider to refuse.)
7200
+ if (!(stoppedAt !== null && withHost)) refuseOtherWire(realHome, s.meta, s.session, "stopped", "nothing was stopped");
6927
7201
  if (stoppedAt !== null) {
6928
7202
  // The host's shutdown changes nothing of a home that is stopped already.
6929
7203
  if (withHost) return idle;
@@ -7029,6 +7303,9 @@ function inputProviderHome(s, text) {
7029
7303
  if (s.unsettled) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${unsettledLaunchSaid(name, backend, s.unsettled.launchSent)}; nothing was sent`);
7030
7304
  const found = homeSessionProvider(s.home, s.meta, provider, backend);
7031
7305
  if (found.problem) throw oatsError("E_SESSION_INPUT_FAILED", `cannot submit session input: ${found.problem}`);
7306
+ // A provider that speaks another wire is never called: refused by name (refuseOtherWire's rule).
7307
+ const wire = wireRefusal(provider, found.binding.provider);
7308
+ if (wire) throw Object.assign(oatsError(wire.code, `${name} was not sent the input: ${wire.message}; nothing was sent`), { details: wire.details });
7032
7309
  const inspected = inspectProviderSession(found.binding, endpoint);
7033
7310
  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
7311
  const resume = inspected.observed.present ? null : resumeLostSession(s.home, name, { waitMs: 0 });
@@ -7084,7 +7361,7 @@ function inputProviderHome(s, text) {
7084
7361
  if (crossing) {
7085
7362
  // (Recorded as a call, as every stop is; no drain: an input does not wait for another.)
7086
7363
  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`);
7364
+ 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
7365
  }
7089
7366
  if (failure) throw failure;
7090
7367
  // No endpoint here: it is on inspect, spawn and start answers only.
@@ -7396,6 +7673,16 @@ export function capturedProviders(meta, frozen) {
7396
7673
  /** The session backend a home launches on, as its record says: a session provider's name, else tmux.
7397
7674
  * A launch hook's OATS_BACKEND (a spawn hook's is the spawn's own choice). */
7398
7675
  const homeBackendOf = (meta) => (recordsSessionProvider(meta) ? meta.backend : "tmux");
7676
+ /** The backend a home was last launched on, as the kernel recorded it OUTSIDE the home (its session
7677
+ * receipt): a session provider's name, or `tmux`; undefined for a home that was never launched,
7678
+ * and for one whose receipt is missing or says nothing this kernel reads. Never the home's own
7679
+ * record (instance.json), which the home's agent can write. A launch hook's OATS_PREVIOUS_BACKEND:
7680
+ * a capability that wrote files of its own for one backend reads here whether they are its to
7681
+ * remove, and removes nothing when the variable is absent. */
7682
+ function previousBackendOf(home) {
7683
+ const authority = runtimeAuthorityOf(homeReceipt(home));
7684
+ return authority?.session ? authority.session.backend : authority?.tmux ? "tmux" : undefined;
7685
+ }
7399
7686
  /** Capability contributions for a start of an existing home: the recorded
7400
7687
  * ones, refreshed by any capability that declares a `launch` hook (asked
7401
7688
  * for the target harness; spawn hooks are never re-run). A harness change
@@ -7441,13 +7728,15 @@ export function prepareLaunchHooks({ frozen, harness, resolvedCfg, home, meta, c
7441
7728
  }
7442
7729
  const aware = withLaunchHook.filter((c) => c.manifest.launchPreview === true);
7443
7730
  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) : [];
7731
+ // (`none`: no hook runs, whether it previews or not; every recorded contribution stands.)
7732
+ const runs = (pass === "none" ? [] : pass === "real" ? [[aware, false]] : pass === "preview" ? [[aware, true]] : [[unaware, false], [aware, true]]).filter(([caps]) => caps.length);
7733
+ const notRun = pass === "none" ? withLaunchHook.map((c) => c.id) : pass === "preview" ? unaware.map((c) => c.id) : [];
7446
7734
  const previewed = runs.filter(([, asPreview]) => asPreview).flatMap(([caps]) => caps.map((c) => c.id));
7447
7735
  const volatileEnv = [];
7448
7736
  let hookDialogClaims;
7449
7737
  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 } }) }));
7738
+ const previousBackend = previousBackendOf(home);
7739
+ 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
7740
  const failed = results.flatMap(({ res }) => res.failures || []).map((f) => `${f.capability}: ${f.message}`);
7452
7741
  if (failed.length) throw oatsError("E_LAUNCH_PREPARATION", `a capability could not prepare the ${harness} launch:\n ${failed.join("\n ")}`);
7453
7742
  const fresh = results.flatMap(({ res }) => res.contributions || []);
@@ -7832,7 +8121,8 @@ function startSession(home, o) {
7832
8121
  const receipt = instanceSessionTarget(realHome);
7833
8122
  const meta = readMeta();
7834
8123
  // 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 });
8124
+ // (Its capability rows are its receipt's, never its own record's: lib/home-integrity.mjs.)
8125
+ if (providerHomeOf(receipt)) return startProviderSession(realHome, o, { receipt, meta: trustedRecord(meta, providerHomeTrust(realHome)), checkRoots, drift, cleanupWarnings });
7836
8126
  const harness = meta.harness;
7837
8127
  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
8128
  let command = meta.command;
@@ -8272,6 +8562,9 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8272
8562
  const session = receipt.session ?? null;
8273
8563
  const name = meta.instance || basename(realHome);
8274
8564
  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`);
8565
+ // 0. A provider that speaks another wire than this kernel is never called: refused by name,
8566
+ // before its session is read, resumed, stopped or launched.
8567
+ refuseOtherWire(realHome, meta, { backend, provider }, "started", "nothing was stopped or started");
8275
8568
  if (o.resume === true) {
8276
8569
  // A launch that was sent and never recorded, on a home launched before or not: unknown, nothing is resumed.
8277
8570
  if (receipt.unsettled) throw oatsError("E_SESSION_UNKNOWN", `${unsettledLaunchSaid(name, backend, receipt.unsettled.launchSent)}; nothing was resumed`);
@@ -8289,7 +8582,7 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8289
8582
  if (inspected.observed.present) {
8290
8583
  if (!o.restart) {
8291
8584
  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}`);
8585
+ 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
8586
  }
8294
8587
  replaced = true;
8295
8588
  }
@@ -8300,7 +8593,51 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8300
8593
  let agent; try { agent = findAgent(dirname(dirname(dirname(realHome))), meta.agent); } catch { agent = undefined; }
8301
8594
  const reselect = o.reselectLaunch === true ? homeLaunchLayers(realHome, meta, { offered: o.launchOffered }) : null;
8302
8595
  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 });
8596
+ // 1a. The provider's own readiness, with the launch that is planned, BEFORE any launch hook runs
8597
+ // and before anything is stopped: a restart never trades a session that runs for a backend that
8598
+ // says it cannot launch one, and a refused start runs no hook. What it is asked with is the
8599
+ // SELECTION, which needs no hook: the harness, yolo and the launch configuration's own
8600
+ // arguments (a hook's arguments reach the launch input, not this), taken from a plan made with no
8601
+ // hook run at all. It is asked whatever else that plan says (its preflight reads the recorded
8602
+ // contributions, which the real plan refreshes), and, should that plan give no selection, right
8603
+ // after the real one: a launch is never sent, nor a session stopped, with the check not asked.
8604
+ 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 });
8605
+ // The kernel holds its copy of every module of the home (lib/home-integrity.mjs), before any of
8606
+ // their manifests is read for the plan: a launch is made of all of them.
8607
+ const untrusted = homeModulesProblem(realHome);
8608
+ if (untrusted) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${untrusted}; nothing was stopped or started`);
8609
+ const bound0 = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8610
+ if (bound0.problem) throw oatsError("E_SESSION_START_FAILED", `${name} was not started: ${bound0.problem}`);
8611
+ // What the provider may widen its harness's sandbox by (lib/sandbox-allowances.mjs), from the
8612
+ // deployment's configuration as it is now, which an async caller resolved (`o.sandboxSource`:
8613
+ // lib/instance-resolution.mjs homeSandboxSource, which takes the deployment and the soul from
8614
+ // where this home is, never from what is in it). Only for capabilities that are also this
8615
+ // home's modules: the rest are named, and add nothing. Refused here (E_BACKEND_SANDBOX_HOST),
8616
+ // before any hook runs and before anything is stopped.
8617
+ let sandbox, sandboxAnswer;
8618
+ const sandboxWarnings = [];
8619
+ if (!o.sandboxSource || o.sandboxSource.unavailable) sandbox = { unavailable: o.sandboxSource?.unavailable ?? "this start did not resolve the deployment's configuration" };
8620
+ else {
8621
+ const allowed = homeSandboxAllowances({ source: o.sandboxSource, home: realHome, moduleNames: Object.keys(isPlainObject(meta.modules) ? meta.modules : {}) });
8622
+ sandboxAnswer = allowed;
8623
+ for (const { capability, reason } of allowed.skipped ?? []) sandboxWarnings.push(`sandbox allowances: ${capability} adds no host: ${reason}`);
8624
+ sandbox = sandboxLaunchInput(allowed);
8625
+ // The paths it names exist, and are what they must be, before anything is stopped.
8626
+ ensureSandboxWritePaths(sandbox.write);
8627
+ }
8628
+ let checkAsked = false;
8629
+ const askCheck = (planned) => {
8630
+ checkAsked = true;
8631
+ const notReady = launchReadinessRefusal(bound0.binding, { io: o.io, launch: plannedLaunch({ home: realHome, harness: planned.harness, yolo: planned.recipe.yolo, args: planned.recipe.args, sandbox }) });
8632
+ if (notReady) throw Object.assign(oatsError(notReady.code, `${name} was not started: ${notReady.message}; nothing was stopped or started`), { details: { backend, capability: provider } });
8633
+ };
8634
+ {
8635
+ let selected = null;
8636
+ try { selected = planOf({ preview: true, noHooks: true }); } catch { /* the real plan, below, says what this could not plan */ }
8637
+ if (selected?.recipe) askCheck(selected);
8638
+ }
8639
+ const plan = planOf();
8640
+ if (!checkAsked) askCheck(plan);
8304
8641
  let recipe = plan.recipe, hookMeta = plan.hookMeta, hookDialogClaims = plan.hookDialogClaims;
8305
8642
  let warnings = [...plan.warnings];
8306
8643
  for (const message of plan.warnings) appendEvent(realHome, { kind: "launch-warning", data: { message } });
@@ -8317,13 +8654,11 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8317
8654
  }
8318
8655
  const removed = removedLaunchEnv({ declared: plan.declaredEnv, hooksEnv: recipe.hooks?.env, configEnv: recipe.env });
8319
8656
  if (kernelNode().warning) warnings.push(kernelNode().warning);
8657
+ // (The binding after the launch hooks: what they left of the home's module copy is what launches.)
8320
8658
  const found = bound ? { binding: bound } : homeSessionProvider(realHome, meta, provider, backend);
8321
8659
  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 } });
8660
+ for (const message of sandboxWarnings) { warnings.push(message); appendEvent(realHome, { kind: "launch-warning", data: { message } }); }
8661
+ const input = providerLaunchInput({ home: realHome, instance: meta.instance, recipe, env: o.env || process.env, removed, previous: session?.endpoint ?? null, sandbox });
8327
8662
  checkRoots();
8328
8663
  // 2. A launch that an earlier spawn or start sent and never recorded (launchSentOf): settled
8329
8664
  // first. The provider stops whatever that launch started, and the home is then planned, or
@@ -8411,7 +8746,12 @@ function startProviderSession(realHome, o, { receipt, meta, checkRoots, drift, c
8411
8746
  if (!outcomeRecordFailures.has(e)) throw unrecorded(e);
8412
8747
  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
8748
  // `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 } : {}) };
8749
+ // (`moduleCopy`, as the home's status row carries it: which copy of its modules ran, and whether
8750
+ // the home's own record of them is the receipt's. The home's record is read as a row reads it
8751
+ // (readHomeRecord: a regular file only), since the session that could exchange it now runs.)
8752
+ let startedModuleCopy;
8753
+ try { startedModuleCopy = moduleCopyReport(readHomeRecord(realHome).meta, providerHomeTrust(realHome)); } catch { startedModuleCopy = undefined; }
8754
+ 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
8755
  }
8416
8756
  /** `session start --resume` of a home on a session provider, and what the machine sweep runs for it
8417
8757
  * (lib/session-resume.mjs): the session continues in its own conversation, through the provider's
@@ -11740,6 +12080,8 @@ function retireSteps(root, name, o, found, at) {
11740
12080
  at.lead = () => `${name}: the directory at ${found.home} could not be removed`;
11741
12081
  rmSync(found.home, { recursive: true, force: true });
11742
12082
  at.lead = () => `${name}: its home was removed, and a file the retire leaves beside it could not be`;
12083
+ // (The kernel's own copies of a provider home's modules go with the home.)
12084
+ removeModulesStore(found.home);
11743
12085
  rmSync(directoryFallbackPath, { force: true });
11744
12086
  // The owed retirement is paid: clear the pending marker, and the failed
11745
12087
  // outcome an earlier deferred attempt may have left beside the home; a