@awebai/oats 0.68.1 → 0.69.2

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 (99) hide show
  1. package/bin/oats.mjs +180 -36
  2. package/docs/capabilities.md +73 -10
  3. package/docs/capability-manifest.schema.json +1 -1
  4. package/docs/configuration.md +68 -2
  5. package/docs/design/2026-09-23-workspace-module-contracts.md +6 -4
  6. package/docs/design/2026-10-22-module-upgrade.md +1 -1
  7. package/docs/desktop-cli-api.md +600 -25
  8. package/docs/desktop-instance-start.md +59 -3
  9. package/docs/desktop.md +175 -10
  10. package/docs/execution-targets.md +536 -62
  11. package/docs/harness-trust.md +3 -1
  12. package/docs/implementation.md +33 -15
  13. package/docs/integrations.md +2 -2
  14. package/docs/knowledge.md +25 -16
  15. package/docs/oats-local.schema.json +2 -2
  16. package/docs/official-catalog.md +6 -5
  17. package/docs/packages.md +14 -14
  18. package/docs/release-notes/v0.69.0.md +658 -0
  19. package/docs/release-notes/v0.69.1.md +25 -0
  20. package/docs/release-notes/v0.69.2.md +259 -0
  21. package/docs/servers.md +51 -7
  22. package/docs/soul.schema.json +1 -0
  23. package/docs/souls-and-instances.md +46 -9
  24. package/docs/tui.md +177 -21
  25. package/docs/upgrading.md +16 -7
  26. package/docs/workspaces.md +2 -2
  27. package/injects/instance-boundary.md +19 -33
  28. package/injects/work-attached.md +8 -13
  29. package/injects/work-checkout.md +16 -30
  30. package/injects/work-directory.md +9 -15
  31. package/injects/work-workspace.md +8 -19
  32. package/injects/work-worktree.md +18 -33
  33. package/lib/capability-contract.mjs +2 -2
  34. package/lib/core.mjs +496 -127
  35. package/lib/file-pieces.mjs +49 -0
  36. package/lib/instance-background.mjs +54 -0
  37. package/lib/instance-events.mjs +25 -4
  38. package/lib/instance-inspect.mjs +3 -0
  39. package/lib/instance-lifecycle.mjs +35 -0
  40. package/lib/instance-resolution.mjs +3 -2
  41. package/lib/instance-same-work.mjs +67 -0
  42. package/lib/instance-upgrade.mjs +18 -0
  43. package/lib/launch-prompt-fixtures/README.md +62 -0
  44. package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
  45. package/lib/launch-prompt-fixtures.mjs +49 -0
  46. package/lib/launch-prompt-resume.mjs +55 -0
  47. package/lib/login-environment.mjs +27 -9
  48. package/lib/materialize.mjs +23 -2
  49. package/lib/resolve.mjs +32 -5
  50. package/lib/schedule.mjs +3 -3
  51. package/lib/servers.mjs +136 -27
  52. package/lib/session-end.mjs +82 -0
  53. package/lib/session-input.mjs +43 -9
  54. package/lib/session-resume-contract.mjs +33 -0
  55. package/lib/session-resume.mjs +337 -0
  56. package/lib/session-seen.mjs +163 -0
  57. package/lib/session-viewer.mjs +147 -44
  58. package/lib/soul-composition.mjs +15 -11
  59. package/lib/start-env.mjs +110 -0
  60. package/lib/tmux-server-scope.mjs +139 -14
  61. package/lib/workspace.mjs +41 -6
  62. package/package-catalog.json +11 -5
  63. package/package.json +1 -1
  64. package/packages/client/cli-adapter.mjs +39 -8
  65. package/packages/client/cli-locator.mjs +3 -2
  66. package/packages/client/deployment-data.mjs +16 -0
  67. package/packages/client/deployment-panel.mjs +7 -0
  68. package/packages/client/file-output-exec.mjs +98 -0
  69. package/packages/client/instance-tree.mjs +64 -14
  70. package/packages/client/launch-prompt-outcome.mjs +25 -13
  71. package/packages/client/own-codes.mjs +2 -0
  72. package/packages/client/panel-views.mjs +11 -3
  73. package/packages/client/remote-roster.mjs +5 -1
  74. package/packages/client/roster-sections.mjs +50 -6
  75. package/packages/client/same-work.mjs +49 -0
  76. package/packages/client/session-attach.mjs +35 -5
  77. package/packages/client/session-resume-cli.mjs +64 -0
  78. package/packages/client/session-resume-trigger.mjs +167 -0
  79. package/packages/client/session-resume.mjs +332 -0
  80. package/packages/client/soul-rows.mjs +2 -0
  81. package/packages/client/spawn-apply-contract.mjs +2 -1
  82. package/packages/client/spawn-decision.mjs +4 -1
  83. package/packages/client/spawn-preview-contract.mjs +12 -1
  84. package/packages/client/spawn-preview.mjs +2 -0
  85. package/packages/client/tmux-status.mjs +30 -7
  86. package/packages/client/waiting-on-you.mjs +11 -4
  87. package/packages/client/workspace-step.mjs +17 -5
  88. package/packages/record/lib/last-conversation.mjs +123 -0
  89. package/packages/record/lib/session-roots.mjs +10 -1
  90. package/packages/tui/README.md +2 -2
  91. package/packages/tui/lib/client.mjs +7 -3
  92. package/packages/tui/lib/main.mjs +49 -14
  93. package/packages/tui/lib/model.mjs +146 -55
  94. package/packages/tui/lib/store.mjs +84 -27
  95. package/packages/tui/lib/term/text.mjs +12 -9
  96. package/packages/tui/lib/views/frame.mjs +74 -7
  97. package/packages/tui/lib/views/help.mjs +10 -3
  98. package/packages/tui/lib/views/instances.mjs +41 -3
  99. package/skills/oats-getting-started/SKILL.md +117 -4
