@awebai/oats 0.62.0 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +14 -1
  2. package/bin/oats.mjs +58 -23
  3. package/docs/desktop-cli-api.md +73 -3
  4. package/docs/execution-targets.md +45 -2
  5. package/docs/first-team.md +6 -0
  6. package/docs/official-catalog.md +1 -1
  7. package/docs/packages.md +5 -5
  8. package/docs/release-lane.md +13 -0
  9. package/docs/release-notes/v0.63.0.md +135 -0
  10. package/docs/release-notes/v0.64.0.md +105 -0
  11. package/docs/souls-and-instances.md +32 -7
  12. package/docs/upgrading.md +6 -3
  13. package/docs/workspaces.md +1 -1
  14. package/lib/core.mjs +100 -28
  15. package/lib/session-input.mjs +12 -2
  16. package/lib/tree-copy.mjs +188 -7
  17. package/package-catalog.json +1 -1
  18. package/package.json +1 -1
  19. package/packages/client/cli-locator.mjs +2 -2
  20. package/packages/client/instance-tree.mjs +53 -3
  21. package/packages/client/roster-sections.mjs +22 -6
  22. package/packages/record/bin/capture.mjs +59 -17
  23. package/packages/record/bin/setup.mjs +2 -1
  24. package/packages/record/docs/capture-service.md +89 -5
  25. package/packages/record/lib/capture-command-operation.mjs +2 -2
  26. package/packages/record/lib/capture-command-output.mjs +3 -2
  27. package/packages/record/lib/capture-command.mjs +20 -3
  28. package/packages/record/lib/capture-hook-runner.mjs +1 -1
  29. package/packages/record/lib/capture-index-reset.mjs +1 -0
  30. package/packages/record/lib/capture-lock.mjs +67 -33
  31. package/packages/record/lib/capture-pass.mjs +22 -8
  32. package/packages/record/lib/capture-run.mjs +1 -1
  33. package/packages/record/lib/capture-service-runner.mjs +1 -1
  34. package/packages/record/lib/capture-supervisor.mjs +24 -5
  35. package/packages/record/lib/capture-work-session.mjs +7 -4
  36. package/packages/record/lib/capture-worker.mjs +20 -4
  37. package/packages/record/lib/derived-state.mjs +30 -2
  38. package/packages/record/lib/index-db.mjs +118 -49
  39. package/packages/record/lib/store.mjs +13 -6
  40. package/skills/oats-getting-started/SKILL.md +438 -170
