@awebai/oats 0.56.0 → 0.57.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.
@@ -106,6 +106,21 @@ function sessionFacts(home) {
106
106
  try { const s = inspectInstanceSession(home); return { state: s.state, present: s.present, backend: s.backend ?? null, established: true }; }
107
107
  catch (e) { return { state: "unestablished", present: null, backend: null, established: false, reason: kernelCode(e, "E_SESSION_UNAVAILABLE") }; }
108
108
  }
109
+ /** The instances attached to `tree`, a tree of the home of the instance `name` under `root` (its
110
+ * `work/` or an extra tree; #964) → [{ instance, home, session }]. `session` is the session as a
111
+ * stop plan reads it (sessionFacts), in one word: "running", "stopped", or "unknown" when it could
112
+ * not be established, which is never taken for stopped. Who is looked at: the recorded
113
+ * descendants of `name`, as a plan lists them, and the instances that record `name` as their
114
+ * parent under a name that is not unique (a plan's `ambiguous`). Lineage does not make an
115
+ * instance attached: its `work` link does (core attachedWorkLink), so these are read too. For
116
+ * `oats worktree remove`, which removes a tree under nobody's running session. Read-only. */
117
+ export function attachedToTree(root, name, tree) {
118
+ const kids = descendantsOf(root, name);
119
+ return [...kids, ...(kids.ambiguous || [])].filter((c) => attachedWorkLink(c.home, tree) !== null).map((c) => {
120
+ const s = sessionFacts(c.home);
121
+ return { instance: c.instance, home: c.home, session: running(s) ? "running" : s.established ? "stopped" : "unknown" };
122
+ });
123
+ }
109
124
  /** Retire's view of a home without its session receipt (before 0.25.9): the
110
125
  * retirement needs only absence, which it can observe — `{state: "absent",
111
126
  * present: false, established: true, note}`; live or ambiguous stays
@@ -353,21 +368,31 @@ function fitParts(render, parts) {
353
368
 
354
369
  /** A retire plan's note for one extra tree (core extraWorktreePlan row). Too long for the Desktop, its
355
370
  * longest parts go to the plan JSON, longest first; the tree's path stays whole, or the note says it
356
- * is too long and where it is. */
357
- function extraWorktreeNote(t) {
371
+ * is too long and where it is. `attached`: the names of the recorded children whose work is this
372
+ * tree (#964). The note names them and says what the retire leaves each with: its link repointed to
373
+ * the tree where it is re-homed, or pointing at a path that is gone where the tree is removed. A
374
+ * tree the retire refuses is neither moved nor removed, and nothing is said of them. `others`: the
375
+ * names of the instances attached to it that the plan lists under `ambiguous`. The retire does not
376
+ * act on them, and the note says what that leaves them with, in a clause of its own. */
377
+ function extraWorktreeNote(t, attached = [], others = []) {
378
+ const said = t.disposition !== "refuse";
379
+ const kids = attached.length && said ? (p) => `; attached child instance(s) ${p.kids} use it as their work, and ${t.disposition === "remove" ? "their work link would then point at a path that is gone" : "the retire repoints their work link to it"}` : () => "";
380
+ const rest = others.length && said ? (p) => `; attached instance(s) ${p.others}, listed under ambiguous, use it as their work: ${t.disposition === "remove" ? "the retire does not stop them, and their work link would then point at a path that is gone" : `the retire neither stops them nor repoints their work link, which would then point at a path that is gone (the tree would be at ${p.movedTo})`}` : () => "";
358
381
  const parts = {
382
+ ...(attached.length ? { kids: [listWithin(attached, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(attached.length), `${attached.length} of the recorded children`] } : {}),
383
+ ...(others.length ? { others: [listWithin(others, (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? String(others.length), `(${others.length} of them)`] } : {}),
359
384
  at: [t.branch ? `branch ${t.branch}` : t.detachedAt ? `detached at ${t.detachedAt.slice(0, 12)}` : "a HEAD that could not be read", `its HEAD: see ${SEE_EXTRA}`],
360
385
  repo: [t.repo, `its repository (see ${SEE_EXTRA})`],
361
386
  movedTo: [t.movedTo, `the path ${SEE_EXTRA} names`],
362
387
  reason: [t.reason, `${SEE_EXTRA} says why`],
363
388
  };
364
- const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}`
365
- : t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}`
389
+ const render = (p) => t.disposition === "remove" ? `extra worktree ${t.path} (${p.at}) is clean and would be removed; its branch and commits stay in ${p.repo}${kids(p)}${rest(p)}`
390
+ : t.disposition === "retain" ? `extra worktree ${t.path} (${p.at}) would be re-homed to ${p.movedTo}: ${p.reason}${kids(p)}${rest(p)}`
366
391
  : `extra worktree ${t.path} (${p.at}): retire refuses, ${p.reason}`;
367
392
  const note = fitParts(render, parts);
368
393
  if (note !== null) return note;
369
394
  const outcome = t.disposition === "remove" ? "would be removed" : t.disposition === "retain" ? "would be re-homed" : "makes retire refuse";
370
- return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it`;
395
+ return `an extra worktree whose path is too long for this note ${outcome}; ${SEE_EXTRA} lists it${kids({ kids: `${attached.length} of the recorded children` })}${rest({ others: `(${others.length} of them)`, movedTo: `the path ${SEE_EXTRA} names` })}`;
371
396
  }
372
397
  /** The plan's note when the worktree is not on the recorded branch: both names, or, too long for the
373
398
  * note, pointers to the plan JSON fields that hold them. */
@@ -445,13 +470,22 @@ export function planRetire(ctx, root, name, { home } = {}) {
445
470
  const repoFromGit = ownTree && !meta.repo ? workIs.tree?.repo ?? null : null;
446
471
  // Attached children whose work is this home's work/ (#718): a retire that keeps the worktree
447
472
  // repoints them to it. One note holds whatever the dialog then picks.
448
- const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, me.home) !== null) : [];
473
+ const attached = ownTree ? kids.filter((c) => attachedWorkLink(c.home, join(me.home, "work")) !== null) : [];
474
+ // The instances attached to a tree of this home that record it as their parent under a name that
475
+ // is not unique (`ambiguous`): the retire does not act on them, so each tree's note says what the
476
+ // retire leaves them with (#964). Lineage does not make an instance attached: its link does.
477
+ const attachedAmbiguous = (tree) => (kids.ambiguous || []).filter((c) => attachedWorkLink(c.home, tree) !== null);
478
+ const ambiguousOnWork = ownTree ? attachedAmbiguous(join(me.home, "work")) : [];
479
+ // Each extra tree's attached instances, as its note names them: the recorded children, and those
480
+ // of an ambiguous name.
481
+ const extraAttached = extraWorktrees.map((t) => ({ kids: kids.filter((c) => attachedWorkLink(c.home, t.path) !== null), others: attachedAmbiguous(t.path) }));
449
482
  // The session as the plan shows it, whole: its state, and the reason or the note of one that is
450
483
  // not established, which the record's launch and endpoint fields decide (awebai/oats#1065). The
451
484
  // children as the plan names them (a child's agent is the name its soul's file gives, which its
452
485
  // home's path does not hold), and with them what the plan shows of other homes' records: the edges
453
486
  // it could not follow (facts.ambiguous, whole: each edge's reason counts the homes of the name)
454
- // and the children attached to this work (a note). Where Git gives no answer for work/, the
487
+ // and the instances attached to this work and to each extra tree, which the notes name (#964;
488
+ // attached instances are made by spawns, so they do not move by themselves). Where Git gives no answer for work/, the
455
489
  // reason the plan shows for that (facts.work.reason): nothing at work/ and a file there are one
456
490
  // answer of the reading under a record that says `worktree`, and two plans. Where Git answers,
457
491
  // what the plan shows of the tree that does not move by itself: the commit, the branch and
@@ -468,7 +502,8 @@ export function planRetire(ctx, root, name, { home } = {}) {
468
502
  // note stays short, and are part of the plan's revision (awebai/oats#1065).
469
503
  const recovery = retirementRecoveryFacts(me.home);
470
504
  const safety = [me.home, target.session, target.launched, tree, kids.map((c) => [c.instance, c.agent, c.home]),
471
- { ambiguous: facts.ambiguous, attached: attached.map((c) => c.home) },
505
+ { ambiguous: facts.ambiguous, attached: attached.map((c) => c.home), ambiguousOnWork: ambiguousOnWork.map((c) => c.home),
506
+ extra: extraWorktrees.map((t, i) => [t.path, extraAttached[i].kids.map((c) => c.home), extraAttached[i].others.map((c) => c.home)]) },
472
507
  // The home's extra trees, when there are any.
473
508
  ...(extraWorktrees.length ? [extraWorktrees] : []),
474
509
  // What the plan reports of the record about work/ (its work mode, its repository, its branch),
@@ -487,7 +522,7 @@ export function planRetire(ctx, root, name, { home } = {}) {
487
522
  recovery];
488
523
  appendEvent(me.home, { kind: "retire-planned", data: { planRevision: planRevision(safety), children: kids.length, dirty: facts.work.observed ? facts.work.changed + facts.work.untracked : null } }, { workspaceOnly: true });
489
524
  const plan = { lifecycleApi: LIFECYCLE_API, action: "retire", instance: name, home: me.home, at: new Date().toISOString(), facts, defaults, planRevision: planRevision(safety),
490
- notes: boundedNotes(extraWorktrees.map(extraWorktreeNote), [
525
+ notes: boundedNotes(extraWorktrees.map((t, i) => extraWorktreeNote(t, extraAttached[i].kids.map((c) => c.instance), extraAttached[i].others.map((c) => c.instance))), [
491
526
  // The two notes about a worktree that is retained are for the instance's own tree alone (#973).
492
527
  // Not for a directory of the home (what it holds is copied and removed), not for a directory
493
528
  // instance whose work/ is a repository of its own (the recovery note below says what is done),
@@ -502,6 +537,7 @@ export function planRetire(ctx, root, name, { home } = {}) {
502
537
  ], [
503
538
  ...(kids.length ? [`${kids.length} recorded child instance(s) are stopped first (bounded SIGTERM, never escalated) and retained (their homes are not removed); a child still running after the grace refuses the retirement`] : []),
504
539
  ...(attached.length ? [`attached child instance(s) ${listWithin(attached.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? attached.length} use this home's work/ as their work: a retire that keeps the worktree repoints their work link to it; with --discard-worktree the worktree is removed and their work link will dangle`] : []),
540
+ ...(ambiguousOnWork.length ? [`attached instance(s) ${listWithin(ambiguousOnWork.map((c) => c.instance), (shown) => shown.join(", "), PLAN_LIST_BUDGET) ?? ambiguousOnWork.length}, listed under ambiguous, use this home's work/ as their work: the retire neither stops them nor repoints their work link, which will then point at a path that is gone, whether the worktree is retained (the receipt names where) or removed with --discard-worktree`] : []),
505
541
  ...((kids.ambiguous || []).length ? [`${kids.ambiguous.length} instance(s) record this name as parent but the name is not unique under this root; they are listed under ambiguous and NOT acted on`] : []),
506
542
  ...(target.session.note ? [sessionNote(target.session)] : []),
507
543
  "pull request state is unknown to the kernel; the ADE reports it when a forge connection exists",
package/lib/worktree.mjs CHANGED
@@ -23,6 +23,7 @@ import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, realpathSync,
23
23
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
24
24
  import { checkHolderByHand, ifItDoesNotEnd, lifecycleBusy, nothingAfter, oatsError, OWN_START_REMEDY } from "./errors.mjs";
25
25
  import { appendEvent } from "./instance-events.mjs";
26
+ import { attachedToTree } from "./instance-lifecycle.mjs";
26
27
  import { recordedTeams } from "./teams.mjs";
27
28
  import { canonicalCloneKey, memberCloneOf } from "./instance-resolution.mjs";
28
29
  import { loadLocal } from "./workspace.mjs";
@@ -608,7 +609,14 @@ export async function worktreeAdd(homeArg, o = {}) {
608
609
 
609
610
  /** `oats worktree remove --purpose <p>`: `git worktree remove` (which refuses a dirty tree),
610
611
  * the branch kept, no hook, the record dropped. A `creating` record whose adder is gone is
611
- * rolled back instead. Only recorded trees: a hand-made one is git's to remove. */
612
+ * rolled back instead. Only recorded trees: a hand-made one is git's to remove.
613
+ *
614
+ * An instance can be attached to the tree: its `work` is a link to it (#958). The tree is not
615
+ * removed under a session that runs there, or that cannot be read (#964): E_CHILDREN_RUNNING,
616
+ * under the purpose's claim and before Git is asked anything, the record kept. This command stops
617
+ * nobody, and no flag removes anyway. An attached instance whose session is stopped does not
618
+ * refuse: the tree is removed, and the answer's `warnings` name it, since its link then points at
619
+ * a path that is gone. A tree that is already gone is removed under nobody: no one is looked at. */
612
620
  export async function worktreeRemove(homeArg, o = {}) {
613
621
  validateTreeArgs(o, { forRemove: true });
614
622
  const home = homeArg;
@@ -630,6 +638,17 @@ export async function worktreeRemove(homeArg, o = {}) {
630
638
  return { purpose, path: tree, removed: true, rolledBack: true, branch: rec.branch, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(warned.length ? { warnings: warned } : {}) };
631
639
  }
632
640
  const clone = rec.clone;
641
+ // Who is attached, asked while the tree is there (a link through an alias resolves only then).
642
+ // The owner's lineage is read under the home's real path: the command may have been given a
643
+ // link to the home, whose name and parents are not the instance's.
644
+ const realHome = realpathOr(home);
645
+ const attached = existsSync(tree) ? attachedToTree(dirname(dirname(dirname(realHome))), basename(realHome), tree) : [];
646
+ const inUse = attached.filter((c) => c.session !== "stopped");
647
+ if (inUse.length) {
648
+ const seen = inUse.map((c) => `${c.instance} (${c.session === "running" ? "its session is running" : "whether its session is running could not be read"})`).join(", ");
649
+ const step = inUse.length === 1 ? `stop it (\`oats instance stop ${inUse[0].instance}\`) or retire it` : "stop each one (`oats instance stop <instance>`) or retire it";
650
+ throw Object.assign(oatsError("E_CHILDREN_RUNNING", `${tree} is the work of ${inUse.length === 1 ? "an attached instance" : "attached instances"}: ${seen}; nothing was removed (the record is kept). To remove the tree, ${step}, then remove again`), { details: { purpose, path: tree, children: inUse } });
651
+ }
633
652
  if (existsSync(tree)) {
634
653
  const status = git(["-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
635
654
  const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
@@ -641,6 +660,8 @@ export async function worktreeRemove(homeArg, o = {}) {
641
660
  await trackedGit(["-C", clone, "worktree", "prune"], { track });
642
661
  if (existsSync(tree)) throw Object.assign(oatsError("E_WORK_PRESERVATION_FAILED", `${tree} is still there after git worktree remove; the record is kept`), { details: { purpose, path: tree } });
643
662
  rmSync(recPath, { force: true });
644
- return { purpose, path: tree, removed: true, rolledBack: false, branch: rec.branch, branchKept: true, ...(claimWarnings.length ? { warnings: claimWarnings } : {}) };
663
+ // What the removal left each attached instance with (their sessions were stopped).
664
+ const warned = [...claimWarnings, ...attached.map((c) => `${c.instance}: its work was ${tree}, which was removed; its work link ${join(c.home, "work")} now points at a path that is gone`)];
665
+ return { purpose, path: tree, removed: true, rolledBack: false, branch: rec.branch, branchKept: true, ...(warned.length ? { warnings: warned } : {}) };
645
666
  });
646
667
  }
@@ -3,7 +3,7 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v5.1.0",
6
+ "ref": "v5.2.0",
7
7
  "path": "oats-package"
8
8
  },
9
9
  "oats.aweb": {
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "oats.framework": {
45
45
  "url": "https://github.com/awebai/oats.git",
46
- "ref": "oats-framework/v1.10.1",
46
+ "ref": "oats-framework/v1.10.2",
47
47
  "path": "oats-package"
48
48
  }
49
49
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -13,7 +13,7 @@
13
13
  // Every candidate is canonicalized to an absolute executable and accepted
14
14
  // ONLY if executable and `<bin> version --json` returns the v1 probe:
15
15
  // {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
16
- // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.57.0 (the band is
16
+ // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.58.0 (the band is
17
17
  // spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
18
18
  // API version — not source adjacency — is authoritative.
19
19
  //
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
52
52
  // carry a `description` for every kind and `<kind> update <id> --description`
53
53
  // sets one (feature `automation-descriptions`, which gates the Desktop's
54
54
  // summary writes). The Desktop v1 surface is otherwise unchanged.
55
- export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 57, 0] };
55
+ export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 58, 0] };
56
56
  /** The band as humans read it — derived, never hand-spelled, so the probe
57
57
  * rejection reason, the backend's /api status and the degradation card can
58
58
  * never disagree with the numbers actually enforced above. */
@@ -70,6 +70,11 @@ export const APPLY_WAIT_MS = 600_000;
70
70
  * clock the wall clock (ms since the epoch), for when a running apply started (`running.since`)
71
71
  * after `after(ms, fn)` runs fn once after ms and answers a cancel; mint the reference and key maker
72
72
  * terms the client's own (client-terms.mjs): every reason is worded with them; required
73
+ * exec optional: the client's own execFile, passed to `invoke` as `invoke(bin, args, { exec })` for the plan
74
+ * read and for the apply alike; without it `invoke` is given no third argument and cliLifecycle's own
75
+ * defaults run. A given exec runs every call cliLifecycle hands it; one with `detached: true` is an apply,
76
+ * which it runs in a session of its own (as execFileInSession does) and never ends, neither at a deadline
77
+ * nor by a signal to its group.
73
78
  * An apply's answer is awaited APPLY_WAIT_MS. When that passes the boundary answers `unknown` and the apply stays
74
79
  * in flight here: its reference, its key, its place as the one apply. Its answer, whenever it comes, is read and
75
80
  * kept 30 minutes like any other; the same reference meanwhile is answered at once (`unknown` while it runs, the
@@ -84,8 +89,10 @@ export const APPLY_WAIT_MS = 600_000;
84
89
  * the workspace's roster group (its `probe` says which features a routed command's host answers with,
85
90
  * lifecycle-contract.mjs `answeringFeatures`); `instances` are that deployment's own rows. */
86
91
  export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => performance.now(), clock = () => Date.now(), mint = () => randomBytes(32).toString('hex'),
87
- after = (ms, fn) => { const timer = setTimeout(fn, ms); timer.unref?.(); return () => clearTimeout(timer); }, terms } = {}) {
92
+ after = (ms, fn) => { const timer = setTimeout(fn, ms); timer.unref?.(); return () => clearTimeout(timer); }, terms, exec } = {}) {
88
93
  requireTerms(terms, 'createLifecycleBoundary');
94
+ // The CLI call, with the client's exec when it gave one: the same exec for a plan read and an apply.
95
+ const call = (bin, args) => (exec ? invoke(bin, args, { exec }) : invoke(bin, args));
89
96
  const plans = new Map(), actions = new Map(), reads = new Map(), beforeEffect = new Set(BEFORE_EFFECT_CODES);
90
97
  let reservedPlans = 0, activeApply = null;
91
98
  const sweep = () => { for (const map of [plans, actions]) for (const [key, value] of map) {
@@ -122,7 +129,7 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
122
129
  if (!reads.has(key)) {
123
130
  const args = { operation: request.operation, phase: 'plan', instance: selected.target.instance, home: selected.target.home, context: selected.context,
124
131
  ...(selected.remote ? { server: selected.remote.server } : {}), choices };
125
- const pending = Promise.resolve().then(() => invoke(selected.bin, args)).catch(() => ({ ok: false, error: { code: 'E_CLI_FAILED' } })).finally(() => reads.delete(key));
132
+ const pending = Promise.resolve().then(() => call(selected.bin, args)).catch(() => ({ ok: false, error: { code: 'E_CLI_FAILED' } })).finally(() => reads.delete(key));
126
133
  reads.set(key, pending);
127
134
  }
128
135
  reservedPlans++;
@@ -202,7 +209,7 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
202
209
  const args = { operation: entry.plan.action, phase: 'apply', instance: entry.target.instance, home: entry.target.home,
203
210
  context: entry.context, ...(entry.remote ? { server: entry.remote.server } : {}), choices: clone(entry.choices), revision: entry.plan.planRevision, key: entry.key };
204
211
  let cancel = () => {};
205
- const answered = Promise.resolve().then(() => invoke(entry.bin, args)).then(result => interpret(result, entry, current.features))
212
+ const answered = Promise.resolve().then(() => call(entry.bin, args)).then(result => interpret(result, entry, current.features))
206
213
  .catch(() => denied('E_OUTCOME_UNKNOWN', entry.target, { status: 'unknown', planRef: entry.id }))
207
214
  .then(result => { entry.reply = clone(result); return result; })
208
215
  .finally(() => { cancel(); entry.pending = null; entry.waited = null; entry.expires = now() + 30 * 60_000; if (activeApply === entry) activeApply = null; });
@@ -126,7 +126,7 @@ export function retainedSpawnMessage(d) {
126
126
  const p = launchPromptOutcome(d.launchPrompts);
127
127
  return `${d.instance} was retained: ${p.reason}.${inputNote(p)} Inspect its existing pane, then use oats session start --home for this home. Do not spawn again.`;
128
128
  }
129
- /** A Start or Restart of an existing home that stopped at a launch prompt, in the Desktop's words: the
129
+ /** A Start or Restart of an existing home that stopped at a launch prompt, in the clients' words: the
130
130
  * kernel answers E_SPAWN_INCOMPLETE with the same retained details as a spawn. `instance` is the name the
131
131
  * dialog started; `d` the decoded details. It claims the weaker thing for both statuses: a blocked start and
132
132
  * one whose completion was not seen are both "not confirmed", never "failed" and never "started". */
@@ -6,7 +6,8 @@ inside `@awebai/oats` and is never published on its own.
6
6
 
7
7
  **It is a preview.** This version shows a workspace's instances, on this
8
8
  machine and on the other machines registered on it, in one list, follows
9
- them, and opens an agent's terminal; it changes nothing in a deployment. While it is a preview its screens and its
9
+ them, opens an agent's terminal, and stops, starts, restarts and retires an
10
+ agent after a confirmation. While it is a preview its screens and its
10
11
  configuration file may change without notice.
11
12
 
12
13
  [`docs/tui.md`](../../docs/tui.md) is the reference: how to start it, what the
@@ -24,7 +25,7 @@ never does.
24
25
  | `lib/config.mjs` | `tui.json`: read once, checked, and the effective action table |
25
26
  | `lib/client.mjs` | the one module that imports the shared readers (`packages/client/`), and the client's terms |
26
27
  | `lib/open.mjs` | the viewer of an opened agent: `oats session attach` run by the same kernel on the user's terminal, and the end of its standard error kept |
27
- | `lib/read.mjs` | the effects of reading: the deployment, the kernel record, the observer of every deployment opened in the run, the roster of other machines (`oats server roster --json`), the refresh loop, the liveness collector, ending every child, and the two looks at the file system the switcher needs (the entries of `~/Agents`, and whether a picked folder is a deployment) |
28
+ | `lib/read.mjs` | the effects of reading: the deployment, the kernel record, the observer of every deployment opened in the run, the roster of other machines (`oats server roster --json`), the refresh loop, the liveness collector, ending every read, the changes (a stop or retire apply, a start or restart: never ended, their output in files of the run's private directory), and the two looks at the file system the switcher needs (the entries of `~/Agents`, and whether a picked folder is a deployment) |
28
29
  | `lib/store.mjs` | the state and `reduce(state, event)`: pure |
29
30
  | `lib/model.mjs` | from the state to the rows and the detail to draw, and to the switcher's rows, by calling the shared readers: pure, no cell position |
30
31
  | `lib/term/keys.mjs` | bytes to key events: a pure parser with an injected clock |
@@ -33,7 +34,7 @@ never does.
33
34
  | `lib/term/style.mjs` | style values: the sixteen ANSI colours and four attributes |
34
35
  | `lib/term/screen.mjs` | the cell buffer and the bytes of a frame |
35
36
  | `lib/term/tty.mjs` | the guard: enter, leave, signals, suspend, resize, the lend of the terminal to a viewer, one write per frame |
36
- | `lib/views/` | pure functions from the model and a size to rows of spans: the frame, the list, the detail, the switcher, the help |
37
+ | `lib/views/` | pure functions from the model and a size to rows of spans: the frame, the list, the detail, the switcher, the help, the confirmation of an act (`act.mjs`) |
37
38
 
38
39
  Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
39
40
 
@@ -50,9 +51,16 @@ Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
50
51
  - The store holds no size and no cell: a key event carries the height of the
51
52
  panes as the last frame drew them.
52
53
  - Every read runs in a session of its own and is ended on every way out.
53
- The one child that is not a read is the viewer (`lib/open.mjs`): it shares
54
- the user's terminal, the guard lends it the terminal, and it is ended first
55
- on every way out while it has it.
54
+ The viewer (`lib/open.mjs`) shares the user's terminal, the guard lends it
55
+ the terminal, and it is ended first on every way out while it has it. A
56
+ change (`lib/read.mjs` `changeExec`: the apply of a stop or a retire, a
57
+ start, a restart) is never signalled: on the way out it is let go, and its
58
+ output goes to files, so it never meets a closed pipe.
59
+ - The acts decide nothing the shared home decides: which act a row offers is
60
+ `instanceActs`, a stop or a retire is the shared confirmation over the
61
+ run's one lifecycle boundary, a start or a restart is `startInstance`, and
62
+ no lifecycle sentence is written in this package where the shared home
63
+ has one.
56
64
  - The screen takes safe text only. Text the TUI did not write goes through
57
65
  `shown()`; `lit()` is for the TUI's own words and refuses anything the
58
66
  display filter would change, a run of spaces included, so a row is spans
@@ -61,7 +69,8 @@ Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
61
69
  Tests: `node --test packages/tui/test/*.test.mjs`, the root tests
62
70
  `test/tui-*.test.mjs`, and the end-to-end tests in a real tmux on a private
63
71
  socket (`test/tui-terminal.test.mjs`, and `test/tui-open-terminal.test.mjs`
64
- for opening an agent, with a second private server for the agents). All of them need the root's install
72
+ for opening an agent, with a second private server for the agents;
73
+ `test/tui-acts.test.mjs` for the acts, run on CI only). All of them need the root's install
65
74
  (`npm ci` at the repository root). The package has no dependency of its own,
66
75
  but one of its tests runs the real kernel, which has: "KERNEL_BIN is this
67
76
  install's own bin/oats.mjs, and its `version --json` is a record the probe
@@ -3,7 +3,8 @@
3
3
  // (term/keys.mjs keyId); they are the part a user's tui.json replaces (config.mjs), so everything
4
4
  // that acts on a key or names one reads the EFFECTIVE table it is handed, never this constant.
5
5
  // An action that does one thing in the list of instances and another in the switcher (`open`)
6
- // says so in `views`: what it does in each, in the order the help lists them.
6
+ // says so in `views`: what it does in each, in the order the help lists them. An action of one
7
+ // view only (the four acts) names that view, so the help says where it acts.
7
8
  export const ACTIONS = Object.freeze([
8
9
  { id: "up", keys: ["up", "k"], label: "up" },
9
10
  { id: "down", keys: ["down", "j"], label: "down" },
@@ -19,6 +20,12 @@ export const ACTIONS = Object.freeze([
19
20
  { id: "instances", keys: ["1"], label: "instances" },
20
21
  { id: "workspaces", keys: ["w"], label: "workspaces" },
21
22
  { id: "open", keys: ["enter"], label: "open", views: [["instances", "open the selected agent's terminal, in the list of instances"], ["switcher", "open the selected workspace, in the switcher"]] },
23
+ // The four acts on an instance: each opens a confirmation, and nothing is done before a move and
24
+ // a press in it. Capitals: a lower-case key is one slip away, a capital takes Shift.
25
+ { id: "stop", keys: ["X"], label: "stop", views: [["instances", "stop the selected agent, after a confirmation"]] },
26
+ { id: "retire", keys: ["D"], label: "retire", views: [["instances", "retire the selected agent, after a confirmation"]] },
27
+ { id: "start", keys: ["S"], label: "start", views: [["instances", "start the selected agent as it was last launched, after a confirmation"]] },
28
+ { id: "restart", keys: ["R"], label: "restart", views: [["instances", "restart the selected agent as it was last launched, after a confirmation"]] },
22
29
  { id: "help", keys: ["?"], label: "help" },
23
30
  { id: "close", keys: ["escape"], label: "close" },
24
31
  { id: "quit", keys: ["q", "ctrl+c"], label: "quit" },
@@ -26,6 +26,10 @@ export { instanceActs, openAct } from "../../client/instance-acts.mjs";
26
26
  export { sessionAttachArgv, prepareRemoteTerm, detachKeySupported, hostDetachKeySupported, preflightFailure, DETACH_KEY_FEATURE } from "../../client/session-attach.mjs";
27
27
  export { attachExit } from "../../client/attach-exit.mjs";
28
28
  export { kernelLines } from "../../client/kernel-lines.mjs";
29
+ export { createLifecycleBoundary } from "../../client/instance-lifecycle.mjs";
30
+ export { createLifecycleConfirmation } from "../../client/lifecycle-confirmation.mjs";
31
+ export { startGate, startInstance } from "../../client/session-start.mjs";
32
+ export { retainedStartMessage, launchFlagIgnored, flagIgnoredNotice } from "../../client/launch-prompt-outcome.mjs";
29
33
  export { INSTANCE_VARIABLES } from "../../client/kernel-environment.mjs";
30
34
  export { validateWorkspace, deploymentsInside } from "../../client/workspace-admission.mjs";
31
35
 
@@ -1,16 +1,17 @@
1
1
  // `oats tui` (preview): the loop. Events from the keyboard and from the reader go through one
2
2
  // pure reduce(state, event); what only the loop can do comes back as an effect; the frame is
3
3
  // drawn from the state. This version shows a workspace's instances, on this machine and on the
4
- // machines registered here, follows them, and opens an agent's terminal with the kernel's own
5
- // viewer; it changes nothing in a deployment (docs/tui.md).
4
+ // machines registered here, follows them, opens an agent's terminal with the kernel's own
5
+ // viewer, and stops, starts, restarts and retires an instance after a confirmation, through the
6
+ // shared lifecycle boundary and start rule (docs/tui.md).
6
7
  import { homedir } from "node:os";
7
8
  import { resolve } from "node:path";
8
9
  import { bindings } from "./actions.mjs";
9
- import { displayLine, pendingEntry, prepareRemoteTerm, sessionAttachArgv } from "./client.mjs";
10
+ import { TERMS, createLifecycleBoundary, createLifecycleConfirmation, displayLine, heldHome, pendingEntry, prepareRemoteTerm, sessionAttachArgv, startInstance } from "./client.mjs";
10
11
  import { loadConfig } from "./config.mjs";
11
- import { model, roster } from "./model.mjs";
12
+ import { ACT_WORDS, actContext, actCwd, localDeployments, model, roster } from "./model.mjs";
12
13
  import { startViewer } from "./open.mjs";
13
- import { admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel } from "./read.mjs";
14
+ import { admitDeployment, createReader, findDeployment, leaveInstance, offeredDeployments, probeKernel, realpath, tellable } from "./read.mjs";
14
15
  import { initialState, reduce } from "./store.mjs";
15
16
  import { createKeyParser, keyId } from "./term/keys.mjs";
16
17
  import { createScreen, glyphs } from "./term/screen.mjs";
@@ -24,7 +25,8 @@ const HELP = `Usage:
24
25
 
25
26
  The OATS terminal client (preview): a full-screen view of a workspace's instances,
26
27
  on this machine and on the machines registered here. It follows them, opens an
27
- agent's terminal with Enter, and changes nothing in a deployment.
28
+ agent's terminal with Enter, and stops, retires, starts or restarts an instance
29
+ (X, D, S, R) after a confirmation.
28
30
  Keys: ? help, Enter open, w workspaces, q quit.
29
31
  docs/tui.md has the rest.
30
32
 
@@ -61,15 +63,19 @@ function errorLines(error) {
61
63
  return String(text).split("\n", 12).map((line) => displayLine(line)).filter(Boolean);
62
64
  }
63
65
 
64
- /** What the loop does outside the terminal, each replaceable by a test. */
65
- const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, startViewer });
66
+ /** What the loop does outside the terminal, each replaceable by a test. `realpath` is the one the
67
+ * shared start rule checks a local home with; `startInstance` and `createLifecycleConfirmation`
68
+ * are the shared home's, replaceable so a test can drive the loop's wiring. */
69
+ const EFFECTS = Object.freeze({ loadConfig, findDeployment, probeKernel, createReader, offeredDeployments, admitDeployment, prepareRemoteTerm, startViewer,
70
+ realpath, tellable, startInstance, createLifecycleConfirmation, createLifecycleBoundary });
66
71
 
67
72
  /** Run. Resolves with the exit status; never calls process.exit, so what was written drains.
68
73
  * Before the alternate screen, in this order, each failure one line on stderr and status 1:
69
74
  * the arguments; the instance variables removed from the environment (a TUI started in an
70
75
  * agent's pane must read the deployment it was asked about, and so must every child it starts);
71
76
  * the terminal; the user's tui.json; the deployment; the kernel it shipped with. */
72
- export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects = EFFECTS }) {
77
+ export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout, cwd = () => process.cwd(), home = homedir(), effects: given = EFFECTS }) {
78
+ const effects = given === EFFECTS ? EFFECTS : { ...EFFECTS, ...given };
73
79
  const { options, error } = parseArgs(argv);
74
80
  if (error) { stderr.write(`${error}\n`); return 1; }
75
81
  if (options.help) { stdout.write(HELP); return 0; }
@@ -96,7 +102,7 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
96
102
  // What the last frame drew, for the store: how tall the list pane is and how far the other
97
103
  // pane scrolls. The store holds no size of its own.
98
104
  let drawn = { page: 1, extent: 0, room: 1, cols: 1 };
99
- let full = true, escTimer = null, ended = false;
105
+ let full = true, escTimer = null, ended = false, reads = 0;
100
106
  /** The preflight of another machine's agent under way: `{ id, controller, prepared }`, where
101
107
  * `prepared` is what it answered (`{ binary, args }`) once it has; or null. */
102
108
  let preflight = null;
@@ -110,6 +116,19 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
110
116
  getRoster: () => ({ remote: state.remote, memory: state.memory, notes: state.notes }),
111
117
  onEntry: heard, onRoster: heard,
112
118
  });
119
+ // THE ACTS (docs/tui.md, "Stopping, starting, restarting and retiring"). One lifecycle boundary
120
+ // per run: its plans, its kept answers and its one apply at a time are this run's. Its exec runs
121
+ // a plan read as a read the loop asked for (kind "read", ended on every way out) and an apply
122
+ // (`detached: true`, cliLifecycle's own mark of a change) as a change, which the TUI never ends.
123
+ // `applying` is the label of the apply this run's confirmation just sent: only one confirmation
124
+ // is open at a time, and the boundary calls its exec in the same turn as the request.
125
+ let applying = null;
126
+ const boundary = effects.createLifecycleBoundary({ terms: TERMS, exec: (bin, argv, { detached, ...options }, callback) => (detached
127
+ ? reader.changeExec(bin, argv, { ...options, label: applying }, callback)
128
+ : reader.exec(bin, argv, options, callback)) });
129
+ /** The confirmation open now: `{ n, made }`, `made` the shared confirmation; or null. */
130
+ let confirmation = null;
131
+
113
132
  /** What the reader gave, into the state, and the screen after it. */
114
133
  function heard(event) { if (!ended) guard.attempt(() => { if (!took(reduce(state, event, keymap))) guard.draw(); }); }
115
134
  /** One step of the reducer taken: the state, then what only the loop can do. True once the
@@ -134,10 +153,59 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
134
153
  preflight = null;
135
154
  if (ready?.id === effect.lend && ready.prepared) lendTo(effect.lend, ready.prepared.binary, ready.prepared.args);
136
155
  }
156
+ if (effect.dismiss !== undefined) dismiss(effect.dismiss);
157
+ if (effect.act) openConfirmation(effect.act);
158
+ if (effect.call) callConfirmation(effect.call);
159
+ if (effect.start) startAct(effect.start);
137
160
  if (effect.refresh) refresh(effect.refresh);
138
161
  return false;
139
162
  }
140
163
 
164
+ /** What the boundary admits a request of deployment `id` against, read at every admission. */
165
+ const contextOf = (id) => actContext(state, id, clock());
166
+ /** Open the shared confirmation of a stop or a retire the store decided on (`{ n, verb, row,
167
+ * label }`). Every step it tells goes to the store as `{ acted }`; an answer that settles asks
168
+ * for a live read of the rows (onSettled), and nothing else after an apply does. */
169
+ function openConfirmation({ n, verb, row, label }) {
170
+ dismiss(confirmation?.n);
171
+ const id = row.deployment?.id, name = row.instance;
172
+ const target = { workspace: id, instance: name, agent: row.agent, agentsRoot: row.agentsRoot, home: row.home, server: row.server ?? null };
173
+ const mine = { n, made: null };
174
+ const tell = () => { if (mine.made && confirmation === mine) heard({ acted: { n, confirmation: { ...mine.made.state(), view: mine.made.view() } } }); };
175
+ confirmation = mine;
176
+ mine.made = effects.createLifecycleConfirmation({
177
+ request: (body) => { if (body?.action === "apply") applying = { verb, name }; return boundary(body, () => contextOf(id)); },
178
+ target, operation: verb, terms: TERMS, label, leftover: heldHome(row)?.kind === "spawn-incomplete",
179
+ onChange: tell, onSettled: () => refresh({ live: true }),
180
+ });
181
+ tell();
182
+ }
183
+ /** A button pressed in the confirmation: its call, when it is still the open one. */
184
+ function callConfirmation({ n, method, args = [] }) {
185
+ if (confirmation?.n === n) confirmation.made[method](...args);
186
+ }
187
+ /** The confirmation closed: what it sent goes on, and what it answers is no longer told. */
188
+ function dismiss(n) {
189
+ if (confirmation === null || confirmation.n !== n) return;
190
+ const { made } = confirmation;
191
+ confirmation = null;
192
+ made?.close();
193
+ }
194
+ /** Start or restart the row (`{ n, verb, id, row }`) through the shared start rule, once, with no
195
+ * launch choice. Its child is a change of this run: the store hears when it is spawned and when
196
+ * it closes (`starting`), and the answer, whatever it is, asks for a live read. */
197
+ function startAct({ n, verb, id, row }) {
198
+ const label = { verb, name: row?.instance ?? "" };
199
+ const exec = (bin, argv, options, callback) => {
200
+ const child = reader.changeExec(bin, argv, { ...options, label }, (...answer) => { heard({ acted: { closed: id } }); callback(...answer); });
201
+ heard({ acted: { spawned: { id, verb }, at: now() } });
202
+ return child;
203
+ };
204
+ Promise.resolve()
205
+ .then(() => effects.startInstance(probe.cli, row, {}, { restart: verb === "restart", deployments: localDeployments(state, clock()), realpath: effects.realpath, localCwd: actCwd(state), exec, terms: TERMS }))
206
+ .then((answer) => heard({ acted: { n, answer } }), () => heard({ acted: { n, answer: null } }));
207
+ }
208
+
141
209
  /** Open the agent the store decided on (lib/model.mjs openDecision). On this machine the
142
210
  * terminal is lent at once. On another, the shared preflight runs first over the reader's exec
143
211
  * (a read like any other, ended on every way out), and what it prepared waits for the store's
@@ -206,7 +274,9 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
206
274
  // timeout. The person opens the agent again.
207
275
  onStop() { stopPreflight(); dropReads(); },
208
276
  onResume(asked) { if (!asked) { stopPreflight(); dropReads(); } refresh({ live: true }); },
209
- onEnd() { ended = true; reader.stop(); },
277
+ // On the way out the confirmation is closed and the reads end; a change in flight is let go,
278
+ // never signalled (lib/read.mjs changeExec), and named after the screen is left.
279
+ onEnd() { ended = true; dismiss(confirmation?.n); reader.stop(); },
210
280
  });
211
281
  function refresh(how) { Promise.resolve(reader.request(how)).catch(() => {}); }
212
282
  /** A preflight under way when the process stops: given up, and the store told. */
@@ -220,11 +290,14 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
220
290
  function dropReads() { reader.voidInFlight(); state = reduce(state, { collecting: false }, keymap).state; }
221
291
  /** The events of one batch of input, in order. Once one of them lent the terminal, the rest are
222
292
  * dropped: they were typed before the viewer started, and none may act while it has the
223
- * terminal (a `q` behind the Enter would end the run under a live viewer). */
293
+ * terminal (a `q` behind the Enter would end the run under a live viewer). Each batch is one
294
+ * read of input, numbered (`read`): a confirmation ignores the press of its act in the read
295
+ * that moved the focus onto it, so a paste cannot both move and press. */
224
296
  function act(events) {
297
+ const read = ++reads;
225
298
  for (const event of events) {
226
299
  if (guard.lent) return;
227
- if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), ...drawn }, keymap))) return;
300
+ if (took(reduce(state, "paste" in event ? { paste: event.paste } : { key: keyId(event), ...(typeof event.text === "string" && !event.alt ? { text: event.text } : {}), read, ...drawn }, keymap))) return;
228
301
  }
229
302
  guard.draw();
230
303
  }
@@ -241,6 +314,11 @@ export async function main({ argv, stdin, stdout, stderr, env, proc = process, n
241
314
  const end = await guard.done;
242
315
  if (escTimer !== null) clearTimer(escTimer);
243
316
  // After the alternate screen is left, so the message stays on the screen the user returns to.
317
+ // One line per change still running, to a terminal or a file only; the status never depends on it.
318
+ const running = reader.changes?.() ?? [];
319
+ if (running.length && effects.tellable(stderr)) {
320
+ try { stderr.write(running.map(({ label }) => `${ACT_WORDS.leaving(label?.verb ?? "change", displayLine(label?.name) ?? "an instance")}\n`).join("")); } catch { /* nothing to tell it to */ }
321
+ }
244
322
  if (end.error !== undefined) stderr.write(`oats: \`oats tui\` stopped on an internal error; the terminal was restored\n${errorLines(end.error).map((line) => ` ${line}\n`).join("")}`);
245
323
  return end.status;
246
324
  }