@@ -0,0 +1,49 @@
1
+ /** A regular file's bytes, read in pieces of at most FILE_PIECE bytes, so
2
+ * that what a digest holds of a file is bounded whatever its size: Node
3
+ * refuses to read a file over 2 GiB whole (ERR_FS_FILE_TOO_LARGE), and a
4
+ * retire digests every file of an instance's work (awebai/oats#617). */
5
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
6
+ import { oatsError } from "./errors.mjs";
7
+
8
+ export const FILE_PIECE = 1024 * 1024;
9
+
10
+ /** Read the file at `path` (text or bytes; a link is followed, as
11
+ * readFileSync follows it) → its size. `sized(size)` is called first, with
12
+ * the size the open file has, then `piece(bytes)` for each piece in order:
13
+ * exactly that many bytes, as readFileSync reads a regular file, so a file
14
+ * that grows meanwhile is read for the size it had. One that ends before
15
+ * that size changed while it was read: E_WORK_INSPECTION_FAILED. When
16
+ * `sized` returns false, nothing of the file is read. A piece's buffer is
17
+ * reused once `piece` returns. `io` is for tests. */
18
+ export function readFilePieces(path, sized, piece, io = { readSync }) {
19
+ const fd = openSync(path, "r");
20
+ try {
21
+ const size = fstatSync(fd).size;
22
+ if (sized(size) === false) return size;
23
+ const buffer = Buffer.allocUnsafe(Math.min(size, FILE_PIECE));
24
+ for (let read = 0; read < size;) {
25
+ const n = io.readSync(fd, buffer, 0, Math.min(buffer.length, size - read), read);
26
+ if (n === 0) throw oatsError("E_WORK_INSPECTION_FAILED", `${String(path)} changed while it was read: it ended after ${read} of the ${size} bytes it held when it was opened. Retry once nothing writes to it`);
27
+ piece(buffer.subarray(0, n));
28
+ read += n;
29
+ }
30
+ return size;
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+
36
+ /** The bytes of the file at `path`, read in pieces (readFilePieces), when it
37
+ * holds at most `limit` bytes → a Buffer; null when it holds more, and then
38
+ * nothing of it is read. */
39
+ export function readFileUpTo(path, limit) {
40
+ let bytes = null, at = 0;
41
+ readFilePieces(path, (size) => { if (size > limit) return false; bytes = Buffer.allocUnsafe(size); }, (piece) => { piece.copy(bytes, at); at += piece.length; });
42
+ return bytes;
43
+ }
44
+
45
+ /** `hash` updated with the bytes of the file at `path` (readFilePieces) → `hash`. */
46
+ export function hashFile(hash, path) {
47
+ readFilePieces(path, () => {}, (bytes) => hash.update(bytes));
48
+ return hash;
49
+ }
@@ -0,0 +1,54 @@
1
+ /** Whether an instance is background (feature instance-background, awebai/oats#1579): presentation like
2
+ * the colour (lib/instance-color.mjs), never identity or policy. A client lists a background instance
3
+ * under its own section; nothing else about the instance changes. It is a home file of its own,
4
+ * `<home>/.oats-background.json`, so that a start or restart, which rewrites instance.json, can never
5
+ * lose it; a later edit of the soul does not move an existing home.
6
+ *
7
+ * The record is `{ backgroundApi: 1, at }` (#1579 item 3: present means background), written atomically
8
+ * (writeThroughPrivateFile) at mode 0600; absent means not background, and `off` removes the file. A
9
+ * reader takes a regular file only, without following a link, up to RECORD_MAX bytes: anything that is
10
+ * not a valid record reads as not background (false), never an error. Dependency-free: spawn, the status
11
+ * rows, inspect and the command all read and write it through here. */
12
+ import { lstatSync, rmSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { readFileHead } from "./bounded-read.mjs";
15
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
16
+
17
+ /** The record's own version, and the command answer's. */
18
+ export const BACKGROUND_API = 1;
19
+ export const INSTANCE_BACKGROUND_API = 1;
20
+ /** The home file, kernel-owned: in KERNEL_HOME_NAME_PREFIXES (lib/capability-contract.mjs), the retire
21
+ * fingerprint's receipts (lib/core.mjs KERNEL_HOME_RECEIPTS) and the manifest schema. */
22
+ export const BACKGROUND_FILE = ".oats-background.json";
23
+ /** A record larger than this is not one. */
24
+ export const RECORD_MAX = 4096;
25
+
26
+ /** Whether `home` records itself background: false for no file, not a regular file (a link is never
27
+ * followed), over RECORD_MAX bytes, unreadable, not a JSON object or another backgroundApi. Never throws. */
28
+ export function readInstanceBackground(home) {
29
+ try {
30
+ const { bytes, size } = readFileHead(join(home, BACKGROUND_FILE), RECORD_MAX + 1);
31
+ if (size > RECORD_MAX) return false;
32
+ const record = JSON.parse(bytes.toString("utf8"));
33
+ return !!record && typeof record === "object" && !Array.isArray(record) && record.backgroundApi === BACKGROUND_API;
34
+ } catch { return false; }
35
+ }
36
+
37
+ /** Record `home` as background (`on` true), or remove the record (`on` false). → `{ background, changed }`.
38
+ * A home already background is no change: nothing is written. `off` removes whatever file stands at the
39
+ * name (a link or an invalid record included) and is a change only when the home read as background.
40
+ * The caller holds the right to change the home. */
41
+ export function writeInstanceBackground(home, on, { now = () => new Date() } = {}) {
42
+ const path = join(home, BACKGROUND_FILE);
43
+ const before = readInstanceBackground(home);
44
+ if (!on) {
45
+ let present = false;
46
+ try { lstatSync(path); present = true; } catch (e) { if (e?.code !== "ENOENT") throw e; }
47
+ if (present) rmSync(path, { force: true });
48
+ return { background: false, changed: before };
49
+ }
50
+ if (before) return { background: true, changed: false };
51
+ const bytes = JSON.stringify({ backgroundApi: BACKGROUND_API, at: now().toISOString() }) + "\n";
52
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, bytes, 0o600);
53
+ return { background: true, changed: true };
54
+ }
@@ -89,11 +89,23 @@ const readReason = (r) => (WAITING_REASONS.includes(r) ? r : null);
89
89
  /** An event time: a string that parses as a date. The writer refuses anything else. */
90
90
  const validTime = (at) => typeof at === "string" && Number.isFinite(Date.parse(at));
91
91
 
92
+ /** A stored message as the reader shows it: one with a refused character anywhere is null; one
93
+ * over WAITING_MESSAGE_MAX code points (a row another producer or an older writer made, a
94
+ * remote kernel's claim) is cut to that many, the last one `…`, so the bound holds for every
95
+ * reader; then the message is valid or null. */
96
+ function readMessage(m) {
97
+ if (typeof m !== "string" || WAITING_MESSAGE_REFUSED.test(m)) return null;
98
+ const points = [...m];
99
+ const cut = points.length > WAITING_MESSAGE_MAX ? `${points.slice(0, WAITING_MESSAGE_MAX - 1).join("")}…` : m;
100
+ return validWaitingMessage(cut) ? cut : null;
101
+ }
102
+
92
103
  /** The READ rule for one claim `{since, producer, reason, message}`, the same for a
93
104
  * row of this machine's log and for a claim another kernel reports (a remote roster
94
105
  * row): `since` is a valid date and `producer` is `kernel` or a producer id, or there
95
- * is no claim (null); a reason outside the closed set and a message that fails
96
- * validWaitingMessage read as null, and the claim still counts. Anything that is not
106
+ * is no claim (null); a reason outside the closed set reads as null, a message over
107
+ * WAITING_MESSAGE_MAX code points is cut (readMessage), and one that then fails
108
+ * validWaitingMessage reads as null: the claim still counts. Anything that is not
97
109
  * such an object is null. */
98
110
  export function readWaitingClaim(claim) {
99
111
  if (!claim || typeof claim !== "object" || Array.isArray(claim)) return null;
@@ -101,7 +113,7 @@ export function readWaitingClaim(claim) {
101
113
  if (!validTime(since)) return null;
102
114
  // A producer the writer would refuse (a hand-edited log) is never shown as one.
103
115
  if (producer !== "kernel" && !(typeof producer === "string" && WAITING_PRODUCER_RE.test(producer))) return null;
104
- return { since, producer, reason: readReason(claim.reason), message: validWaitingMessage(claim.message) ? claim.message : null };
116
+ return { since, producer, reason: readReason(claim.reason), message: readMessage(claim.message) };
105
117
  }
106
118
 
107
119
  /** realpath of `p`, or, when `p` is gone, the realpath of its nearest existing
@@ -276,7 +288,16 @@ function claimsOf(rows, incarnation) {
276
288
  }
277
289
  return claims;
278
290
  }
279
- const positiveOf = (claims) => [...claims.values()].filter((c) => c.waiting).sort((x, y) => x.since.localeCompare(y.since)).at(-1) ?? null;
291
+ /** The claim waitingOnYou shows: the newest positive claim that carries a message, so a claim
292
+ * with no text never hides one a person can read (#1502); the newest text-less claim only adds
293
+ * the reason it lacks. With no message anywhere, the newest positive claim. */
294
+ function positiveOf(claims) {
295
+ const positive = [...claims.values()].filter((c) => c.waiting).sort((x, y) => x.since.localeCompare(y.since));
296
+ const said = positive.filter((c) => c.message !== null).at(-1) ?? null;
297
+ const unsaid = positive.filter((c) => c.message === null).at(-1) ?? null;
298
+ if (said === null) return unsaid;
299
+ return said.reason === null && unsaid !== null ? { ...said, reason: unsaid.reason } : said;
300
+ }
280
301
  const waitingShape = (c) => (c ? { since: c.since, producer: c.producer, reason: c.reason, message: c.message } : null);
281
302
 
282
303
  /** Events for one instance ADDRESS, newest last, from both logs, with a bounded
@@ -29,6 +29,7 @@ import { operatorCoverage, operatorProblems } from "./operator-coverage.mjs";
29
29
  import { readLockIfPresent } from "./packages.mjs";
30
30
  import { composeSoulInstructions } from "./soul-composition.mjs";
31
31
  import { readInstanceColor } from "./instance-color.mjs";
32
+ import { readInstanceBackground } from "./instance-background.mjs";
32
33
  /** Bounds of a provider check's answer (bytes, nesting, entries), as the released binding wire set them. */
33
34
  const BINDING_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
34
35
  import { parseStrictJson } from "./canonical-json.mjs";
@@ -539,6 +540,8 @@ export function inspectDocument(t, { kernel }) {
539
540
  launchConfig: m.launch?.launchConfig ?? null, launchConfigDefault: m.launch?.launchConfigDefault === true, launched: !!m.launched, createdAt: m.createdAt || null,
540
541
  // Feature instance-color: the home's colour record (lib/instance-color.mjs), a palette name or null.
541
542
  color: readInstanceColor(t.home),
543
+ // Feature instance-background: `true` while the home holds a valid record, absent otherwise (as on a row).
544
+ ...(readInstanceBackground(t.home) ? { background: true } : {}),
542
545
  resolution: m.workspace?.resolution ?? null, soulDir: t.soul.soulDir, instructions: { ...readTextCapped(join(t.home, "AGENTS.md")), sources: m.instructions || [] } } : null,
543
546
  ...(m ? { identity: servedIdentityOf(m) } : {}),
544
547
  problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.skillsProblems || []), ...(t.composedSkillsProblems || []), ...(t.discoveryError ? [t.discoveryError] : []),
@@ -17,6 +17,8 @@ import { appendEvent } from "./instance-events.mjs";
17
17
  import { afterFirstEffect, isAnswerCode, kernelCode, lifecycleBusy, oatsError, reportDefect } from "./errors.mjs";
18
18
  import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
19
19
  import { INSTANCE_COLOR_API, INSTANCE_COLORS, writeInstanceColor } from "./instance-color.mjs";
20
+ import { INSTANCE_BACKGROUND_API, writeInstanceBackground } from "./instance-background.mjs";
21
+ import { sameWorkOf, writeSameWork } from "./instance-same-work.mjs";
20
22
 
21
23
  export const LIFECYCLE_API = 1;
22
24
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
@@ -88,6 +90,39 @@ export function setInstanceColor(ctx, root, name, { home, color }) {
88
90
  return { instanceColorApi: INSTANCE_COLOR_API, instance: name, home: me.home, color, changed };
89
91
  }
90
92
 
93
+ /** `oats instance background <instance> on|off` (feature instance-background, awebai/oats#1579): record or
94
+ * remove the background record of the home `name` resolves to, with the authority and the refusals of
95
+ * `instance color` above (setInstanceColor), a stopped home included. `background` is a boolean; the caller
96
+ * refused anything else. → `{ instanceBackgroundApi, instance, home, background, changed }`. */
97
+ export function setInstanceBackground(ctx, root, name, { home, background }) {
98
+ if (typeof background !== "boolean") throw oatsError("E_BAD_ARGS", "background must be on or off");
99
+ const me = resolveTarget(ctx, root, name, { home });
100
+ if (existsSync(join(me.home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${me.home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire); the background was not changed`);
101
+ if (existsSync(retirePendingMarkerPath(me.home))) throw oatsError("E_INSTANCE_RETIRING", `${name} is being retired; the background was not changed`);
102
+ refuseBesideRetire("instance background", me.home);
103
+ const { changed } = writeInstanceBackground(me.home, background);
104
+ return { instanceBackgroundApi: INSTANCE_BACKGROUND_API, instance: name, home: me.home, background, changed };
105
+ }
106
+
107
+ /** `oats instance same-work <instance> on|off` (feature instance-same-work, awebai/oats#1577): bind the flag
108
+ * of the home `name` resolves to to its recorded parent (`on`), or remove it (`off`). Addressed, and refused
109
+ * beside a retire or in a quarantined home, exactly as setInstanceColor is. `on` needs a recorded
110
+ * `parentInstance` (E_BAD_ARGS without one) and rebinds a record bound to an old parent; the same parent
111
+ * again writes nothing. `off` succeeds whatever stands there, parent or none. → `{ instance, sameWork }`,
112
+ * the rule (sameWorkOf) read after the write. */
113
+ export function setInstanceSameWork(ctx, root, name, { home, on }) {
114
+ if (typeof on !== "boolean") throw oatsError("E_BAD_ARGS", "instance same-work takes on or off");
115
+ const me = resolveTarget(ctx, root, name, { home });
116
+ if (existsSync(join(me.home, ".oats-rollback-incomplete.json"))) throw oatsError("E_INSTANCE_RETIRING", `${me.home} is a quarantined home (or a spawn still in progress); finish its retirement (oats retire); the flag was not changed`);
117
+ if (existsSync(retirePendingMarkerPath(me.home))) throw oatsError("E_INSTANCE_RETIRING", `${name} is being retired; the flag was not changed`);
118
+ refuseBesideRetire("instance same-work", me.home);
119
+ const recorded = targetRecord(me.home)?.parentInstance;
120
+ const parent = typeof recorded === "string" && recorded !== "" ? recorded : null;
121
+ if (on && parent === null) throw oatsError("E_BAD_ARGS", `${name} has no parent instance: same work is declared against a recorded parent; the flag was not changed`);
122
+ writeSameWork(me.home, on ? parent : null);
123
+ return { instance: name, sameWork: sameWorkOf(me.home, parent) };
124
+ }
125
+
91
126
  /** Every instance under the roots whose recorded parent chain reaches `name`,
92
127
  * deepest first (children are acted on before their parent). Recorded
93
128
  * parentage is the only relation the kernel knows; it is reported as such. */
@@ -654,9 +654,10 @@ export async function discoverOrStandalone(local, { lock, deployment, remoteOpti
654
654
  }
655
655
 
656
656
  /** Materialize a prepared resolution into `home`. Called by spawnInstance after
657
- * the home directory exists and before the harness is launched. */
657
+ * the home directory exists and before the harness is launched. `prepared.blocks`
658
+ * (the kernel's blocks) close the AGENTS.md, after the capability injects. */
658
659
  export async function materializePrepared(prepared, home) {
659
- return materialize(prepared.resolution, home, { lock: prepared.lock, remoteOptions: prepared.remoteOptions, soulAgentsMd: prepared.soulAgentsMd, soulDir: prepared.soulDir });
660
+ return materialize(prepared.resolution, home, { lock: prepared.lock, remoteOptions: prepared.remoteOptions, soulAgentsMd: prepared.soulAgentsMd, soulDir: prepared.soulDir, blocks: prepared.blocks });
660
661
  }
661
662
  /** The capability skills materializePrepared would copy, named before anything is fetched (the spawn preview). */
662
663
  export async function plannedPreparedSkills(prepared) {
@@ -0,0 +1,67 @@
1
+ /** The "same work" flag (feature instance-same-work, awebai/oats#1577): a child instance's declared
2
+ * "same work as my parent", which clients draw as the parent→child line. A home file of its own,
3
+ * `<home>/.oats-same-work.json`, so that a start, restart, stop or resume, which rewrite instance.json,
4
+ * never lose it; only `oats instance same-work … off` or retirement removes it.
5
+ *
6
+ * The flag is BOUND to the parent it was set against: the record names that parent, and the flag is on
7
+ * only while it is still the home's recorded `parentInstance` (sameWorkOf, the one rule). A reparent (a
8
+ * retire's relink, a `--relation parent` spawn re-pointing its anchor) leaves the record bound to the
9
+ * old name, so the flag reads off and nothing errors.
10
+ *
11
+ * The record is `{ sameWorkApi: 1, parent, at }`, written atomically (writeThroughPrivateFile) at mode
12
+ * 0600; present means on. A reader takes a regular file only, without following a link, up to
13
+ * RECORD_MAX bytes: anything that is not a valid record reads as no binding (null), never an error.
14
+ * Dependency-free: the status rows, spawn and the command all go through here. */
15
+ import { lstatSync, rmSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { readFileHead } from "./bounded-read.mjs";
18
+ import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
19
+
20
+ /** The record's own version. */
21
+ export const SAME_WORK_API = 1;
22
+ /** The home file, kernel-owned: in KERNEL_HOME_NAME_PREFIXES (lib/capability-contract.mjs), the retire
23
+ * fingerprint's receipts (lib/core.mjs KERNEL_HOME_RECEIPTS) and the manifest schema. */
24
+ export const SAME_WORK_FILE = ".oats-same-work.json";
25
+ /** A record larger than this is not one. */
26
+ export const RECORD_MAX = 4096;
27
+
28
+ /** The parent `home`'s record is bound to, or null: no file, not a regular file (a link is never
29
+ * followed), over RECORD_MAX bytes, unreadable, not JSON, another sameWorkApi or no non-empty string
30
+ * `parent`. Never throws. */
31
+ export function readSameWork(home) {
32
+ try {
33
+ const { bytes, size } = readFileHead(join(home, SAME_WORK_FILE), RECORD_MAX + 1);
34
+ if (size > RECORD_MAX) return null;
35
+ const record = JSON.parse(bytes.toString("utf8"));
36
+ if (!record || typeof record !== "object" || Array.isArray(record) || record.sameWorkApi !== SAME_WORK_API) return null;
37
+ return typeof record.parent === "string" && record.parent !== "" ? record.parent : null;
38
+ } catch { return null; }
39
+ }
40
+
41
+ /** Bind `home`'s flag to `parent` (an instance name), or remove the record when `parent` is null.
42
+ * → `{ changed }`. A record already bound to `parent` is no change: nothing is written. One bound to
43
+ * another (old) parent is rewritten to this one. A removal takes whatever stands at the name (an
44
+ * unreadable file, a link, a directory) and is a change only when a valid record was there. The caller
45
+ * decided `parent` (the home's recorded parentInstance) and holds the right to change the home. */
46
+ export function writeSameWork(home, parent, { now = () => new Date() } = {}) {
47
+ if (parent !== null && (typeof parent !== "string" || parent === "")) throw new TypeError("writeSameWork: parent is an instance name or null");
48
+ const path = join(home, SAME_WORK_FILE);
49
+ const before = readSameWork(home);
50
+ if (parent !== null && before === parent) return { changed: false };
51
+ let present;
52
+ try { present = lstatSync(path); } catch (e) { if (e?.code !== "ENOENT") throw e; }
53
+ // A directory at the name is no record, and a rename cannot replace it: it goes first. A link or a
54
+ // file is replaced by the rename itself, or removed here when the flag is cleared.
55
+ if (present && (parent === null || present.isDirectory())) rmSync(path, { recursive: true, force: true });
56
+ if (parent === null) return { changed: before !== null };
57
+ const bytes = JSON.stringify({ sameWorkApi: SAME_WORK_API, parent, at: now().toISOString() }) + "\n";
58
+ writeThroughPrivateFile(path, `${path}.tmp-${process.pid}`, bytes, 0o600);
59
+ return { changed: true };
60
+ }
61
+
62
+ /** THE rule: whether `home` does the same work as its parent, read against the row's current
63
+ * `parentInstance` (a non-empty string, else false): true only when the record is bound to exactly it. */
64
+ export function sameWorkOf(home, parentInstance) {
65
+ if (typeof parentInstance !== "string" || parentInstance === "") return false;
66
+ return readSameWork(home) === parentInstance;
67
+ }
@@ -38,6 +38,7 @@ import {
38
38
  retirementHomeChanged,
39
39
  rebaseUpgradeRetirementBaseline,
40
40
  planInstanceResources,
41
+ orderInstructionBlocks,
41
42
  findRetirementBaseline,
42
43
  officialPackageCatalog,
43
44
  } from "./core.mjs";
@@ -639,6 +640,7 @@ async function prepare(ctx, root, name, opts, { own = false } = {}) {
639
640
  const resolution = {
640
641
  resolutionApi: 1,
641
642
  modules,
643
+ instructionOrder: recordedInstructionOrder(meta, modules),
642
644
  payloads: meta.providers || {},
643
645
  payloadOrigins: Object.fromEntries(
644
646
  (meta.capabilityRuntime || []).map((c) => [
@@ -855,6 +857,7 @@ function derivedMetadata(p, tx, receipt) {
855
857
  path: block.file,
856
858
  materialized: true,
857
859
  });
860
+ orderInstructionBlocks(expected, outcome.blocks);
858
861
  const composition = {
859
862
  ...meta.composition,
860
863
  expected: expected.map((r) => ({
@@ -945,6 +948,21 @@ function derivedMetadata(p, tx, receipt) {
945
948
  resolutionRevision: resolution.revision,
946
949
  };
947
950
  }
951
+ /** The home's capability-block order, from the `instructions` it recorded (its AGENTS.md as
952
+ * spawned or last upgraded); a module with no recorded block follows, by name. An upgrade
953
+ * keeps that order, and the kernel's blocks close the recomposed AGENTS.md. */
954
+ function recordedInstructionOrder(meta, modules) {
955
+ const names = modules.map((m) => m.name),
956
+ order = [];
957
+ for (const row of Array.isArray(meta.instructions) ? meta.instructions : []) {
958
+ const name =
959
+ typeof row?.source === "string" && row.source.startsWith("capability:")
960
+ ? row.source.slice("capability:".length)
961
+ : null;
962
+ if (name && names.includes(name) && !order.includes(name)) order.push(name);
963
+ }
964
+ return [...order, ...names.filter((n) => !order.includes(n)).sort()];
965
+ }
948
966
  function keepPrevious(home, receipt, meta) {
949
967
  const root = join(home, ".oats/previous");
950
968
  if (existsSync(root)) realDir(root);
@@ -84,3 +84,65 @@ into a pattern.
84
84
 
85
85
  Folder-trust prompts are never confirmed. The captured trust screens in
86
86
  `test/fixtures/launch-prompts/` are negative test evidence.
87
+
88
+ # Resume-confirmation entries
89
+
90
+ `resume-confirmation.json` lists the dialogs Claude may show when OATS resumes a
91
+ lost session (`claude --resume <id> -- '<notice>'`) and Claude asks how to resume
92
+ a long, inactive conversation (Pro/Max plans). `launch-prompt-fixtures.mjs`
93
+ loads and validates it (`validateResumeConfirmationEntries`,
94
+ `RESUME_CONFIRMATION_ENTRIES`, `matchResumeConfirmation`), and
95
+ `launch-prompt-resume.mjs` watches the resumed pane for it. OATS only
96
+ **reports** this dialog ("waiting for you to choose"): it never answers it, never
97
+ sends a key, and never sets or reads an undocumented Claude variable.
98
+
99
+ ## Derived, not captured
100
+
101
+ No real capture of these dialogs exists. The entries are **derived** from
102
+ Claude's own strings: `claude-resume-cost-2.1.308` from the strings of the
103
+ Claude Code 2.1.308 binary, `claude-resume-conversation-documented` from Claude's
104
+ documentation (sessions page, "The 'Resume this conversation?' dialog") and the
105
+ 2.1.304 changelog. Each provenance row says so (`source: "derived"`, the Claude
106
+ version, the evidence). A `note` may record context strings the dialog shows (its
107
+ title, body, a `Don't ask me again` option); they are never required to match.
108
+
109
+ ## Matched by whole labels, not by equality
110
+
111
+ An entry is a list of option `labels`. It matches when **every** label appears
112
+ in the normalized screen (the same normalization as above) as a **whole label**:
113
+ an occurrence not preceded or followed by a letter or digit. So
114
+ `❯ 1. Resume from summary (instant, recommended)` matches the label
115
+ `Resume from summary`, and `Resume from summaryX` does not. One label of a pair
116
+ alone is no match. A label split across rows that each carry a side border
117
+ (`│`) does not normalize back to the label, and is no match.
118
+
119
+ A label match is acceptable here, where a `confirmation` entry keeps full-screen
120
+ equality, because of what a match does: a resume-confirmation match only
121
+ reports, so a false match costs a wrong "waiting" line, whereas a `confirmation`
122
+ entry gates a keystroke and stays exact.
123
+
124
+ Loading refuses an entry with a `selected` key, any `❯` anywhere (labels
125
+ included), an `input` other than `"none"`, a kind other than
126
+ `resume-confirmation`, fewer than two labels, an empty or not already normalized
127
+ label, or a provenance row without a `source`; ids are unique. The loaded entries
128
+ are frozen. The development-channel loader still refuses a `resume-confirmation`
129
+ kind in `dev-channel-confirmation.json`.
130
+
131
+ ## The watcher
132
+
133
+ `watchResumeConfirmation` polls the pane through the launch transport's
134
+ `snapshot` for at most 20 s. A matching screen reports the entry at once. It
135
+ stops early once the screen has shown a working session (Claude's
136
+ running-session banner, or the notice echoed as the session's first turn) with
137
+ no match for the settle window (2 s): Claude shows the dialog on the first
138
+ message after resuming, so a session showing that message without the dialog has
139
+ passed it. A false early stop costs only a missing "waiting" line, never a key. A
140
+ snapshot that fails (pane gone, replaced, not exclusively owned) stops it as
141
+ unobservable; an unknown screen at the bound is not a block.
142
+
143
+ ## Replacing a derived entry
144
+
145
+ When a real capture of a dialog exists, it replaces the derived entry in a
146
+ follow-up, reviewed change, with the raw capture (unedited
147
+ `tmux capture-pane -p`, no key sent) committed under
148
+ `test/fixtures/launch-prompts/` and a test that it matches.
@@ -0,0 +1,32 @@
1
+ {
2
+ "entries": [
3
+ {
4
+ "id": "claude-resume-cost-2.1.308",
5
+ "kind": "resume-confirmation",
6
+ "input": "none",
7
+ "labels": ["Resume from summary", "Resume full session as-is"],
8
+ "note": "Derived, not captured. The first option reads `Resume from summary (recommended)` or `Resume from summary (instant, recommended)`; the label matches either as a whole label. Context the dialog shows, recorded but never required: title `This session is <age> old and <n> tokens.`; body `Resuming the full session will consume a substantial portion of your usage limits. We recommend resuming from a summary.`; option `Don't ask me again`.",
9
+ "provenance": [
10
+ {
11
+ "source": "derived",
12
+ "claudeVersion": "2.1.308",
13
+ "evidence": "strings of the Claude Code 2.1.308 binary (the resume-cost dialog's option labels); no real capture of the dialog exists"
14
+ }
15
+ ]
16
+ },
17
+ {
18
+ "id": "claude-resume-conversation-documented",
19
+ "kind": "resume-confirmation",
20
+ "input": "none",
21
+ "labels": ["Resume this conversation?", "Start a new conversation"],
22
+ "note": "Derived, not captured: the dialog as Claude's documentation names it.",
23
+ "provenance": [
24
+ {
25
+ "source": "derived",
26
+ "claudeVersion": "2.1.304",
27
+ "evidence": "Claude Code documentation, sessions page, section \"The 'Resume this conversation?' dialog\"; Claude Code changelog 2.1.304; no real capture of the dialog exists"
28
+ }
29
+ ]
30
+ }
31
+ ]
32
+ }
@@ -102,6 +102,55 @@ export function matchFlagIgnoredEntry(text, entries = FLAG_IGNORED_ENTRIES) {
102
102
  return entries.find(entry => entry.kind === "flag-ignored" && blocks.includes(entry.text)) ?? null;
103
103
  }
104
104
 
105
+ /** Reject a resume-confirmation entry that could be anything but a report: it
106
+ * takes no input, carries no selection, and names at least two whole option
107
+ * labels, each already normalized. These entries are derived from Claude's
108
+ * strings and documentation, not captured (launch-prompt-fixtures/README.md),
109
+ * so they are matched by labels, and they never gate a key. */
110
+ export function validateResumeConfirmationEntries(entries) {
111
+ const bad = (entry, why) => { throw new Error(`resume-confirmation entry ${JSON.stringify(entry?.id ?? null)}: ${why}`); };
112
+ if (!Array.isArray(entries) || !entries.length) bad(null, "the list must be a non-empty array");
113
+ const ids = new Set();
114
+ for (const entry of entries) {
115
+ if (typeof entry?.id !== "string" || !entry.id || ids.has(entry.id)) bad(entry, "needs a unique id");
116
+ ids.add(entry.id);
117
+ if (entry.kind !== "resume-confirmation") bad(entry, "kind must be resume-confirmation");
118
+ if (entry.input !== "none") bad(entry, "a resume confirmation is only reported: input must be \"none\"");
119
+ if (Object.hasOwn(entry, "selected")) bad(entry, "a resume confirmation has no selected option");
120
+ if (JSON.stringify(entry).includes(SELECTION)) bad(entry, `a resume confirmation carries no ${SELECTION}`);
121
+ if (!Array.isArray(entry.labels) || entry.labels.length < 2) bad(entry, "labels must list at least two option labels");
122
+ if (entry.labels.some(label => typeof label !== "string" || !label || normalizeScreen(label) !== label)) bad(entry, "each label must be non-empty and already normalized");
123
+ if (!Array.isArray(entry.provenance) || !entry.provenance.length || entry.provenance.some(p => typeof p?.source !== "string" || !p.source)) {
124
+ bad(entry, "provenance must list rows, each with a source");
125
+ }
126
+ }
127
+ return deepFreeze(entries);
128
+ }
129
+
130
+ /** The shipped resume-confirmation entries: report-only, see launch-prompt-fixtures/README.md. */
131
+ export const RESUME_CONFIRMATION_ENTRIES = Object.freeze(validateResumeConfirmationEntries(
132
+ JSON.parse(readFileSync(new URL("./launch-prompt-fixtures/resume-confirmation.json", import.meta.url), "utf8")).entries));
133
+
134
+ const WORD = /[\p{L}\p{N}]/u;
135
+ /** Whether `label` occurs in `screen` as a whole label: an occurrence neither
136
+ * preceded nor followed by a letter or digit. */
137
+ function hasWholeLabel(screen, label) {
138
+ for (let at = screen.indexOf(label); at >= 0; at = screen.indexOf(label, at + 1)) {
139
+ const before = [...screen.slice(Math.max(0, at - 2), at)].at(-1) ?? "";
140
+ const next = screen.codePointAt(at + label.length);
141
+ const after = next === undefined ? "" : String.fromCodePoint(next);
142
+ if (!WORD.test(before) && !WORD.test(after)) return true;
143
+ }
144
+ return false;
145
+ }
146
+
147
+ /** The resume-confirmation entry whose labels ALL appear as whole labels in the
148
+ * normalized screen, or null. Report-only: a match never authorizes a key. */
149
+ export function matchResumeConfirmation(text, entries = RESUME_CONFIRMATION_ENTRIES) {
150
+ const screen = normalizeScreen(text);
151
+ return entries.find(entry => entry.kind === "resume-confirmation" && entry.labels.every(label => hasWholeLabel(screen, label))) ?? null;
152
+ }
153
+
105
154
  // Claude's running-session banner, as every captured session screen starts
106
155
  // (2.1.289 and 2.1.296): `Claude Code v<semver>`, after the logo's row. The logo
107
156
  // animates, so its row is any run of block elements (U+2580–U+259F) and spaces.
@@ -0,0 +1,55 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { RESUME_CONFIRMATION_ENTRIES, matchResumeConfirmation, normalizeScreen, showsClaudeSession } from "./launch-prompt-fixtures.mjs";
3
+ import { RESUME_WAITING } from "./session-resume-contract.mjs";
4
+
5
+ // The longest a resumed start is watched for Claude's resume-cost dialog.
6
+ const BOUND = 20000;
7
+ const wait = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+
9
+ /** Watch a resumed Claude session's pane for the dialog asking how to resume a
10
+ * long, inactive conversation, and report it. Report-only: this never sends a
11
+ * key and never calls transport.send; the operator answers the dialog.
12
+ *
13
+ * Polls transport.snapshot(target, remaining) until the bound (at most 20 s):
14
+ * - a screen matching a resume-confirmation entry → { waiting: "resume-confirmation", entry: <id> }, at once;
15
+ * - a working session held for settleMs with no match → { waiting: null, why: "session" };
16
+ * - a snapshot that throws (pane gone, replaced, not exclusively owned) → { waiting: null, why: "unobservable" };
17
+ * - anything else at the bound → { waiting: null, why: "bound" }: an unknown screen is not a block. */
18
+ export function watchResumeConfirmation({ transport, target, notice, limitMs = BOUND, intervalMs = 100, settleMs = 2000,
19
+ now = () => performance.now(), sleep = wait, entries = RESUME_CONFIRMATION_ENTRIES }) {
20
+ const limit = Math.min(Number.isFinite(limitMs) && limitMs > 0 ? limitMs : BOUND, BOUND);
21
+ const interval = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : 100;
22
+ const echoed = typeof notice === "string" ? normalizeScreen(notice) : "";
23
+ const deadline = now() + limit;
24
+ // When the current run of working-session screens without a match began.
25
+ let session;
26
+ // Hard iteration bound also protects against a broken injected clock.
27
+ for (let observations = 0; observations <= limit / interval; observations++) {
28
+ const left = deadline - now();
29
+ if (!(left > 0)) break;
30
+ let text;
31
+ try {
32
+ const screen = transport.snapshot(target, Math.max(1, Math.ceil(left)));
33
+ if (typeof screen?.text !== "string") throw new Error("no screen text");
34
+ text = screen.text;
35
+ } catch {
36
+ return { waiting: null, why: "unobservable" };
37
+ }
38
+ const entry = matchResumeConfirmation(text, entries);
39
+ if (entry) return { waiting: RESUME_WAITING.RESUME_CONFIRMATION, entry: entry.id };
40
+ // Claude shows this dialog on the first message after resuming, so a session
41
+ // that shows that message (the notice, echoed as its first turn) or Claude's
42
+ // running-session banner without the dialog, held for the settle window, has
43
+ // passed it. A false early stop costs only a missing "waiting" line, never a key.
44
+ if (showsClaudeSession(text) || (echoed && normalizeScreen(text).includes(echoed))) {
45
+ session ??= now();
46
+ if (now() - session >= settleMs) return { waiting: null, why: "session" };
47
+ } else {
48
+ session = undefined;
49
+ }
50
+ const rest = deadline - now();
51
+ if (!(rest > 0)) break;
52
+ sleep(Math.min(interval, rest));
53
+ }
54
+ return { waiting: null, why: "bound" };
55
+ }
@@ -33,6 +33,10 @@
33
33
  // group, gets SIGKILL (never the shell's own pid, which is reaped by then). A descendant that made
34
34
  // its own session or group (a daemon) is outside it, and group cleanup does not promise to end it.
35
35
  //
36
+ // A registered host: `oats server connect` reads the PATH of the host user's login shell with the
37
+ // same rules (bash, zsh or fish, `-l -i -c`, one nonce frame, bounded) over ssh (lib/servers.mjs);
38
+ // there the emitter is printf, since the host may have no node on ssh's own PATH.
39
+ //
36
40
  // Imports nothing but node's own modules: the kernel stays dependency-free.
37
41
  import { spawnSync } from "node:child_process";
38
42
  import { randomBytes } from "node:crypto";
@@ -59,7 +63,7 @@ const EMITTER = `const f=require("fs"),n=process.argv[1],b=Buffer.from("\\n${BEG
59
63
  const BASH_FUNCTION = /^BASH_FUNC_.+%%$/;
60
64
  /** One single-quoted word for `shell`: POSIX's `'…'\\''…'` for bash and zsh; fish's own form, where a
61
65
  * backslash and a quote inside single quotes are escaped with a backslash. */
62
- const quoteFor = (shell) => basename(shell) === "fish"
66
+ export const quoteFor = (shell) => basename(shell) === "fish"
63
67
  ? (s) => `'${String(s).replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`
64
68
  : (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
65
69
  const samePath = (a, b) => { try { return realpathSync(a) === realpathSync(b); } catch { return resolve(a) === resolve(b); } };
@@ -108,15 +112,11 @@ export function captureLoginEnvironment({ creatorEnv = process.env, instance = f
108
112
  if (r.status !== 0) return { failure: `your login shell exited with status ${r.status}`, notes };
109
113
  const printed = r.stdout;
110
114
  if (printed?.length > LOGIN_CAPTURE_MAX_BYTES) return { failure: "its answer was larger than 1 MiB", notes };
111
- // Exactly one start and one end delimiter of this nonce, in that order; anything else is no answer
112
- // or an ambiguous one, never a part of it taken as the whole.
113
- const begin = Buffer.from(`\n${BEGIN}${nonce}\n`), end = Buffer.from(`\n${END}${nonce}\n`);
114
- const from = printed ? printed.indexOf(begin) : -1, to = printed ? printed.indexOf(end) : -1;
115
- if (from < 0 && to < 0) return { failure: "your login shell gave no answer", notes };
116
- if (from < 0 || to < from + begin.length || printed.indexOf(begin, from + 1) >= 0 || printed.indexOf(end, to + 1) >= 0) return { failure: "its answer was not exactly one complete frame", notes };
117
- const data = printed.subarray(from + begin.length, to);
115
+ const frame = readLoginFrame(printed, nonce);
116
+ if (frame.none) return { failure: "your login shell gave no answer", notes };
117
+ if (frame.ambiguous) return { failure: "its answer was not exactly one complete frame", notes };
118
118
  let env;
119
- try { env = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data)); } catch { return { failure: "its answer was not one complete JSON object", notes }; }
119
+ try { env = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame.data)); } catch { return { failure: "its answer was not one complete JSON object", notes }; }
120
120
  if (!env || typeof env !== "object" || Array.isArray(env)) return { failure: "its answer was not one complete JSON object", notes };
121
121
  // Functions bash exports are code every bash in a pane would import: dropped, never carried.
122
122
  for (const name of Object.keys(env)) if (BASH_FUNCTION.test(name)) delete env[name];
@@ -127,6 +127,24 @@ export function captureLoginEnvironment({ creatorEnv = process.env, instance = f
127
127
  return { env: Object.assign(Object.create(null), env), notes };
128
128
  }
129
129
 
130
+ /** What a login shell printed, read for the one frame of `nonce`: exactly one start and one end
131
+ * delimiter of this nonce, in that order. → `{ data }` (the bytes between them), `{ none: true }`
132
+ * (neither delimiter) or `{ ambiguous: true }` (anything else), never a part taken as the whole. */
133
+ export function readLoginFrame(printed, nonce) {
134
+ const bytes = printed == null ? null : Buffer.from(printed);
135
+ const begin = Buffer.from(`\n${BEGIN}${nonce}\n`), end = Buffer.from(`\n${END}${nonce}\n`);
136
+ const from = bytes ? bytes.indexOf(begin) : -1, to = bytes ? bytes.indexOf(end) : -1;
137
+ if (from < 0 && to < 0) return { none: true };
138
+ if (from < 0 || to < from + begin.length || bytes.indexOf(begin, from + 1) >= 0 || bytes.indexOf(end, to + 1) >= 0) return { ambiguous: true };
139
+ return { data: bytes.subarray(from + begin.length, to) };
140
+ }
141
+
142
+ /** The shell code that prints the shell's own PATH as one frame of `nonce` (readLoginFrame), for a
143
+ * shell without node: printf in bash, zsh and fish alike (fish joins a quoted "$PATH" with colons). */
144
+ export function loginPathEmitter(nonce) {
145
+ return `printf '\\n%s\\n%s\\n%s\\n' ${BEGIN}${nonce} "$PATH" ${END}${nonce}`;
146
+ }
147
+
130
148
  /** The seed's session variables, per name from the first source that has it: (a) the creator, only
131
149
  * when it is not an instance; (b) for an instance, the recorded server's global environment; (c)
132
150
  * the platform's user session, read as data. */