@@ -0,0 +1,105 @@
1
+ # OATS 0.64.0
2
+
3
+ Unreleased
4
+
5
+ ## Upgrade
6
+
7
+ - **Install the Desktop first and the CLI second,** as
8
+ [Upgrading](../upgrading.md) says: a 0.63 Desktop refuses a 0.64.0 CLI. The
9
+ 0.64.0 Desktop accepts OATS CLIs `>=0.26.0 <0.65.0`.
10
+
11
+ - **The official catalog moves oats.framework 1.13.2 → 1.13.3** (oats.core
12
+ 2.6.5 and oats.setup 2.8.2, see Provider updates). The other packages are
13
+ unchanged. A deployment takes it by moving its `oats.framework` pin and
14
+ running `oats sync`. Only new spawns use it.
15
+
16
+ - **Coming from 0.61 or earlier:** do 0.62.0's Upgrade steps too (the capture
17
+ service's `oats setup`, once per user on each host, from that user's shell).
18
+
19
+ ## Changed
20
+
21
+ - **One way in: the README's "Start here" points to the
22
+ `oats-getting-started` skill**, which a person's own coding agent
23
+ downloads verbatim and follows ([#1314](https://github.com/awebai/oats/issues/1314)).
24
+ - **The skill is rewritten.** It asks one round of questions: the use case,
25
+ the existing repositories, the knowledge tools, new or existing
26
+ workspace, messaging, harness and deployment directory.
27
+ - **It installs what is missing,** then OATS Desktop and the CLI at the
28
+ same version (with the pi bridge, `@awebai/oats-pi`, when the harness is
29
+ pi). The Desktop comes from the release asset, downloaded with
30
+ `gh` and checked against `SHA256SUMS.txt` and its attestation; on Linux it
31
+ installs per user and shows in the app launcher.
32
+ - **The GitHub login** is gh's device flow, which the agent starts and the
33
+ person approves in their browser.
34
+ - **A new workspace** becomes a private repository holding the workspace
35
+ file, its membership and one thin soul,
36
+ `<workspace>-oats-setup-expert`, which holds `oats.setup` and has no
37
+ knowledge of its own, so it spawns on a machine before knowledge is set
38
+ up there. It takes the workspace's messaging, so it stays the
39
+ workspace's operator. **An existing workspace** is onboarded as it is;
40
+ when it has messaging, the skill sets it up on the machine before the
41
+ spawn, with an invite token the person types in their own terminal.
42
+ - **Then** the skill spawns the setup expert with the person's answers as
43
+ its task, and the expert does the rest (`/oats-setup-expert`,
44
+ oats.framework 1.13.0). An existing workspace without a setup soul gets
45
+ one first, from its owner, by pull request.
46
+ - The Desktop is started on the new deployment, and the TUI is offered.
47
+ - The person types only passwords, logins and tokens, and no secret passes through
48
+ the agent.
49
+
50
+ - `spawnOrigin` now describes the caller independently of lineage: valid
51
+ instance context in this deployment records `instance`; otherwise `operator`,
52
+ including operator spawns with `--parent`. Existing instances keep their
53
+ recorded values, whose older meaning followed the relation. Attribution is
54
+ informational and does not change permissions (#1371).
55
+
56
+ - Desktop: the command palette (⌘K / Ctrl+Shift+K) now shows the sidebar's
57
+ tree, with the sidebar's lines and state dots, ordered by the instance you
58
+ focused most recently. A group or a parent moves up when you focus any
59
+ instance under it, and a child stays under its parent. This replaces the
60
+ flat Recent group. The palette still opens on the agent you were on before,
61
+ and the sidebar keeps its own name order (#1383).
62
+
63
+ - **OATS Desktop accepts an `oats` CLI 0.64.x.** Its band is now
64
+ `>=0.26.0 <0.65.0`. 0.64 adds no new gate on the band: `spawnOrigin` keeps
65
+ its `instance`/`operator` values, which the Desktop passes through without
66
+ reading, and the Desktop already shows a fallback shell as `shell` (#1387).
67
+
68
+ ## Fixed
69
+
70
+ - Shared spawn help now lists the existing `--base <ref>` flag beside `--branch`
71
+ and explains its worktree-only scope and default to the soul commit observed
72
+ by spawn (#1370, #445).
73
+
74
+ - `oats spawn --help` and `oats help` now list the full existing spawn flag
75
+ inventory, including decision replay, scope, launch, child policy and wake
76
+ options, with compatibility and internal inputs labelled. Flag behavior is
77
+ unchanged (#1373).
78
+
79
+ - Status and session inspection now recognize a fallback shell when tmux
80
+ reports an empty or `unset` pane command, so a stopped harness no longer
81
+ appears to be running in that case (#1381).
82
+
83
+ ## Provider updates
84
+
85
+ - **oats.framework 1.13.3: oats.core 2.6.5 and oats.setup 2.8.2.** Text
86
+ only: neither capability's floor (`compatibility.oats`) changes.
87
+ - **`/oats-operate`** says what `spawnOrigin` records from OATS 0.64.0: the
88
+ caller's context (`instance` from a valid instance environment in this
89
+ deployment, otherwise `operator`), independent of the relation. It is
90
+ attribution, not a permission check, and a remote spawn records the
91
+ host side. The skill also says how `--branch` and `--base` choose a
92
+ worktree's branch and start point
93
+ ([#1371](https://github.com/awebai/oats/issues/1371),
94
+ [#1370](https://github.com/awebai/oats/issues/1370)).
95
+ - **oats.setup names the right OATS version for the getting-started entry
96
+ path.** `/oats-setup-expert`, `/oats-setup-model` and the oats.setup
97
+ briefing said the `oats-getting-started` skill writes the setup expert's
98
+ hand-over and creates its soul from OATS 0.62.0. That skill first ships
99
+ in 0.64.0, and they now say so
100
+ ([#1314](https://github.com/awebai/oats/issues/1314)).
101
+
102
+ ## Documentation
103
+
104
+ - `docs/first-team.md` opens with the getting-started skill as the quick
105
+ way; the page remains the manual path.
@@ -306,6 +306,12 @@ soul would, run it from the deployment with `OATS_INSTANCE_HOME` and
306
306
 
307
307
  ### Spawn
308
308
 
309
+ `oats spawn --help` lists the existing spawn flags and their conditions; the
310
+ spawn section of `oats help` contains the same inventory. Both work outside a
311
+ deployment. Compatibility and internal inputs are labelled, including the
312
+ locally refused legacy instance selector. For preview confirmation and receipt
313
+ replay, see the [spawn decision and apply contract](desktop-cli-api.md#the-decision).
314
+
309
315
  ```bash
310
316
  oats spawn release-manager --purpose cut-3.2 --task "…" # a soul of a confirmed member
311
317
  oats spawn release-manager --preview --json # decide everything, create nothing
@@ -384,8 +390,7 @@ Spawn lineage is **explicit** and relation-based:
384
390
  declares what the new instance IS to an existing one (`--parent <instance>` is
385
391
  sugar for `--relative-to <instance> --relation child`):
386
392
 
387
- - **child**: nests under the anchor: `parentInstance` = anchor,
388
- `spawnOrigin: instance`.
393
+ - **child**: nests under the anchor: `parentInstance` = anchor.
389
394
  - **parent**: the NEW instance becomes the anchor's parent: it inherits the
390
395
  anchor's old lineage slot, and the anchor's `instance.json` is re-pointed so
391
396
  its `parentInstance` is the new instance (a reviewer/maintainer of your work
@@ -400,15 +405,27 @@ sugar for `--relative-to <instance> --relation child`):
400
405
  when one exists; when the anchor is a root, the new instance records an
401
406
  explicit `siblingInstance` link so the cluster is still derivable from
402
407
  `oats status --json` (`parentInstance` + `siblingInstance` edges).
403
- - **unrelated** (default): no link, operator-origin, top-level.
408
+ - **unrelated** (default): no link, top-level.
404
409
 
405
410
  Attached-mode spawns are ALWAYS children of the owner of the shared work tree
406
411
  (the instance in whose home the tree is, as its `work/` or as one of its
407
412
  extra trees: see [`attached`](#attached--another-instances-tree)),
408
413
  because an attached agent serves that owner; relation flags other than a
409
- redundant child-of-owner are rejected. Any other spawn, including one from a
410
- shell that inherited an agent's environment variables, is operator-origin and
411
- appears top-level.
414
+ redundant child-of-owner are rejected.
415
+
416
+ `spawnOrigin` records the caller independently of these links. For new spawns
417
+ from OATS 0.64.0, it is `instance` when the caller's `OATS_INSTANCE` and/or
418
+ `OATS_INSTANCE_HOME` resolve consistently to an extant home in this deployment;
419
+ otherwise it is `operator`. A stopped home counts. A shell, Desktop or console
420
+ caller without that context records `operator` even with `--parent`; an instance
421
+ caller records `instance` even without a relation. A shell inheriting valid
422
+ instance context also records `instance`. This is informational attribution,
423
+ not a security boundary or a permission check. Existing instances keep their
424
+ recorded value, including the relation-based meaning recorded by older kernels.
425
+ For a remote spawn (`--server`), attribution uses the host-side caller context;
426
+ caller identity is not forwarded, so the origin is normally `operator`.
427
+ See [the caller resolution rules](desktop-cli-api.md#spawn-origin).
428
+
412
429
  Agents spawning sub-agents should pass `--parent "$OATS_INSTANCE"` (or the
413
430
  relation that fits).
414
431
 
@@ -570,7 +587,12 @@ parses it, so it copies the files Git reads:
570
587
  and `info/exclude`) and the settings that change what `git status` reports
571
588
  (`core.fileMode`, `core.ignoreCase`, `core.precomposeUnicode`,
572
589
  `core.symlinks`, `core.autocrlf`, `core.eol`);
573
- - the bytes and the permission bits of its files, Git metadata left out.
590
+ - the bytes and the permission bits of its files, Git metadata left out, and
591
+ each symbolic link as itself: its raw target and its own permission bits.
592
+ A link is recreated with its target and then given its source's mode with
593
+ lchmod, on the link, never on what it points at; a platform that cannot
594
+ set a link's mode (no lchmod) refuses the copy where the new link's mode
595
+ differs, rather than keep a copy that differs from its source.
574
596
 
575
597
  The rule is that the work is unchanged only if everything its copy would
576
598
  carry is equal byte for byte, and anything that cannot be compared exactly
@@ -1618,6 +1640,9 @@ as `--repo`, then `oats-local.yaml` `clones:`, then `<deployment>/<member name>`
1618
1640
  (`E_CLONE_MISSING` / `E_CLONE_MISMATCH` otherwise — see
1619
1641
  [configuration.md](configuration.md)).
1620
1642
 
1643
+ `--branch <b>` overrides the branch name; `--base <ref>` overrides its start
1644
+ point. These options apply to worktree mode.
1645
+
1621
1646
  The branch starts at the commit of the soul's repository that the spawn
1622
1647
  observed (the one it resolved the soul at), not at what the clone has checked
1623
1648
  out: the clone may be a human's checkout or a shared reference, far behind.
package/docs/upgrading.md CHANGED
@@ -89,9 +89,12 @@ For those released versions, follow their own Upgrade sections and the steps
89
89
  above. In particular, install the target Desktop before the CLI: the 0.61.0
90
90
  Desktop accepts CLIs `>=0.26.0 <0.62.0`, and a 0.60 Desktop refuses a 0.61.0 CLI.
91
91
 
92
- Service A ships in [0.62.0](release-notes/v0.62.0.md). Read its Upgrade
93
- section and keep this order: install the 0.62.0 Desktop first (it accepts CLIs
94
- `>=0.26.0 <0.63.0`), then the 0.62.0 CLI and matching pi bridge. Only **after
92
+ Service A ships in [0.62.0](release-notes/v0.62.0.md) and every later
93
+ release. Read 0.62.0's Upgrade section and keep this order: install the
94
+ Desktop of the release you upgrade to first (the 0.62.0 Desktop accepts CLIs
95
+ `>=0.26.0 <0.63.0`, the 0.63.0 Desktop `>=0.26.0 <0.64.0`, the 0.64.0
96
+ Desktop `>=0.26.0 <0.65.0`), then that
97
+ release's CLI and matching pi bridge. Only **after
95
98
  installing that CLI**, run its setup conversion once per user on each host,
96
99
  from that user's shell, then its health and doctor checks. That conversion is where an owned legacy
97
100
  watcher is replaced by the periodic service; foreign or disabled definitions
@@ -54,7 +54,7 @@ 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.13.1 # bare version → resolves through the official catalog
57
+ oats.framework: v1.13.3 # bare version → resolves through the official catalog
58
58
  oats.okf: v5.2.1
59
59
  acme.tools: git:github.com/acme/tools@v0.4.0 # outside the catalog → git:<repo>@<tag|OID>; still a package
60
60
 
package/lib/core.mjs CHANGED
@@ -83,7 +83,7 @@ export { exactTreeDigest, fingerprintTree, generatedWorkDigest, KERNEL_HOME_RECE
83
83
 
84
84
  import { canonicalJson, lineAt, parseStrictJson } from "./canonical-json.mjs";
85
85
  import { readPortableBytes } from "./bounded-read.mjs";
86
- import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes } from "./tree-copy.mjs";
86
+ import { copyTreeSafe, entriesAsBytes, joinBytes, pathBytes, treeDisagreement } from "./tree-copy.mjs";
87
87
  import { readAheadConsumed, readingAhead } from "./read-ahead.mjs";
88
88
  import { assertSameWorktreeHead, gitRead, gitRefPresence, gitRepoRead, gitRepoRun, headName, worktreeCommitUnreached, worktreeHead } from "./instance-git.mjs";
89
89
  import { systemTool } from "./system-tools.mjs";
@@ -3696,6 +3696,30 @@ export function spawnInstance(root, agent, o = {}) {
3696
3696
  function localMissingForSpawn(agent) {
3697
3697
  return oatsError("E_LOCAL_MISSING", `spawning ${agent?.name ?? "an instance"} needs a workspace deployment (oats-local.yaml, found walking up from the deployment): a soul's capabilities are the workspace's resolution, prepared before the spawn — \`oats onboard\` creates the deployment`);
3698
3698
  }
3699
+ /** Informational caller attribution, never permission or lineage. Only consistent
3700
+ * runtime identity evidence resolving to an extant home in this deployment counts;
3701
+ * a stopped home still counts. Invalid evidence must not refuse a spawn. */
3702
+ function callerSpawnOrigin(root) {
3703
+ const name = process.env.OATS_INSTANCE, home = process.env.OATS_INSTANCE_HOME;
3704
+ if (name === undefined && home === undefined) return "operator";
3705
+ try {
3706
+ if (name !== undefined && !INSTANCE_NAME_RE.test(name)) return "operator";
3707
+ if (home !== undefined && !isAbsolute(home)) return "operator";
3708
+ let matches;
3709
+ if (home === undefined) {
3710
+ matches = findInstanceHomes(root, name);
3711
+ if (matches.length !== 1) return "operator";
3712
+ }
3713
+ const canonical = realpathSync(home ?? matches[0].home);
3714
+ // Name lookup's immediate-child check also applies to the agents root: an
3715
+ // instances/ directory symlinked to another deployment cannot qualify it.
3716
+ if (basename(dirname(canonical)) !== "instances" || dirname(dirname(dirname(canonical))) !== realpathSync(root)) return "operator";
3717
+ const record = readHomeRecord(canonical);
3718
+ if (record.state !== "record" || record.meta.instance !== basename(canonical) || (name !== undefined && record.meta.instance !== name)) return "operator";
3719
+ matches ??= findInstanceHomes(root, record.meta.instance);
3720
+ return matches.some((m) => realpathSync(m.home) === canonical) ? "instance" : "operator";
3721
+ } catch { return "operator"; }
3722
+ }
3699
3723
  export async function spawnInstanceAsync(root, agent, o = {}) {
3700
3724
  const it = spawnBody(root, agent, o);
3701
3725
  let step = it.next();
@@ -3714,6 +3738,8 @@ function unconfirmedSpawn(error) {
3714
3738
  return error;
3715
3739
  }
3716
3740
  function* spawnBody(root, agent, o = {}) {
3741
+ // Capture the caller before target scaffolding or hooks supply the new instance's identity.
3742
+ const spawnOrigin = callerSpawnOrigin(root);
3717
3743
  if (!o.prepared) throw localMissingForSpawn(agent);
3718
3744
  const deliver = (r) => r;
3719
3745
  const work = o.work || agent.work || "checkout";
@@ -3845,12 +3871,8 @@ function* spawnBody(root, agent, o = {}) {
3845
3871
  // never leaves a half-created home behind. ATTACHED mode is special by design
3846
3872
  // decision: an attached agent shares its owner's work tree and is ALWAYS the
3847
3873
  // owner's child — relation flags that say anything else are contradictory and
3848
- // rejected. Ambient env
3849
- // (OATS_INSTANCE) is deliberately NOT consulted: any shell
3850
- // opened inside an agent's tmux window inherits those vars, and env inheritance
3851
- // is not evidence of intent — human spawns from such shells were misattributed
3852
- // as instance-origin. Manual spawns land top-level unless a relation is
3853
- // explicitly given (operator directive).
3874
+ // rejected. Caller identity is attribution only: it never supplies a lineage
3875
+ // edge. Without an explicit relation a spawn stays top-level.
3854
3876
  const legacyParent = typeof o.parent === "string" && o.parent.trim() ? o.parent.trim() : undefined;
3855
3877
  let relation = typeof o.relation === "string" && o.relation.trim() ? o.relation.trim() : undefined;
3856
3878
  let relativeTo = typeof o.relativeTo === "string" && o.relativeTo.trim() ? o.relativeTo.trim() : undefined;
@@ -4900,7 +4922,7 @@ ${task.trim() ? `\n## Task\n\n${task.trim()}\n` : "\nNo task was provided at spa
4900
4922
  siblingInstance: siblingInstance && siblingInstance !== instance ? siblingInstance : undefined,
4901
4923
  relation: relation || undefined,
4902
4924
  relativeTo: relation ? relativeTo : undefined,
4903
- spawnOrigin: relation || (parentInstance && parentInstance !== instance) ? "instance" : "operator",
4925
+ spawnOrigin,
4904
4926
  policy: { childSpawns: ownChildPolicy },
4905
4927
  ...(triggerEventFile ? { trigger: { id: o.triggerEvent.trigger, key: o.triggerEvent.key ?? null, source: o.triggerEvent.source, repo: o.triggerEvent.repo ?? null, number: o.triggerEvent.number ?? null, subject: o.triggerEvent.subject ?? null, url: o.triggerEvent.url ?? null, event: o.triggerEvent.event, headSha: o.triggerEvent.headSha ?? null, observedAt: o.triggerEvent.observedAt ?? null, eventFile: triggerEventFile,
4906
4928
  // A capability source's event carries its declared fields (a pull request's never does).
@@ -6129,6 +6151,26 @@ export function statusDisagreement(sourceStatus, recoveredStatus, cap = STATUS_D
6129
6151
  const paths = [...new Set([...a.keys(), ...b.keys()])].filter((p) => a.get(p) !== b.get(p)).sort();
6130
6152
  return { rows: paths.slice(0, cap).map((path) => ({ path, source: a.get(path) ?? null, recovery: b.get(path) ?? null })), total: paths.length };
6131
6153
  }
6154
+ const RECOVERY_DISAGREEMENT_SHOWN = 5;
6155
+ /** The refusal of a copy whose exact digest is not its source's (`what`), with where the two differ
6156
+ * now (treeDisagreement, read with the same `excludePaths`) as `recoveryDisagreement`, and the first
6157
+ * of those in the message. The digest comparison has refused already; this reading only says where
6158
+ * to look, and its `basis: "current"` says that it is the source as it is now, not the bytes the
6159
+ * comparison recorded. Exported for its test. */
6160
+ export function recoveryDisagreed(what, source, copy, excludePaths) {
6161
+ const diff = treeDisagreement(source, copy, { excludePaths });
6162
+ const shown = diff.entries.slice(0, RECOVERY_DISAGREEMENT_SHOWN).map((d) => `${d.path} (${d.kind})`).join("; ");
6163
+ const more = diff.entries.length > RECOVERY_DISAGREEMENT_SHOWN ? `; and ${diff.entries.length - RECOVERY_DISAGREEMENT_SHOWN} more` : "";
6164
+ const unfinished = diff.complete ? "" : `${shown ? "; " : ""}the search stopped (${diff.stoppedBy})`;
6165
+ const found = shown || unfinished ? `${shown}${more}${unfinished}` : "no difference between the current source and the copy";
6166
+ return Object.assign(new Error(`${what}; where they differ now (diagnostic only): ${found}`), { recoveryDisagreement: { basis: "current", ...diff } });
6167
+ }
6168
+ /** The details of E_WORK_PRESERVATION_FAILED for `e`: the disagreements it carries, beside `home`.
6169
+ * Exported for its test. */
6170
+ export function preservationDetails(home, e) {
6171
+ if (!e.statusDisagreement && !e.recoveryDisagreement) return undefined;
6172
+ return { home, ...(e.statusDisagreement ? { statusDisagreement: e.statusDisagreement } : {}), ...(e.recoveryDisagreement ? { recoveryDisagreement: e.recoveryDisagreement } : {}) };
6173
+ }
6132
6174
  /** Refuse a recovery whose Git status is not the source's, naming the differing rows (capped). */
6133
6175
  function assertStatusAgrees(source, recovered, what, repo) {
6134
6176
  const sourceStatus = worktreeStatus(source), recoveredStatus = worktreeStatus(recovered);
@@ -6615,16 +6657,40 @@ function runtimeAuthorityOf(baseline) {
6615
6657
  return { launched: true, tmux: { session: tmux.session, window: tmux.window, socket: resolve(tmux.socket) } };
6616
6658
  }
6617
6659
 
6618
- /** instance.json's tmux endpoint is the one the independent receipt authorises. */
6619
- function tmuxEndpointAgrees(meta, authority) {
6620
- return meta.tmux?.session === authority.tmux?.session && meta.tmux?.window === authority.tmux?.window && resolve(meta.tmux?.socket || ".") === authority.tmux?.socket;
6660
+ /** The fields of instance.json's tmux endpoint that differ from the one the independent receipt
6661
+ * authorises, as fixed labels in a fixed order: `tmux.session`, `tmux.window`, `tmux.socket`. */
6662
+ function tmuxEndpointDifferences(meta, authority) {
6663
+ return [
6664
+ ...(meta.tmux?.session === authority.tmux?.session ? [] : ["tmux.session"]),
6665
+ ...(meta.tmux?.window === authority.tmux?.window ? [] : ["tmux.window"]),
6666
+ ...(resolve(meta.tmux?.socket || ".") === authority.tmux?.socket ? [] : ["tmux.socket"]),
6667
+ ];
6621
6668
  }
6669
+ /** instance.json's tmux endpoint is the one the independent receipt authorises. */
6670
+ function tmuxEndpointAgrees(meta, authority) { return tmuxEndpointDifferences(meta, authority).length === 0; }
6622
6671
 
6672
+ /** Whether a blocked or incomplete launch prompt explains metadata's `launched: false` beside a
6673
+ * launched receipt. */
6674
+ function promptRetained(meta, authority) {
6675
+ return authority.launched === true && meta.launched === false && ["blocked", "incomplete"].includes(meta.launchPrompts?.status);
6676
+ }
6623
6677
  /** A blocked prompt is a retained runtime, not evidence that no process exists.
6624
6678
  * The independent launched receipt and exact endpoint agreement remain mandatory. */
6625
6679
  function launchStateAgrees(meta, authority) {
6626
- return meta.launched === authority.launched || (authority.launched === true && meta.launched === false &&
6627
- ["blocked", "incomplete"].includes(meta.launchPrompts?.status) && tmuxEndpointAgrees(meta, authority));
6680
+ return meta.launched === authority.launched || (promptRetained(meta, authority) && tmuxEndpointAgrees(meta, authority));
6681
+ }
6682
+
6683
+ /** The refusal for instance.json that disagrees with the independent receipt. `details.fields` names
6684
+ * what differs, from a fixed vocabulary in a fixed order: `launched` (unless a blocked or incomplete
6685
+ * launch prompt explains metadata's `launched: false`), then, for a launched receipt, each differing
6686
+ * tmux endpoint field. Labels only: never a path, a value or the receipt. Callers throw it only once
6687
+ * their own comparison has refused, so these labels diagnose a refusal and never decide one. */
6688
+ function authorityMismatch(message, meta, authority) {
6689
+ const fields = [
6690
+ ...(meta.launched === authority.launched || promptRetained(meta, authority) ? [] : ["launched"]),
6691
+ ...(authority.launched ? tmuxEndpointDifferences(meta, authority) : []),
6692
+ ];
6693
+ return Object.assign(oatsError("E_RUNTIME_AUTHORITY_MISMATCH", message), { details: { fields } });
6628
6694
  }
6629
6695
 
6630
6696
  /** The refusal for a home whose session receipt is at neither key its path gives (findRetirementBaseline):
@@ -6658,20 +6724,23 @@ function instanceSessionTarget(home) {
6658
6724
  if (!isPlainObject(meta)) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `cannot read ${recordPath}: it holds no JSON object`);
6659
6725
  const authority = baseline.version === RETIRE_BASELINE_VERSION && receiptRecordsHome(baseline, canonicalHomePath(home)) && runtimeAuthorityOf(baseline);
6660
6726
  if (!authority) throw oatsError("E_RUNTIME_ENDPOINT_UNKNOWN", `independent session receipt is missing or invalid for ${home}`);
6661
- if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", "instance metadata disagrees with independent session receipt");
6727
+ if (!launchStateAgrees(meta, authority) || (authority.launched && !tmuxEndpointAgrees(meta, authority))) throw authorityMismatch("instance metadata disagrees with independent session receipt", meta, authority);
6662
6728
  return { home, target: authority.launched ? { backend: "tmux", ...authority.tmux } : undefined };
6663
6729
  }
6664
6730
 
6665
- export function inspectInstanceSession(home) {
6666
- if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", waitingOnYou: null };
6731
+ /** `io` (`{ exec }`) is the tmux and process-table seam inspectSessionTarget takes. */
6732
+ export function inspectInstanceSession(home, { io } = {}) {
6733
+ if (typeof home === "string" && isAbsolute(home) && !existsSync(home)) return { home: realPathOrNearest(home), backend: null, present: false, state: "stopped", running: false, waitingOnYou: null };
6667
6734
  const s = instanceSessionTarget(home);
6668
- if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", waitingOnYou: null };
6735
+ if (!s.target) return { home: s.home, backend: null, present: false, state: "not-launched", running: false, waitingOnYou: null };
6669
6736
  let observed;
6670
- try { observed = inspectSessionTarget(s.target, undefined, { includeSize: true }); }
6737
+ try { observed = inspectSessionTarget(s.target, io, { includeSize: true }); }
6671
6738
  // The tmux failure stays the cause: sessionServerGone judges it.
6672
6739
  catch (e) { throw Object.assign(oatsError("E_SESSION_UNAVAILABLE", `cannot inspect session: ${e.message}`), { cause: e }); }
6673
- // Feature waiting-on-you: beside `state`, whose enum is unchanged.
6674
- return { home: s.home, ...observed, waitingOnYou: harnessRunning(observed) ? liveWaiting(s.home) : null };
6740
+ // Features session-inspect-running and waiting-on-you: beside `state`, whose enum is unchanged.
6741
+ // `running` is status's own liveness predicate over this observation, never a second reading.
6742
+ const running = harnessRunning(observed);
6743
+ return { home: s.home, ...observed, running, waitingOnYou: running ? liveWaiting(s.home) : null };
6675
6744
  }
6676
6745
  /** Whether an observed session runs a harness: present, and neither a
6677
6746
  * fallback shell nor a dead pane. Only such a session can be waiting on a human. */
@@ -7497,8 +7566,10 @@ export function startInstanceSession(home, o = {}) {
7497
7566
  // Reconcile even an exited target: the independent baseline may
7498
7567
  // already name it while metadata still names the old allocation.
7499
7568
  // The adopted start's session boundary, at its launch time, completed
7500
- // in whichever log the interrupted start did not record it.
7501
- recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: pending.launch?.launchConfig ?? meta.launch?.launchConfig ?? null, phase: "recovered" });
7569
+ // in whichever log the interrupted start did not record it. The receipt's
7570
+ // recipe names its configuration (null: the bare harness); only a receipt
7571
+ // without a recipe falls back to the recorded one.
7572
+ recordStartBoundary(realHome, { startId: pending.id, startedAt: pending.startedAt, harness: pending.harness ?? meta.harness ?? null, backend: "tmux", launchConfig: (pending.launch ? pending.launch.launchConfig : meta.launch?.launchConfig) ?? null, phase: "recovered" });
7502
7573
  const done = record(meta, { ...pending, model: pending.model ?? undefined, reused: "adopted" }, !st.present || st.state === "shell");
7503
7574
  // The adopted target is on another server than the home recorded (the start that allocated it
7504
7575
  // could not record it): this adoption records it, and says so once, here.
@@ -7693,7 +7764,7 @@ export function startInstanceSession(home, o = {}) {
7693
7764
  // end and wait, bounded. A harness still there afterwards is reported
7694
7765
  // as running; nothing is escalated and nothing is launched.
7695
7766
  stopReceipt = stopHarness(target, { graceMs: o.stopGraceMs ?? 20000, io: o.io, kill: o.io?.kill, sleep: o.io?.sleep });
7696
- writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe?.launchConfig ?? meta.launch?.launchConfig ?? null, model: model ?? null } }, 0o600);
7767
+ writeJsonAtomic(join(realHome, ".oats-restart.json"), { instance: meta.instance, at: new Date().toISOString(), stop: stopReceipt, next: { harness: launchPlan?.harness || harness, launchConfig: launchPlan?.recipe.launchConfig ?? null, model: model ?? null } }, 0o600);
7697
7768
  appendEvent(realHome, { kind: stopReceipt.exited ? "restarted" : "stop-refused", data: { phase: "restart-stop", signal: stopReceipt.signal, waitedMs: stopReceipt.waitedMs, stillRunning: stopReceipt.stillRunning ?? [] } });
7698
7769
  if (!stopReceipt.exited) throw oatsError("E_SESSION_STOP_FAILED", `${meta.instance} was asked to stop (${stopReceipt.signal} to ${stopReceipt.requested.map((r) => `${r.comm} pid ${r.pid}`).join(", ")} at ${stopReceipt.sentAt}) and was still running after ${stopReceipt.waitedMs} ms (${stopReceipt.state}); nothing was escalated and nothing was started; stop it yourself, or retry with a longer --stop-grace. Receipt: ${join(realHome, ".oats-restart.json")}`);
7699
7770
  try { state = inspectSessionTarget(target, o.io); }
@@ -7794,7 +7865,8 @@ export function startInstanceSession(home, o = {}) {
7794
7865
  // The session exists: its boundary (lib/instance-events.mjs) is recorded
7795
7866
  // now, before the metadata, so a start whose metadata write fails still
7796
7867
  // voids the claims of the session it replaced; its adoption only completes a log it missed.
7797
- recordStartBoundary(realHome, { startId: id, startedAt, harness: launchPlan?.harness || harness, backend: "tmux", launchConfig: launchPlan?.recipe?.launchConfig ?? meta.launch?.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
7868
+ // The planned recipe names the configuration (null: the bare harness), never the recorded recipe's.
7869
+ recordStartBoundary(realHome, { startId: id, startedAt, harness: launchPlan?.harness || harness, backend: "tmux", launchConfig: launchPlan?.recipe.launchConfig ?? null, phase: o.restart ? "restart" : "start" });
7798
7870
  // Keep launch evidence until the command exits or the target disappears.
7799
7871
  // A transient child (for example the native-start recorder) is not proof that startup
7800
7872
  // has finished. A later start reconciles the receipt without a watcher.
@@ -9118,7 +9190,7 @@ function copyRecoveryWork(observation, meta, parent, { rereadSource = true } = {
9118
9190
  let sourceBytes, gitPaths;
9119
9191
  if (observation.worktree) { sourceBytes = observedWorkBytes(observation); gitPaths = observation.workGitPaths ?? worktreeGitPaths(observation.work); }
9120
9192
  else { gitPaths = worktreeGitPaths(observation.work); sourceBytes = worktreeBytes(observation.work, gitPaths); }
9121
- if (sourceBytes !== worktreeBytes(recoveredRepo, gitPaths)) throw new Error("worktree recovery verification disagreed with the source");
9193
+ if (sourceBytes !== worktreeBytes(recoveredRepo, gitPaths)) throw recoveryDisagreed("worktree recovery verification disagreed with the source", observation.work, recoveredRepo, gitPaths);
9122
9194
  assertStatusAgrees(observation.work, recoveredRepo, "recovered Git index/status disagreed with the source", ".");
9123
9195
  }
9124
9196
  // The proof of the copy: its HEAD is the commit the worktree has checked
@@ -9237,7 +9309,7 @@ function writeRetirementRecovery(observation, meta, instance, phase) {
9237
9309
  } catch (e) {
9238
9310
  const left = removeStaging(staging);
9239
9311
  if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
9240
- const details = e.statusDisagreement ? { home: observation.home, statusDisagreement: e.statusDisagreement } : undefined;
9312
+ const details = preservationDetails(observation.home, e);
9241
9313
  throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${observation.home}; recovery could not be verified: ${e.message}${left ?? ""}`, details), details ? { details } : {});
9242
9314
  }
9243
9315
  }
@@ -9323,7 +9395,7 @@ function completeRetirementRecovery({ receipt, manifest }, before, after, meta)
9323
9395
  } catch (e) {
9324
9396
  const left = staging ? removeStaging(staging) : null;
9325
9397
  if (unreadableHeads.has(e)) { if (left) e.message += left; throw e; }
9326
- const details = e.statusDisagreement ? { home: after.home, statusDisagreement: e.statusDisagreement } : undefined;
9398
+ const details = preservationDetails(after.home, e);
9327
9399
  throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `retirement work remains at ${after.home}; recovery could not be verified: ${e.message}${left ?? ""}`, details), details ? { details } : {});
9328
9400
  }
9329
9401
  }
@@ -10328,7 +10400,7 @@ function retireSteps(root, name, o, found, at) {
10328
10400
  if (runtimeAuthority) {
10329
10401
  const metaAgrees = launchStateAgrees(meta, runtimeAuthority) && (!runtimeAuthority.launched || tmuxEndpointAgrees(meta, runtimeAuthority));
10330
10402
  if (!metaAgrees) {
10331
- throw oatsError("E_RUNTIME_AUTHORITY_MISMATCH", `cannot quiesce ${name}: mutable instance metadata disagrees with independent runtime endpoint authority`);
10403
+ throw authorityMismatch(`cannot quiesce ${name}: mutable instance metadata disagrees with independent runtime endpoint authority`, meta, runtimeAuthority);
10332
10404
  }
10333
10405
  }
10334
10406
  // The plan's promise about recorded children (`o.children`, computed the way
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
5
5
  import { performance } from "node:perf_hooks";
6
6
 
7
7
  const shells = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "login"]);
8
+ const isShellProcess = (name) => shells.has(basename(name).replace(/^-/, ""));
8
9
  function tmux(target, args, { exec = execFileSync, input, timeout = 10000, killSignal } = {}) {
9
10
  // launchd does not supply a UTF-8 locale. In that environment tmux replaces
10
11
  // the tab delimiters in list-panes output with underscores unless forced.
@@ -55,7 +56,16 @@ export function createSessionPaneInspector(io) {
55
56
  throw new Error("invalid tmux pane response");
56
57
  }
57
58
  let state = dead === "1" ? "stopped" : "unknown";
58
- if (dead === "0" && shells.has(command)) {
59
+ let shell = shells.has(command);
60
+ if (dead === "0" && (command === "" || command === "unset") && /^\d+$/.test(panePid)) {
61
+ // A missing tmux label can still be a fallback shell. Only the pane's
62
+ // own comm can establish that; an optional failed read stays unknown.
63
+ try {
64
+ const own = readProcesses().find(([, pid]) => pid === panePid);
65
+ shell = own ? isShellProcess(own[3]) : false;
66
+ } catch { /* missing process information is not proof of a fallback shell */ }
67
+ }
68
+ if (dead === "0" && shell) {
59
69
  // macOS tmux can report the wrapper shell while the harness is its child.
60
70
  // Only a shell with no non-shell descendants is a fallback prompt.
61
71
  if (!/^\d+$/.test(panePid)) throw new Error("tmux returned no pane process id");
@@ -67,7 +77,7 @@ export function createSessionPaneInspector(io) {
67
77
  for (const [, pid, parent, name] of processes) {
68
78
  if (descendants.has(parent) && !descendants.has(pid)) {
69
79
  descendants.add(pid); changed = true;
70
- if (!shells.has(basename(name).replace(/^-/, ""))) active = true;
80
+ if (!isShellProcess(name)) active = true;
71
81
  }
72
82
  }
73
83
  }