@awebai/oats 0.69.17 → 0.69.18

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 (52) hide show
  1. package/README.md +1 -1
  2. package/bin/oats.mjs +14 -13
  3. package/docs/capabilities.md +7 -0
  4. package/docs/container.md +172 -18
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +8 -2
  6. package/docs/desktop-cli-api.md +73 -33
  7. package/docs/desktop.md +40 -18
  8. package/docs/execution-targets.md +36 -33
  9. package/docs/implementation.md +7 -6
  10. package/docs/integrations.md +2 -2
  11. package/docs/knowledge.md +5 -5
  12. package/docs/official-catalog.md +7 -7
  13. package/docs/packages.md +13 -13
  14. package/docs/release-lane.md +24 -19
  15. package/docs/release-notes/v0.69.18.md +358 -0
  16. package/docs/servers.md +3 -1
  17. package/docs/souls-and-instances.md +18 -16
  18. package/docs/trust-model.md +119 -0
  19. package/docs/upgrading.md +39 -19
  20. package/docs/workspaces.md +3 -3
  21. package/lib/command-flags.mjs +1 -1
  22. package/lib/core.mjs +24 -9
  23. package/lib/errors.mjs +1 -1
  24. package/lib/home-owner.mjs +25 -0
  25. package/lib/host-run-admission.mjs +21 -0
  26. package/lib/host-run-child.mjs +31 -0
  27. package/lib/host-run-work.mjs +150 -0
  28. package/lib/host-run.mjs +20 -11
  29. package/lib/instance-naming.mjs +26 -44
  30. package/lib/packages.mjs +0 -43
  31. package/lib/pi-bridge.mjs +18 -6
  32. package/lib/schedule.mjs +5 -3
  33. package/lib/servers.mjs +4 -3
  34. package/lib/session-end.mjs +9 -0
  35. package/lib/session-resume.mjs +19 -9
  36. package/lib/session-seen.mjs +13 -8
  37. package/lib/triggers.mjs +3 -1
  38. package/lib/worktree.mjs +5 -2
  39. package/package-catalog.json +3 -3
  40. package/package.json +2 -2
  41. package/packages/client/above-tested-notice.mjs +30 -0
  42. package/packages/client/above-tested.mjs +225 -0
  43. package/packages/client/cli-locator.mjs +67 -52
  44. package/packages/client/deployment-label.mjs +4 -4
  45. package/packages/client/instance-name.mjs +5 -29
  46. package/packages/client/session-start.mjs +31 -3
  47. package/packages/client/workspace-choices.mjs +1 -1
  48. package/packages/client/workspace-views.mjs +1 -1
  49. package/packages/record/README.md +10 -8
  50. package/packages/record/lib/process-identity.mjs +14 -36
  51. package/packages/tui/lib/read.mjs +19 -3
  52. package/skills/oats-getting-started/SKILL.md +33 -4
package/docs/upgrading.md CHANGED
@@ -6,11 +6,12 @@ host that comes from it.
6
6
 
7
7
  ## Upgrading to the latest version
8
8
 
9
- The latest version is **OATS 0.69.17** ([release notes](release-notes/v0.69.17.md)).
10
- The 0.69.17 Desktop accepts OATS CLIs `>=0.26.0 <0.70.0`.
9
+ The latest version is **OATS 0.69.18** ([release notes](release-notes/v0.69.18.md)).
10
+ The 0.69.18 Desktop accepts OATS CLIs `>=0.26.0`, tested through 0.69: the
11
+ Desktop and the CLI can be upgraded [in either order](#either-order-works).
11
12
 
12
13
  **First, read the `## Upgrade` section of every release after yours, up to
13
- 0.69.17,** in the [release notes](release-notes/): it says what to do before
14
+ 0.69.18,** in the [release notes](release-notes/): it says what to do before
14
15
  the CLI changes, and what else must change with it (the Desktop, another
15
16
  tool, a package pin). [Coming from an older version](#coming-from-an-older-version)
16
17
  names the releases that ask for more than the steps below. `oats version`
@@ -19,14 +20,14 @@ prints the version you have.
19
20
  Then, on each host:
20
21
 
21
22
  ```sh
22
- # 0. where the Desktop is installed: Desktop 0.69.17 first
23
- npm install -g @awebai/oats@0.69.17 # 1. the CLI
23
+ # 0. where the Desktop is installed: Desktop 0.69.18, in either order
24
+ npm install -g @awebai/oats@0.69.18 # 1. the CLI
24
25
  oats update # 2. in each deployment: the plan, then it asks before it runs
25
26
  oats doctor # 3. in the same deployment
26
27
  ```
27
28
 
28
29
  The Desktop's installers are the assets of the
29
- [GitHub Release](https://github.com/awebai/oats/releases) of that version
30
+ [GitHub Release](https://github.com/oats-project/oats/releases) of that version
30
31
  ([OATS Desktop](desktop.md#install)). Then restart the pi sessions that were
31
32
  running: a session keeps the bridge it loaded when it started.
32
33
  [The steps](#the-steps) says what each step does and why they come in this
@@ -40,9 +41,12 @@ the version you are upgrading from.
40
41
  ## The steps
41
42
 
42
43
  Upgrading OATS means three things, in this order, on each host, and one
43
- before them where the Desktop is installed:
44
+ more where the Desktop is installed:
44
45
 
45
- 0. **The Desktop**, where it is installed: the new version's, before the CLI.
46
+ 0. **The Desktop**, where it is installed: the new version's. Install it
47
+ before the CLI where the Desktop is 0.69.17 or older
48
+ ([which goes first](#either-order-works)); with a newer one, either order
49
+ works.
46
50
  1. **The CLI** (`@awebai/oats`, the kernel).
47
51
  2. **The pi bridge** (`@awebai/oats-pi`), in every pi folder the host's
48
52
  deployments launch pi with: `oats update`, in each deployment.
@@ -62,12 +66,21 @@ instances. A pi started outside any instance looks for a global install, an
62
66
  **A release's own steps are in its notes**, in its `## Upgrade` section.
63
67
  This page is the part that is the same for every release.
64
68
 
65
- **Why the Desktop goes first.** A Desktop accepts a CLI up to its own minor
66
- version and refuses a newer one: with the CLI moved first, the Desktop that
67
- is still running lists no instance until it is replaced. The new Desktop
68
- accepts the older CLI in the meantime. The CLI can move by two commands, the
69
- `npm install` and an `oats update` whose plan installs it: step 0 comes
70
- before either.
69
+ <a id="either-order-works"></a>**Either order works**, with a Desktop newer than 0.69.17. Such a Desktop was
70
+ tested with the CLIs of its own minor version, and accepts a newer minor or
71
+ major one: reads, terminals, Spawn, Start, Restart, the colour and the
72
+ background keep working with it, and every other change is held back until
73
+ the Desktop of that version is installed. It says so in one line, in the
74
+ place of the CLI card:
75
+ `This Desktop was tested with oats CLIs up to <X.Y>; the installed CLI is <version>. Stop, Remove, schedules, triggers and every other change except Spawn, Start, Restart, colour and background are off until you install OATS Desktop <version>.`
76
+ A Desktop accepts an older CLI too, down to its floor, so installing it first
77
+ holds nothing back.
78
+
79
+ **A Desktop of 0.69.17 or older still refuses a CLI newer than its own minor
80
+ version:** with the CLI moved first, it lists no instance until it is
81
+ replaced. Where one is installed, step 0 comes first. The CLI can move by two
82
+ commands, the `npm install` and an `oats update` whose plan installs it:
83
+ step 0 comes before either.
71
84
 
72
85
  **Package versions are a different thing.** `oats update` moves the CLI and
73
86
  the bridge, never a package. A deployment's capabilities come from the
@@ -84,12 +97,12 @@ Without a terminal (a script, an agent's shell) it runs only with `--yes`.
84
97
 
85
98
  `oats update` also does step 1: when npm lists a newer `@awebai/oats`, its
86
99
  plan starts with that install, and the bridges move to that same version in
87
- the same run. So where the Desktop is installed, step 0 comes before such an
88
- `oats update` too: `oats update --check` shows whether the plan holds that
89
- install, and runs nothing. When that install is of another minor or major
100
+ the same run. So where a Desktop of 0.69.17 or older is installed, step 0
101
+ comes before such an `oats update` too: `oats update --check` shows whether
102
+ the plan holds that install, and runs nothing. When that install is of another minor or major
90
103
  version, the plan says so in one line under its steps, whether or not a
91
- Desktop is installed: `OATS Desktop refuses a CLI newer than its own minor
92
- version: if you use it, install OATS Desktop <version> first.`
104
+ Desktop is installed: `An OATS Desktop older than <X.Y> holds actions back with this CLI. Stop, Remove, schedules, triggers and every other change except Spawn, Start, Restart, colour and background are off until you install OATS Desktop <version>. (An OATS Desktop of 0.69.17 or older refuses this CLI until then.)`
105
+ Its second sentence is the Desktop's own notice, word for word.
93
106
 
94
107
  **`oats update` only moves forward.** It never installs an older CLI or an
95
108
  older bridge than the one in place:
@@ -204,6 +217,13 @@ of the Desktop and the CLI, and an optional package pin. A change a script
204
217
  must follow is in its release's Upgrade section whether or not it is listed
205
218
  here.
206
219
 
220
+ - **[0.69.18](release-notes/v0.69.18.md#upgrade):** from this Desktop on,
221
+ the Desktop and the CLI go in either order (a Desktop of 0.69.17 or older
222
+ still goes first); the catalog pins oats.aweb 1.41.0, oats.okf 6.0.3 and
223
+ oats.framework 1.25.0. Start the host's wake broker before a Codex or
224
+ `delivery: session` home's next start: oats.aweb 1.40.0 and later refuse
225
+ such a home while none runs. Respawn instances to take the new naming and model
226
+ floor texts.
207
227
  - **[0.69.17](release-notes/v0.69.17.md#upgrade):** the catalog pins
208
228
  oats.okf 6.0.2 and oats.framework 1.24.1; respawn each running
209
229
  `oats-engineering-expert` and `oats-product-expert` once after `oats sync`,
@@ -54,8 +54,8 @@ members: # repo refs, NO @revision (E_WORKSPAC
54
54
  - git:github.com/acme/tools # a member that ALSO publishes a package (see below)
55
55
 
56
56
  packages: # the ONLY versioned things
57
- oats.framework: v1.24.1 # bare version → resolves through the official catalog
58
- oats.okf: v6.0.2
57
+ oats.framework: v1.25.0 # bare version → resolves through the official catalog
58
+ oats.okf: v6.0.3
59
59
  acme.tools: git:github.com/acme/tools@v0.4.0 # outside the catalog → git:<repo>@<tag|OID>; still a package
60
60
 
61
61
  teams: # SHARED teams: the same provider team for everyone
@@ -425,7 +425,7 @@ member soul that is the expert in that capability (`oats-okf-expert`,
425
425
  **OATS's coordination is a member copy of the engineering template.** The
426
426
  `oats` repository keeps its own copy of
427
427
  [oats-project/oats-engineering-coordination](https://github.com/oats-project/oats-engineering-coordination)
428
- at template-v3.0.1, adapted to OATS: `oats.engineering-expert`,
428
+ at template-v3.1.3, adapted to OATS: `oats.engineering-expert`,
429
429
  `oats.developer`, `oats.build`, `oats.code-review`, `oats.maintainer`,
430
430
  `oats.landing-rules` and `oats.dispatcher`, in `capabilities/oats-<name>/`.
431
431
  `capabilities/TEMPLATE-RELEASE` records the release, its commit and what was copied, and
@@ -109,7 +109,7 @@ export const COMMAND_FLAGS = Object.freeze([
109
109
  refused: Object.fromEntries(["--home", "--dir", "--producer", "--reason"].map((f) => [f, attentionHasNo(f)])), usage: ATTENTION_USAGE },
110
110
  { command: "instance suggest-name", operands: [], values: ["--soul", "--task", "--task-file", "--harness", "--model", "--launch-config", "--dir"], switches: ["--json"],
111
111
  refused: { "--server": "instance suggest-name takes no --server: it runs this machine's harness, for a spawn that may land on another; the host it lands on makes the name unique (or names an unnamed --suggest-name spawn itself)" },
112
- usage: "usage: oats instance suggest-name --soul <soul> (--task <t> | --task-file <f>) [--harness claude|pi] [--model <m>] [--launch-config <n>] [--dir <d>] [--json]" },
112
+ usage: "usage: oats instance suggest-name [--soul <soul>] (--task <t> | --task-file <f>) [--harness claude|pi] [--model <m>] [--launch-config <n>] [--dir <d>] [--json]" },
113
113
  { command: "worktree add", operands: [], values: ["--purpose", "--branch", "--base", "--repo"], switches: ["--preview", "--json"], refused: WORKTREE_REFUSED,
114
114
  usage: "usage: oats worktree add --purpose <p> --branch <b> --base <remote-branch> [--repo <member key|clone path>] [--preview] [--json]" },
115
115
  { command: "worktree remove", operands: [], values: ["--purpose"], switches: ["--json"], refused: WORKTREE_REFUSED,
package/lib/core.mjs CHANGED
@@ -27,6 +27,7 @@
27
27
  * work (worktree|checkout|attached|workspace|directory), harness (pi|claude|codex), model (pi model pattern, optional)
28
28
  * (attached as soul default is for service agents — spawn must supply workDir)
29
29
  */
30
+ import { assertHostRunAdmission } from "./host-run-admission.mjs";
30
31
  import { isLaunchEnvReference, referenceSource, referenceValue, fileReferenceRemedy, launchEnvHandoff, LAUNCH_ENV_HANDOFF } from "./launch-env.mjs";
31
32
  import { canonicalHomePath, realPathOrNearest } from "./real-path.mjs";
32
33
  import { createLaunchPromptController, neverSettled } from "./launch-prompts.mjs";
@@ -56,6 +57,7 @@ import { captureLoginEnvironment } from "./login-environment.mjs";
56
57
  import { kernelNode } from "./stable-node.mjs";
57
58
  import { assertNoPartialUpgrade, packageRespawnWarning, packageUpgradeDrift, upgradeCleanupWarnings, upgradeMutexRetry, UPGRADE_RECEIPT_NAME_RE } from "./upgrade-state.mjs";
58
59
 
60
+ import { refuseHomeOfAnotherUser } from "./home-owner.mjs";
59
61
  import { oatsError, afterEndedSteps, afterFirstEffect, asKernelError, BEFORE_EFFECT_CODES, checkHolderByHand, errorCause, ifItDoesNotEnd, isAnswerCode, isKernelCode, kernelCode, lifecycleBusy, nothingAfter, reportDefect, OWN_NAME_FAILURES, OWN_START_REMEDY, herdrInstanceBusy, herdrInstanceRemoved, herdrSettingRemoved, HERDR_REMOVED } from "./errors.mjs";
60
62
  import { envRows, recordedTeams, teamsEnv } from "./teams.mjs";
61
63
  import { PANE_PATH_FIX, harnessNotOnPanePath, harnessUnavailable, launchConfigAmbiguous, launchConfigUnknown, launchConfigUnknownFix, launchLayers, launchPreferenceUnmatched, launchPreferenceUnmatchedProblem, launchReport, selectionFrom } from "./launch-preference.mjs";
@@ -727,7 +729,13 @@ export function instanceModulesRoot(dir) {
727
729
  * trusted by construction — a member capability by membership (decision 2), a
728
730
  * package capability by its declaration in the workspace's packages: (human
729
731
  * decision 2026-09-24: there is no package approval). The copy is the
730
- * instance's own. Nothing else is a capability this kernel runs. */
732
+ * instance's own. Nothing else is a capability this kernel runs.
733
+ *
734
+ * The trust decision is the workspace's declaration of the member or the
735
+ * package, made before spawn. This only checks provenance: that the manifest
736
+ * about to be used is a module copy made at spawn, and where it came from.
737
+ * It refuses no module copy, and the copy is in the home its agent can
738
+ * write, so it is no defence against that agent (docs/trust-model.md). */
731
739
  export function capabilityTrust(manifest) {
732
740
  if (!manifest) return { trusted: false, reason: "manifest missing" };
733
741
  if (!String(manifest._origin).startsWith("module:")) return { trusted: false, reason: `${manifest.capability} is not a workspace module copy` };
@@ -3440,12 +3448,12 @@ function callerSpawner(caller, io) {
3440
3448
  }
3441
3449
  }
3442
3450
  /** A soul name as a spawn names it, by shape only: a slug, after an optional `<package or member>/`
3443
- * and an optional `<package>--` (lib/instance-naming.mjs soulRole reads its role from the same). */
3451
+ * and an optional `<package>--`. */
3444
3452
  const SOUL_NAME_SHAPE = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*\/)?(?:[a-z0-9]+(?:-[a-z0-9]+)*--)?[a-z0-9]+(?:-[a-z0-9]+)*$/;
3445
- /** `oats instance suggest-name` (feature instance-suggest-name, awebai/oats#1490 §2): the name a spawn
3446
- * of `soul` would get by `--suggest-name`, chosen on THIS machine for a spawn that may land on another.
3447
- * `soul` is only a name (it gives the role) and needn't exist here: nothing resolves it. It resolves no
3448
- * souls, members, lock or remote: it reads only this machine's launch configurations (the
3453
+ /** `oats instance suggest-name` (feature instance-suggest-name, awebai/oats#1490 §2): the name a
3454
+ * `--suggest-name` spawn would get, chosen on THIS machine for a spawn that may land on another.
3455
+ * `soul` is optional and only shape-checked (installed Desktops send it): it doesn't change the name,
3456
+ * needn't exist here, and nothing resolves it. It resolves no souls, members, lock or remote: it reads only this machine's launch configurations (the
3449
3457
  * oats-local.yaml in reach of `dir`) and the OATS tmux server's environment, writes nothing and
3450
3458
  * reserves no name. The name is not made unique: the host the spawn lands on owns uniqueness
3451
3459
  * (E_INSTANCE_NAME_TAKEN at its apply). The harness: `harness`, else the configuration's, else claude;
@@ -3456,7 +3464,7 @@ const SOUL_NAME_SHAPE = /^(?:[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-
3456
3464
  * of `{ name?, naming }`, `name` only when `naming.source` is "suggested". A naming failure is never an
3457
3465
  * error (an executable that is not there is `harness-failed`); bad arguments are. */
3458
3466
  export async function suggestSpawnName({ dir = process.cwd(), soul, task, harness: asked, model: askedModel, launchConfig: named } = {}) {
3459
- if (typeof soul !== "string" || soul.length > 256 || !SOUL_NAME_SHAPE.test(soul)) throw oatsError("E_BAD_ARGS", `--soul ${JSON.stringify(soul)} is not a soul name (a slug, optionally qualified as <package>/<soul>)`);
3467
+ if (soul !== undefined && (typeof soul !== "string" || soul.length > 256 || !SOUL_NAME_SHAPE.test(soul))) throw oatsError("E_BAD_ARGS", `--soul ${JSON.stringify(soul)} is not a soul name (a slug, optionally qualified as <package>/<soul>)`);
3460
3468
  if (typeof task !== "string") throw oatsError("E_BAD_ARGS", "the task must be text");
3461
3469
  if (asked !== undefined && !LAUNCH_HARNESSES.includes(asked)) throw oatsError("E_BAD_ARGS", `--harness must be one of ${LAUNCH_HARNESSES.join("|")}`);
3462
3470
  if (askedModel !== undefined && (typeof askedModel !== "string" || !askedModel)) throw oatsError("E_BAD_ARGS", "--model needs a model id");
@@ -3496,7 +3504,7 @@ export async function suggestSpawnName({ dir = process.cwd(), soul, task, harnes
3496
3504
  const namingModel = preference === undefined || preference === NATIVE_DEFAULT_MODEL ? null : (harness === "pi" ? firstEntry(preference) : resolveModelPreference(preference, harness)) || null;
3497
3505
  const seam = Number(process.env.OATS_TEST_NAMING_TIMEOUT_MS);
3498
3506
  const call = {
3499
- soulName: soul, harness, bin, task, timeoutMs: seam > 0 ? seam : NAMING_TIMEOUT_MS,
3507
+ harness, bin, task, timeoutMs: seam > 0 ? seam : NAMING_TIMEOUT_MS,
3500
3508
  instanceModel: namingModel,
3501
3509
  env: () => launchEffectiveEnv({ base: process.env, configEnv: config?.env || {}, launch: launchEnv, harness }),
3502
3510
  taken: () => false,
@@ -3506,6 +3514,7 @@ export async function suggestSpawnName({ dir = process.cwd(), soul, task, harnes
3506
3514
  return suggestInstanceName(call);
3507
3515
  }
3508
3516
  export async function spawnInstanceAsync(root, agent, o = {}) {
3517
+ assertHostRunAdmission();
3509
3518
  const it = spawnBody(root, agent, o);
3510
3519
  let step = it.next();
3511
3520
  while (!step.done) {
@@ -4017,7 +4026,7 @@ function* spawnBody(root, agent, o = {}) {
4017
4026
  const left = o.preview === true ? preflightStarted + preflightBudgetMs - Date.now() : own, souls = deploymentSoulNames(root, o.prepared), homes = deploymentInstanceHomes(root);
4018
4027
  let windows;
4019
4028
  const suggestion = yield () => suggestInstanceName({
4020
- soulName: agent.name, harness, bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4029
+ harness, bin, instanceModel: model || null, task, timeoutMs: Math.min(own, left),
4021
4030
  env: () => launchEffectiveEnv({ base: process.env, configEnv: launchConfig?.env || {}, launch: expectedEnv, harness }),
4022
4031
  taken: (n) => homes.has(n) || souls.has(n) || (windows ??= oatsTmuxWindows(session)).includes(n),
4023
4032
  });
@@ -4148,6 +4157,7 @@ function* spawnBody(root, agent, o = {}) {
4148
4157
  // itself never with `recursive` — EEXIST means another spawn (a concurrent
4149
4158
  // apply of the same decision, or anything else) got here first, and this one
4150
4159
  // has touched nothing.
4160
+ assertHostRunAdmission();
4151
4161
  mkdirSync(dirname(home), { recursive: true });
4152
4162
  // 0700: the home holds the instance's identity keys, TASK.md and transcripts.
4153
4163
  try { mkdirSync(home, { mode: 0o700 }); }
@@ -5044,6 +5054,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
5044
5054
  promptDispatched = !!controller;
5045
5055
  let windowId;
5046
5056
 
5057
+ assertHostRunAdmission();
5047
5058
  const envHandoff = launchEnvHandoff(home, promptStartId, refs);
5048
5059
  try { windowId = tmuxOn(socket, ["new-window", "-P", "-F", controller ? LAUNCH_PANE_FORMAT : "#{window_id}", "-t", `=${session}:`, "-n", instance, "-c", home, envHandoff.wrap(windowCmd), ...markAgentPane(instance)], undefined, oatsWindowEnvironment()).trim(); }
5049
5060
  catch (e) { envHandoff.remove(); throw launchFailed("new-window", "the window command was refused", e); }
@@ -6941,6 +6952,7 @@ function resumePaneTarget(target, socket, output) {
6941
6952
  try { return { ...target, ...launchPaneTarget(socket, output) }; } catch { return null; }
6942
6953
  }
6943
6954
  export function startInstanceSession(home, o = {}) {
6955
+ assertHostRunAdmission();
6944
6956
  if (typeof home !== "string" || !isAbsolute(home)) throw oatsError("E_BAD_ARGS", "session start needs an absolute instance home");
6945
6957
  if (o.resume !== true) return startClaimed("start", home, o);
6946
6958
  // --resume (feature session-resume) runs the recorded launch as it is: a launch choice cannot go with it.
@@ -7527,6 +7539,7 @@ function startSession(home, o) {
7527
7539
  }
7528
7540
  checkRoots();
7529
7541
  recordEnv();
7542
+ assertHostRunAdmission();
7530
7543
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7531
7544
  promptDispatched = !!launchController;
7532
7545
  try {
@@ -7564,6 +7577,7 @@ function startSession(home, o) {
7564
7577
  launchController = makeLaunchController();
7565
7578
  checkRoots();
7566
7579
  recordEnv();
7580
+ assertHostRunAdmission();
7567
7581
  writeJsonAtomic(pendingPath, { id, target, command, model: model ?? null, startedAt, ...planExtra }, 0o600);
7568
7582
  promptDispatched = !!launchController;
7569
7583
  try {
@@ -9719,6 +9733,7 @@ export const READ_CLAIM_WHEN_UNWRITABLE = Symbol("oats.readClaimWhenUnwritable")
9719
9733
  * (claimWrite, unwritableCode): never the code, the words or the details of an answer. */
9720
9734
  export function claimHomeFor(verb, name, home, { waitMs = 0, [READ_CLAIM_WHEN_UNWRITABLE]: readInstead = false } = {}) {
9721
9735
  if (!CLAIM_VERBS.includes(verb)) throw new TypeError(`claimHomeFor: ${JSON.stringify(verb)} is not a verb that takes a home's claim (${CLAIM_VERBS.join(", ")})`);
9736
+ refuseHomeOfAnotherUser(verb, name, home);
9722
9737
  const lock = retireClaimPath(home);
9723
9738
  const refusals = lifecycleClaimRefusals(verb, name, home, lock);
9724
9739
  try {
package/lib/errors.mjs CHANGED
@@ -193,7 +193,7 @@ export const ifItDoesNotEnd = (what, at) => `if it does not end, ${checkHolderBy
193
193
  * after the verb's first effect is never answered (afterFirstEffect). The docs table of
194
194
  * docs/desktop-cli-api.md is checked against this constant, and a client's own set must lie
195
195
  * inside it (test/lifecycle-before-effect-codes.test.mjs). */
196
- const BEFORE_EFFECT = Object.freeze(["E_BAD_ARGS", "E_USAGE", "E_PLAN_STALE", "E_INSTANCE_RETIRING", "E_LIFECYCLE_BUSY", "E_HOME_MISMATCH", "E_SESSION_UNKNOWN",
196
+ const BEFORE_EFFECT = Object.freeze(["E_BAD_ARGS", "E_USAGE", "E_PLAN_STALE", "E_INSTANCE_RETIRING", "E_LIFECYCLE_BUSY", "E_HOME_MISMATCH", "E_HOME_NOT_OWNED", "E_SESSION_UNKNOWN",
197
197
  "E_AMBIGUOUS_INSTANCE", "E_UNIDENTIFIED_INSTANCE_HOME", "E_REMOTE_INCOMPATIBLE", "E_AMBIGUOUS", "E_SNAPSHOT_UNKNOWN"]);
198
198
  export const BEFORE_EFFECT_CODES = Object.freeze({ "instance stop": BEFORE_EFFECT, retire: BEFORE_EFFECT });
199
199
  /** The defect afterFirstEffect makes. Its name is on the prototype, so that it is in the stack's
@@ -0,0 +1,25 @@
1
+ // The kernel acts on a home only as the home's owner (docs/trust-model.md, rule 3).
2
+ import { statSync } from "node:fs";
3
+ import { oatsError } from "./errors.mjs";
4
+
5
+ /** The `oats` command each claim verb is typed as. */
6
+ const COMMAND = Object.freeze({ start: "session start", resume: "session start --resume", stop: "instance stop", retire: "retire", upgrade: "instance upgrade" });
7
+
8
+ /** Refuse `verb` on the home of instance `name` when the effective user does not own it.
9
+ * A lifecycle verb runs what the home contains (its hooks, its harness, the Git of its
10
+ * repositories), so run as another user it would lend that user's authority to whoever can
11
+ * write the home. Root is no exception: it is the case that matters most.
12
+ * Nothing is checked where the platform has no user ids. A home that cannot be read is left
13
+ * to the verb's own refusals. Throws E_HOME_NOT_OWNED, with `details` { instance, home,
14
+ * owner, user } (the two uids); it is thrown before the verb writes anything. The fix it
15
+ * names keeps the owner's HOME (`sudo -H`): OATS keeps its own state under it. */
16
+ export function refuseHomeOfAnotherUser(verb, name, home, { euid = process.geteuid?.(), stat = statSync } = {}) {
17
+ if (euid == null) return;
18
+ let owner;
19
+ try { owner = stat(home).uid; } catch { return; }
20
+ if (owner === euid) return;
21
+ const message = `Nothing was done: ${home} belongs to uid ${owner}, and this ${verb} of ${name} runs as uid ${euid}${euid === 0 ? " (root)" : ""}. `
22
+ + "OATS acts on a home only as its owner, because it runs what the home contains; root is no exception. "
23
+ + `Run the same command as that user, with that user's HOME: sudo -H -u '#${owner}' oats ${COMMAND[verb] ?? verb} …`;
24
+ throw Object.assign(oatsError("E_HOME_NOT_OWNED", message), { details: { instance: name, home, owner, user: euid } });
25
+ }
@@ -0,0 +1,21 @@
1
+ /** Private host-run child control, never an operator setting. A synchronous
2
+ * tick cannot receive IPC/signals while it waits for a command, so each new
3
+ * admission reads the fence the owning host run publishes before cancellation.
4
+ * Outside its private bootstrap there is no fence and ordinary CLI rules hold. */
5
+ import { readFileSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import { oatsError } from "./errors.mjs";
8
+
9
+ let fence = null;
10
+ const CHILD = fileURLToPath(new URL("./host-run-child.mjs", import.meta.url));
11
+ export function installHostRunFence(path) { fence = path; }
12
+ export function hostRunAdmissionOpen() {
13
+ if (fence === null) return true;
14
+ try { return readFileSync(fence, "utf8") === "open"; } catch { return false; }
15
+ }
16
+ export function assertHostRunAdmission() {
17
+ if (!hostRunAdmissionOpen()) throw oatsError("E_HOST_RUN_FAILED", "host run is stopping; no further launch was admitted");
18
+ }
19
+ /** Carry control only across kernel-owned launches, via the private entrypoint.
20
+ * No public flag or inherited environment variable gives another command control. */
21
+ export function hostRunChildArgs(bin, argv, group = false) { return fence === null ? [bin, ...argv] : [CHILD, bin, fence, group ? "group" : "member", ...argv]; }
@@ -0,0 +1,31 @@
1
+ /** Private bootstrap for a kernel child owned by host run. The leading control
2
+ * arguments are consumed here, never parsed as public CLI options. */
3
+ import { existsSync, renameSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { processStartToken } from "../packages/record/lib/process-identity.mjs";
7
+ import { pathToFileURL } from "node:url";
8
+ import { assertHostRunAdmission, installHostRunFence } from "./host-run-admission.mjs";
9
+ const [bin, fence, ownership, ...argv] = process.argv.slice(2);
10
+ if (!bin || !fence) throw new Error("host-run child requires its owner control");
11
+ installHostRunFence(fence);
12
+ if (ownership === "group" && process.platform !== "win32") {
13
+ // Register before importing any launch-capable code. An intermediate
14
+ // supervisor can be stopped or killed without orphaning an unowned launch.
15
+ const readOnly = argv.includes("--plan");
16
+ if (!readOnly) assertHostRunAdmission();
17
+ const start = processStartToken(process.pid);
18
+ if (!start) throw new Error("host-run child cannot establish its process identity");
19
+ const registration = join(dirname(fence), "groups", String(process.pid));
20
+ writeFileSync(`${registration}.new`, JSON.stringify({ pid: process.pid, processStart: start }), { mode: 0o600 });
21
+ renameSync(`${registration}.new`, registration);
22
+ const deadline = Date.now() + 5000;
23
+ while (!existsSync(`${registration}.owned`)) {
24
+ if (!readOnly) assertHostRunAdmission();
25
+ if (Date.now() >= deadline) throw new Error("host-run child ownership was not acknowledged");
26
+ await delay(10);
27
+ }
28
+ if (!readOnly) assertHostRunAdmission();
29
+ }
30
+ process.argv = [process.execPath, bin, ...argv];
31
+ await import(pathToFileURL(bin).href);
@@ -0,0 +1,150 @@
1
+ /** Host-run's owned child groups and private admission fence. The parent stays
2
+ * responsive while a synchronous tick runs. It keeps ownership until the
3
+ * children AND their groups have ended; a timeout is never proof of cleanup. */
4
+ import { spawn } from "node:child_process";
5
+ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { setTimeout as delay } from "node:timers/promises";
10
+ import { signalGroup } from "./process-group.mjs";
11
+ import { processLiveness } from "../packages/record/lib/process-identity.mjs";
12
+
13
+ const CHILD = fileURLToPath(new URL("./host-run-child.mjs", import.meta.url));
14
+ const instanceKeys = ["OATS_INSTANCE", "OATS_INSTANCE_HOME", "OATS_HOME", "PI_AGENT_INSTANCE", "PI_AGENT_HOME"];
15
+
16
+ /** Private process boundary. The optional durations shorten real subprocess
17
+ * tests; host run always uses 10 s natural grace and 5 s owned cancellation. */
18
+ export function hostRunWork({ kernel, env, naturalMs = 10_000, cancelMs = 5_000, say = () => {} }) {
19
+ const dir = mkdtempSync(join(tmpdir(), "oats-host-work-")), fence = join(dir, "admit");
20
+ writeFileSync(fence, "open", { mode: 0o600 });
21
+ const groups = join(dir, "groups");
22
+ mkdirSync(groups, { mode: 0o700 });
23
+ const childEnv = { ...env };
24
+ for (const key of instanceKeys) delete childEnv[key];
25
+ const owned = new Set();
26
+ let fenced = false, drained = null, quiescent = false;
27
+ const alive = (state) => {
28
+ if (state.empty) return false;
29
+ if (!state.child.pid) return !state.done;
30
+ if (process.platform === "win32") return !state.done;
31
+ try { process.kill(-state.child.pid, 0); return true; }
32
+ catch (e) { if (e.code === "ESRCH") { state.empty = true; return false; } return true; }
33
+ };
34
+ const signal = (state, sig) => {
35
+ if (!alive(state)) return;
36
+ if (process.platform === "win32") state.child.kill(sig);
37
+ else signalGroup(state.child, sig);
38
+ };
39
+ let ownershipError = null;
40
+ const registrations = new Map();
41
+ const discover = () => {
42
+ if (ownershipError) return;
43
+ for (const name of readdirSync(groups)) {
44
+ if (!/^[1-9][0-9]*$/.test(name) || registrations.has(name)) continue;
45
+ const path = join(groups, name);
46
+ let record;
47
+ try { record = JSON.parse(readFileSync(path, "utf8")); }
48
+ catch (e) { throw new Error(`host-run child ownership is unreadable (${e.code || "record"})`); }
49
+ if (String(record.pid) !== name || typeof record.processStart !== "string") throw new Error("host-run child ownership is invalid");
50
+ // No ACK until the still-live leader is verified. Before ACK the child
51
+ // imports no kernel work, so an already gone registrant has no effects.
52
+ const { state: live } = processLiveness(record);
53
+ if (live !== "alive") {
54
+ if (live === "gone") rmSync(path, { force: true });
55
+ continue;
56
+ }
57
+ const state = [...owned].find(s => s.child.pid === record.pid) ?? { child: { pid: record.pid }, done: true, empty: false };
58
+ owned.add(state);
59
+ registrations.set(name, state);
60
+ writeFileSync(`${path}.owned`, "owned", { mode: 0o600 });
61
+ }
62
+ };
63
+ let watch = null;
64
+ const pending = () => {
65
+ try { discover(); }
66
+ catch (e) { ownershipError = e; say(`child ownership failed: ${e.message}`); }
67
+ const active = [];
68
+ for (const state of owned) {
69
+ if (!state.done || alive(state)) active.push(state);
70
+ else owned.delete(state);
71
+ }
72
+ for (const [pid, state] of registrations) if (!owned.has(state)) {
73
+ registrations.delete(pid);
74
+ rmSync(join(groups, pid), { force: true });
75
+ rmSync(join(groups, `${pid}.owned`), { force: true });
76
+ }
77
+ if (!active.length && watch !== null) { clearInterval(watch); watch = null; }
78
+ return active;
79
+ };
80
+ const wait = async (until) => {
81
+ while (pending().length && Date.now() < until) await delay(10);
82
+ return pending().length === 0;
83
+ };
84
+ const run = (argv, { timeoutMs } = {}) => {
85
+ if (fenced && !argv.includes("--plan")) return Promise.resolve({ ok: false, error: { code: "E_HOST_RUN_FAILED", message: "host run is stopping; no further child was admitted" } });
86
+ return new Promise((resolve) => {
87
+ const state = { child: null, done: false, empty: false };
88
+ let timeout, escalation, interrupted = false;
89
+ const fail = (message) => ({ ok: false, error: { code: "E_HOST_RUN_FAILED", message } });
90
+ const chunks = [];
91
+ let size = 0, error = null;
92
+ state.child = spawn(kernel.execPath, [CHILD, kernel.bin, fence, "group", ...argv], {
93
+ env: childEnv, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"],
94
+ });
95
+ state.child.stdout.on("data", (chunk) => {
96
+ if (size + chunk.length <= 16 * 1024 * 1024) { size += chunk.length; chunks.push(chunk); }
97
+ else { interrupted = true; signal(state, "SIGKILL"); }
98
+ });
99
+ // Child diagnostics are not its JSON answer. Drain to prevent pipe backpressure.
100
+ state.child.stderr.resume();
101
+ state.child.once("error", (e) => { error = e; });
102
+ state.child.once("close", (_code, sig) => {
103
+ state.done = true;
104
+ clearTimeout(timeout); clearTimeout(escalation);
105
+ let answer;
106
+ try { answer = JSON.parse(Buffer.concat(chunks).toString("utf8").trim().split("\n").pop()); } catch { answer = undefined; }
107
+ resolve(!interrupted && answer && typeof answer === "object" ? answer : fail(`oats ${argv.join(" ")} ${interrupted ? "was cancelled" : `exited${sig ? ` on ${sig}` : error?.code ? ` (${error.code})` : ""} without an answer`}`));
108
+ });
109
+ owned.add(state);
110
+ watch ??= setInterval(pending, 25);
111
+ if (timeoutMs !== undefined) timeout = setTimeout(() => {
112
+ interrupted = true;
113
+ signal(state, "SIGTERM");
114
+ escalation = setTimeout(() => signal(state, "SIGKILL"), Math.min(1000, cancelMs));
115
+ }, timeoutMs);
116
+ });
117
+ };
118
+ const drain = () => drained ??= (async () => {
119
+ if (await wait(Date.now() + naturalMs)) return;
120
+ // Write before TERM: a synchronous tick resumes after an interrupted
121
+ // command before its deferred signal handler runs. It must not admit next.
122
+ writeFileSync(fence, "stop");
123
+ fenced = true;
124
+ say("launch grace expired: admissions fenced; cancelling owned work");
125
+ for (const state of pending()) signal(state, "SIGTERM");
126
+ const start = Date.now();
127
+ if (await wait(start + Math.min(3000, cancelMs))) return;
128
+ for (const state of pending()) signal(state, "SIGKILL");
129
+ if (await wait(start + cancelMs)) return;
130
+ say("owned work has not ended; retaining the host-run claim");
131
+ // An unkillable OS wait is the runtime's final failure boundary. Never
132
+ // release a claim or begin agent stops beside launch-capable survivors.
133
+ while (pending().length) await delay(25);
134
+ })();
135
+ const close = async () => {
136
+ await drain();
137
+ // Final read-only listings can have run after the admission drain.
138
+ if (pending().length) {
139
+ for (const state of pending()) signal(state, "SIGKILL");
140
+ while (pending().length) await delay(10);
141
+ }
142
+ // Only this postcondition permits claim release if later control-file
143
+ // cleanup reports an error. An earlier drain failure must keep the claim.
144
+ quiescent = true;
145
+ clearInterval(watch);
146
+ rmSync(dir, { recursive: true, force: true });
147
+ if (ownershipError) throw ownershipError;
148
+ };
149
+ return { run, drain, close, get quiescent() { return quiescent; } };
150
+ }
package/lib/host-run.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
  * - One host run per machine: the lock `host-run/lock` under OATS_HOME_DIR (default ~/.oats), taken
12
12
  * as the resume sweep takes its own (lib/dir-lock.mjs acquireDirLock): a claim that names its
13
13
  * holder by pid, process start and boot id. A lock whose holder is gone, or that was taken in
14
- * another boot (in a container, another run), is taken over at once; a holder that runs, and a
14
+ * another kernel boot, is taken over at once; a holder that runs, and a
15
15
  * lock that cannot be judged, are E_HOST_RUN_BUSY, `details` `{ lock, found }`.
16
16
  * - A run, in order: the lock; the resume sweep once (`oats session resume`); then, at second 0 of
17
17
  * each minute, `oats schedule tick --host` when the host schedule registry lists a scope (with
@@ -32,6 +32,7 @@ import { oatsError } from "./errors.mjs";
32
32
  import { hostUnitStatus } from "./schedule-host.mjs";
33
33
  import { readRegistry } from "./schedule.mjs";
34
34
  import { kernelAnswer, resumeSessions } from "./session-resume.mjs";
35
+ import { hostRunWork } from "./host-run-work.mjs";
35
36
  import { OUTCOME } from "./session-resume-contract.mjs";
36
37
  import { bootId, takenInAnotherBoot } from "./session-seen.mjs";
37
38
 
@@ -104,8 +105,9 @@ function sweepSaid(rows) {
104
105
  * `stopped` one row per home that ran when it stopped, in the listing's order (stopHome).
105
106
  *
106
107
  * On the signal, in this order: no minute is armed any more; a tick or a sweep that runs is
107
- * waited for (a tick's wake job starts a stopped home, so ticking ends before any home is
108
- * stopped); one listing; then every running home is stopped, side by side, each by a child of its
108
+ * given 10 s to finish, then new admissions are fenced and owned children are cancelled
109
+ * within a further 5 s (a tick's wake job may start a home, so owned work ends before any
110
+ * home is stopped); one bounded listing; then every running home is stopped, side by side, each by a child of its
109
111
  * own (lib/host-stop-child.mjs: the stop `oats session restart` and a retire use, its record
110
112
  * written first and asking for a resume, the harness given `stopGraceMs` and never escalated).
111
113
  * The next start's sweep resumes those homes.
@@ -119,7 +121,7 @@ function sweepSaid(rows) {
119
121
  export async function hostRun({
120
122
  kernel, env = process.env, boot = bootId(), hostStatus = hostUnitStatus,
121
123
  scopes = () => readRegistry().workspaces,
122
- run = (argv) => kernelAnswer({ ...kernel, env }, argv, { code: "E_HOST_RUN_FAILED", what: `oats ${argv.join(" ")}` }),
124
+ run,
123
125
  stopGraceMs = STOP_GRACE_MS,
124
126
  stopHome = async (home, graceMs) => {
125
127
  const answer = await kernelAnswer({ execPath: kernel.execPath, bin: STOP_CHILD, env }, [home, String(graceMs)], { code: "E_SESSION_STOP_FAILED", what: "the stop" });
@@ -138,8 +140,10 @@ export async function hostRun({
138
140
  const unit = hostStatus(), active = refuse.timer(unit);
139
141
  if (active) throw active;
140
142
  const release = acquireHostRunLock({ boot });
141
- let signal = null, disarm = null, stopListening = () => {};
143
+ let signal = null, disarm = null, stopListening = () => {}, work = null, draining = null;
142
144
  try {
145
+ work = run ? null : hostRunWork({ kernel, env, say });
146
+ const execute = run ?? work.run;
143
147
  const warnings = inactiveUnitWarnings(unit);
144
148
  const stopRequested = new Promise((requested) => {
145
149
  // The first signal ends the ticking at once: no minute is armed after it. A later one changes nothing.
@@ -147,6 +151,8 @@ export async function hostRun({
147
151
  if (signal) return;
148
152
  signal = received;
149
153
  disarm?.();
154
+ // Start the grace clock even while the initial sweep is awaited.
155
+ draining = work?.drain();
150
156
  requested();
151
157
  });
152
158
  });
@@ -154,7 +160,7 @@ export async function hostRun({
154
160
  for (const warning of warnings) say(`warning: ${warning}`);
155
161
 
156
162
  // The sweep, once: a home lost while this runs is a crash, and the sweep's bound is per boot.
157
- const swept = await run(["session", "resume", "--json"]);
163
+ const swept = await execute(["session", "resume", "--json"]);
158
164
  const sweep = swept?.ok === true ? swept.result : { error: { code: swept?.error?.code ?? "E_HOST_RUN_FAILED", message: swept?.error?.message ?? "no answer" } };
159
165
  say(swept?.ok === true ? `resume sweep: ${sweepSaid(sweep.rows ?? [])}` : `resume sweep failed ${failed(swept)}`);
160
166
 
@@ -162,7 +168,7 @@ export async function hostRun({
162
168
  // minute missed while this process did not run is never armed again.
163
169
  const ticks = { run: 0, skipped: 0, failed: 0, noScope: 0 };
164
170
  let ticking = null, listing = null, ticked;
165
- const list = () => run(["session", "resume", "--plan", "--json"]);
171
+ const list = (options) => execute(["session", "resume", "--plan", "--json"], options);
166
172
  const arm = () => { disarm = timer(minute, MINUTE - (now() % MINUTE)); };
167
173
  const minute = () => {
168
174
  if (signal) return;
@@ -178,7 +184,7 @@ export async function hostRun({
178
184
  else if (registered && ticking) { ticks.skipped += 1; say("tick skipped: the tick of the minute before still runs"); }
179
185
  else if (registered) {
180
186
  ticks.run += 1;
181
- ticking = run(["schedule", "tick", "--host", "--json"]).then((answer) => {
187
+ ticking = execute(["schedule", "tick", "--host", "--json"]).then((answer) => {
182
188
  ticking = null;
183
189
  if (answer?.ok !== true) { ticks.failed += 1; say(`tick failed ${failed(answer)}`); }
184
190
  });
@@ -195,10 +201,12 @@ export async function hostRun({
195
201
  if (!signal) arm();
196
202
  await stopRequested;
197
203
 
198
- // Ticking has ended. A tick that runs is waited for: its wake job may start a home.
204
+ // Ticking has ended. The signal started the bounded owned-work drain even
205
+ // when it arrived during the initial sweep. No launch may race agent stops.
199
206
  say(`${signal}: ticking ended`);
207
+ await draining;
200
208
  await Promise.all([ticking, listing]);
201
- const last = await list();
209
+ const last = await list({ timeoutMs: 3000 });
202
210
  if (last?.ok !== true) say(`listing failed ${failed(last)}: no instance is stopped`);
203
211
  const homes = last?.ok === true ? (last.result?.rows ?? []).filter((row) => row.outcome === OUTCOME.ALREADY_RUNNING && typeof row.home === "string").map((row) => row.home) : [];
204
212
  if (homes.length) say(`stopping ${plural(homes.length, "running instance")}, each given ${stopGraceMs / 1000} s`);
@@ -213,6 +221,7 @@ export async function hostRun({
213
221
  } finally {
214
222
  disarm?.();
215
223
  stopListening();
216
- release();
224
+ try { await work?.close(); }
225
+ finally { if (!work || work.quiescent) release(); }
217
226
  }
218
227
  }