@awebai/oats 0.69.5 → 0.69.6
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.
- package/bin/oats.mjs +78 -320
- package/docs/design/2026-09-26-okf-knowledge-operations.md +2 -0
- package/docs/design/2026-10-29-warm-reader.md +261 -0
- package/docs/design/README.md +4 -0
- package/docs/desktop-cli-api.md +250 -12
- package/docs/execution-targets.md +11 -2
- package/docs/implementation.md +26 -8
- package/docs/integrations.md +1 -1
- package/docs/knowledge.md +14 -7
- package/docs/named-test-runs.md +4 -0
- package/docs/official-catalog.md +3 -3
- package/docs/packages.md +12 -12
- package/docs/release-notes/v0.69.6.md +165 -0
- package/docs/schedules.md +8 -1
- package/docs/tui.md +21 -4
- package/docs/upgrading.md +9 -5
- package/docs/workspaces.md +2 -2
- package/lib/argv.mjs +41 -0
- package/lib/automation-scope.mjs +6 -4
- package/lib/automations.mjs +61 -11
- package/lib/captured-context.mjs +12 -0
- package/lib/hot-reads.mjs +21 -15
- package/lib/install-stamp.mjs +61 -0
- package/lib/instance-events.mjs +8 -6
- package/lib/instance-listing.mjs +13 -5
- package/lib/kernel-features.mjs +10 -0
- package/lib/local-edit.mjs +1 -1
- package/lib/local-inputs.mjs +3 -0
- package/lib/member-clone.mjs +15 -11
- package/lib/read-call.mjs +143 -0
- package/lib/reader.mjs +203 -0
- package/lib/remote.mjs +47 -6
- package/lib/resolved-deployment.mjs +12 -4
- package/lib/roster-read.mjs +199 -0
- package/lib/session-input.mjs +35 -11
- package/lib/workspace-read.mjs +160 -0
- package/package-catalog.json +2 -2
- package/package.json +1 -1
- package/packages/client/cli-locator.mjs +1 -0
- package/packages/client/cli-probe-contract.mjs +4 -2
- package/packages/client/deployment-observer.mjs +8 -3
- package/packages/client/deployment-panel.mjs +17 -1
- package/packages/client/deployment-read-cli.mjs +48 -27
- package/packages/client/own-codes.mjs +3 -0
- package/packages/client/warm-reader.mjs +241 -0
- package/packages/tui/lib/client.mjs +2 -1
- package/packages/tui/lib/read.mjs +59 -11
- package/skills/oats-getting-started/SKILL.md +2 -2
package/lib/reader.mjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/** lib/reader.mjs — `oats reader --stdio`, the warm reader (awebai/oats#1630): a process a client starts as its own
|
|
2
|
+
* child, which answers `oats status --json` and `oats workspace status --json` over its stdin and stdout, many
|
|
3
|
+
* times, with the kernel's own read code (lib/roster-read.mjs and lib/workspace-read.mjs, through
|
|
4
|
+
* lib/read-call.mjs). The contract is docs/desktop-cli-api.md "The warm reader"; the decisions,
|
|
5
|
+
* docs/design/2026-10-29-warm-reader.md.
|
|
6
|
+
*
|
|
7
|
+
* - Warm code, not warm data. Each request reads the deployment afresh: its answer is what `oats <argv>`, run by
|
|
8
|
+
* this install with the same environment and with cwd = `--dir`, prints and exits with. What the reader cannot
|
|
9
|
+
* answer that way it refuses, and the client runs the CLI.
|
|
10
|
+
* - One request at a time, in arrival order. The reads' module state is process-wide (lib/read-call.mjs
|
|
11
|
+
* READ_STATE), and so is the cwd: the children the reads run by name (tmux, git) resolve a relative PATH
|
|
12
|
+
* entry against it, so the reader chdirs to the request's `--dir` for the read and back to its install root
|
|
13
|
+
* when the request ends, never keeping a deployment directory that may go away. A second lane must first give
|
|
14
|
+
* each child its own cwd.
|
|
15
|
+
* - The install stamp (lib/install-stamp.mjs), taken before the kernel loads and again for each request: an install
|
|
16
|
+
* that changed under the reader (an upgrade, a Node upgrade) is never answered from the old code. That request and every queued one are refused E_READER_STALE, and the
|
|
17
|
+
* reader exits 0.
|
|
18
|
+
* - Its lifetime is the client's: stdin EOF or error, EPIPE on stdout, SIGTERM/SIGINT/SIGHUP end it. A request in
|
|
19
|
+
* flight is not answered, and its read session is closed from the `exit` handler, which kills its git
|
|
20
|
+
* children (a deployments-list lock, lib/dir-lock.mjs, exits from its own signal handler).
|
|
21
|
+
* - Its stdout carries protocol lines only: anything else written there (console.log) goes to stderr, and every
|
|
22
|
+
* child on the read path pipes or ignores its stdout.
|
|
23
|
+
* Kernel-private, not exported from `./core`. Dependency-free. */
|
|
24
|
+
import { isAbsolute, resolve } from "node:path";
|
|
25
|
+
import { expandInlineValues, flagValue } from "./argv.mjs";
|
|
26
|
+
import { inheritedContextRefusal } from "./captured-context.mjs";
|
|
27
|
+
import { listResolved } from "./deployments.mjs";
|
|
28
|
+
import { hotRead } from "./hot-reads.mjs";
|
|
29
|
+
import { installStamp } from "./install-stamp.mjs";
|
|
30
|
+
import { READER_API } from "./kernel-features.mjs";
|
|
31
|
+
import { callSession, parseMaxAge, readBudget, refusalAnswer, resetReadState } from "./read-call.mjs";
|
|
32
|
+
import { statusAnswer } from "./roster-read.mjs";
|
|
33
|
+
import { OATS_VERSION, PKG_ROOT } from "./version.mjs";
|
|
34
|
+
import { workspaceStatusAnswer } from "./workspace-read.mjs";
|
|
35
|
+
|
|
36
|
+
/** The reads a reader answers, by their hot-read names (lib/hot-reads.mjs hotRead): the hello's `reads`. */
|
|
37
|
+
export const READS = Object.freeze(["status", "workspace status"]);
|
|
38
|
+
/** The longest request line, in bytes, its newline not counted. */
|
|
39
|
+
export const LINE_LIMIT = 64 * 1024;
|
|
40
|
+
/** The longest `stderr` of an answer frame, in UTF-8 bytes. It is diagnostics only (the read session's notices), cut
|
|
41
|
+
* here so that a client's bound on an answer line, the CLI read's own output limit, is never passed for its sake. */
|
|
42
|
+
export const STDERR_LIMIT = 8 * 1024;
|
|
43
|
+
/** The modules the reads import lazily (by a literal `import()`), loaded before the hello so that the hello means
|
|
44
|
+
* ready: no request waits on a module load. test/reader-protocol.test.mjs pins it against the reads' closure. */
|
|
45
|
+
export const PRELOAD = Object.freeze({
|
|
46
|
+
"member-clone": () => import("./member-clone.mjs"),
|
|
47
|
+
drift: () => import("./drift.mjs"),
|
|
48
|
+
semver: () => import("./semver.mjs"),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const BAD_REQUEST = "E_READER_BAD_REQUEST", UNSUPPORTED = "E_READER_UNSUPPORTED", STALE = "E_READER_STALE", DEFECT = "E_READER_DEFECT";
|
|
52
|
+
const validId = (id) => (typeof id === "string" && [...id].length <= 64) || Number.isSafeInteger(id);
|
|
53
|
+
const refused = (id, code, message) => ({ id, refused: { code, message } });
|
|
54
|
+
|
|
55
|
+
/** Run the reader on this process's stdin and stdout until its client ends it. Returns once it is listening. `stamp`
|
|
56
|
+
* is the install's stamp taken before any kernel module loaded (bin/oats.mjs; lib/install-stamp.mjs), the baseline
|
|
57
|
+
* every request is checked against. */
|
|
58
|
+
export async function runReader({ stamp }) {
|
|
59
|
+
const stale = () => installStamp() !== stamp;
|
|
60
|
+
process.chdir(PKG_ROOT);
|
|
61
|
+
|
|
62
|
+
// stdout is the protocol's: every other write meant for it goes to stderr.
|
|
63
|
+
const protocol = process.stdout.write.bind(process.stdout);
|
|
64
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
65
|
+
const send = (frame) => new Promise((done) => { protocol(`${JSON.stringify(frame)}\n`, () => done()); });
|
|
66
|
+
const end = (code) => process.exit(code);
|
|
67
|
+
|
|
68
|
+
// The request in flight's read session: closed on any exit, which kills its git children.
|
|
69
|
+
let inFlight = null;
|
|
70
|
+
process.on("exit", () => inFlight?.closeNow());
|
|
71
|
+
for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.on(signal, () => {
|
|
72
|
+
// A deployments-list lock (lib/dir-lock.mjs) holds its own handler, which releases the lock and exits.
|
|
73
|
+
if (process.listenerCount(signal) === 1) end(code);
|
|
74
|
+
});
|
|
75
|
+
process.stdout.on("error", () => end(0)); // EPIPE: the client is gone
|
|
76
|
+
process.stdin.on("end", () => end(0));
|
|
77
|
+
process.stdin.on("error", () => end(0));
|
|
78
|
+
|
|
79
|
+
for (const load of Object.values(PRELOAD)) await load();
|
|
80
|
+
|
|
81
|
+
const queue = [];
|
|
82
|
+
let pending = [], pendingBytes = 0, oversize = false, working = false, stopped = false;
|
|
83
|
+
const take = (part, complete) => {
|
|
84
|
+
if (!oversize) {
|
|
85
|
+
pendingBytes += part.length;
|
|
86
|
+
if (pendingBytes > LINE_LIMIT) { oversize = true; pending = []; } else if (part.length) pending.push(part);
|
|
87
|
+
}
|
|
88
|
+
if (!complete) return;
|
|
89
|
+
queue.push(oversize ? { oversize: true } : { line: Buffer.concat(pending).toString("utf8") });
|
|
90
|
+
pending = []; pendingBytes = 0; oversize = false;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/** Refuse `id` and every queued request as stale, then exit 0. */
|
|
94
|
+
const refuseStale = async (id) => {
|
|
95
|
+
stopped = true;
|
|
96
|
+
process.stdin.pause();
|
|
97
|
+
const message = "the kernel install changed since this reader started: run the read with the CLI, and start a new reader";
|
|
98
|
+
await send(refused(id, STALE, message));
|
|
99
|
+
for (const item of queue.splice(0)) await send(refused(requestOf(item).id ?? null, STALE, message));
|
|
100
|
+
end(0);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const handle = async (item) => {
|
|
104
|
+
const request = requestOf(item);
|
|
105
|
+
if (request.refusal) return send(refused(request.id ?? null, BAD_REQUEST, request.refusal));
|
|
106
|
+
const { id, argv } = request;
|
|
107
|
+
if (stale()) return refuseStale(id);
|
|
108
|
+
let frame;
|
|
109
|
+
try {
|
|
110
|
+
frame = await answer(argv, (session) => { inFlight = session; });
|
|
111
|
+
} catch (e) {
|
|
112
|
+
stopped = true;
|
|
113
|
+
process.stderr.write(`${e?.stack ?? e}\n`);
|
|
114
|
+
await send(refused(id, DEFECT, `the reader failed: ${e?.message ?? e}; run the read with the CLI`));
|
|
115
|
+
return end(1); // per-request state may be half reset
|
|
116
|
+
}
|
|
117
|
+
if (stale()) return refuseStale(id);
|
|
118
|
+
return send({ id, ...frame });
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const pump = async () => {
|
|
122
|
+
if (working) return;
|
|
123
|
+
working = true;
|
|
124
|
+
try { while (queue.length && !stopped) await handle(queue.shift()); } finally { working = false; }
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
process.stdin.on("data", (chunk) => {
|
|
128
|
+
if (stopped) return;
|
|
129
|
+
let start = 0;
|
|
130
|
+
for (let nl = chunk.indexOf(10); nl !== -1; nl = chunk.indexOf(10, start)) { take(chunk.subarray(start, nl), true); start = nl + 1; }
|
|
131
|
+
take(chunk.subarray(start), false);
|
|
132
|
+
pump();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
await send({ readerApi: READER_API, version: OATS_VERSION, reads: READS });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** `text` cut to at most STDERR_LIMIT bytes of UTF-8, at a character boundary. */
|
|
139
|
+
export function boundedStderr(text) {
|
|
140
|
+
if (Buffer.byteLength(text) <= STDERR_LIMIT) return text;
|
|
141
|
+
let out = "", bytes = 0;
|
|
142
|
+
for (const ch of text) {
|
|
143
|
+
const n = Buffer.byteLength(ch);
|
|
144
|
+
if (bytes + n > STDERR_LIMIT) break;
|
|
145
|
+
out += ch;
|
|
146
|
+
bytes += n;
|
|
147
|
+
}
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A queued line as a request: `{ id, argv }`, or `{ id?, refusal }` for a line that is none. */
|
|
152
|
+
function requestOf(item) {
|
|
153
|
+
if (item.oversize) return { refusal: `a request line is at most ${LINE_LIMIT} bytes` };
|
|
154
|
+
let request;
|
|
155
|
+
try { request = JSON.parse(item.line); } catch { return { refusal: "a request is one JSON object on one line" }; }
|
|
156
|
+
if (!request || typeof request !== "object" || Array.isArray(request)) return { refusal: "a request is one JSON object on one line" };
|
|
157
|
+
if (!validId(request.id)) return { refusal: "a request's id is a string of at most 64 characters or a safe integer" };
|
|
158
|
+
if (!Array.isArray(request.argv) || !request.argv.every((a) => typeof a === "string")) return { id: request.id, refusal: "a request's argv is an array of strings" };
|
|
159
|
+
return { id: request.id, argv: request.argv };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** One request's answer frame (without its id): `{ exit, answer, stderr? }`, or `{ refused }`. `track` is told the
|
|
163
|
+
* read session while it is open. Accepted: what hotRead classifies as one of READS, read with --json, with an
|
|
164
|
+
* absolute --dir. Then the CLI's own dispatch, in its order: the flag syntax, --max-age, the inherited context,
|
|
165
|
+
* then the read itself with its deployments-list observer. */
|
|
166
|
+
async function answer(argv, track) {
|
|
167
|
+
const unsupported = (message) => ({ refused: { code: UNSUPPORTED, message: `${message}: run the read with the CLI` } });
|
|
168
|
+
const read = hotRead(argv);
|
|
169
|
+
if (!read || !READS.includes(read.form)) return unsupported(`this reader answers ${READS.map((r) => `oats ${r}`).join(" and ")} only`);
|
|
170
|
+
const { argv: args, problem, inline } = expandInlineValues(argv);
|
|
171
|
+
if (!args.includes("--json")) return unsupported("a request reads with --json");
|
|
172
|
+
const given = flagValue(args, inline, "dir");
|
|
173
|
+
if (typeof given !== "string" || !isAbsolute(given)) return unsupported("a request names its deployment with an absolute --dir");
|
|
174
|
+
const dir = resolve(given);
|
|
175
|
+
resetReadState(); // a refusal below carries no warning a previous request noted
|
|
176
|
+
try { process.chdir(dir); } catch (e) { return unsupported(`--dir ${dir} cannot be the working directory (${e.code ?? e.message})`); }
|
|
177
|
+
try {
|
|
178
|
+
const said = ({ exit, answer: doc, stderr }) => ({ exit, answer: doc, ...(stderr ? { stderr: boundedStderr(stderr) } : {}) });
|
|
179
|
+
if (problem) return said(refusalAnswer("E_BAD_ARGS", problem));
|
|
180
|
+
let maxAge = null;
|
|
181
|
+
if (args.includes("--max-age")) {
|
|
182
|
+
const parsed = parseMaxAge(flagValue(args, inline, "max-age"));
|
|
183
|
+
if (parsed.refusal) return said(refusalAnswer(parsed.refusal.code, parsed.refusal.message));
|
|
184
|
+
maxAge = parsed.maxAge;
|
|
185
|
+
}
|
|
186
|
+
const captured = inheritedContextRefusal(process.env);
|
|
187
|
+
if (captured) return said(refusalAnswer(captured.code, captured.message, captured.details));
|
|
188
|
+
const session = callSession({ maxAge, budgetMs: readBudget(process.env) });
|
|
189
|
+
track(session);
|
|
190
|
+
try {
|
|
191
|
+
const cacheDir = process.env.OATS_REMOTE_CACHE ? resolve(process.env.OATS_REMOTE_CACHE) : undefined;
|
|
192
|
+
const ctx = { dir, maxAge, session: () => session, cacheDir, deployments: listResolved };
|
|
193
|
+
if (read.form === "workspace status") return said(await workspaceStatusAnswer(ctx));
|
|
194
|
+
const team = args.includes("--team");
|
|
195
|
+
return said(await statusAnswer({ ...ctx, dir: team ? null : dir, team }));
|
|
196
|
+
} finally {
|
|
197
|
+
await session.close();
|
|
198
|
+
track(null);
|
|
199
|
+
}
|
|
200
|
+
} finally {
|
|
201
|
+
try { process.chdir(PKG_ROOT); } catch { /* the install is gone: the stamp says so */ }
|
|
202
|
+
}
|
|
203
|
+
}
|
package/lib/remote.mjs
CHANGED
|
@@ -181,7 +181,7 @@ export const TREE_BUDGET = 64 * 1024 * 1024; // fetchRemoteTree: 64 MiB pe
|
|
|
181
181
|
export const SMALL_BLOB_LIMIT = 64 * 1024;
|
|
182
182
|
/** The oldest git that keeps a partial cache honest: GIT_NO_LAZY_FETCH arrived in 2.45; an older git fetches a
|
|
183
183
|
* missing blob on its own, or dies trying. With an older git every cache fetches whole trees. */
|
|
184
|
-
export const PARTIAL_FETCH_GIT = [2, 45];
|
|
184
|
+
export const PARTIAL_FETCH_GIT = Object.freeze([2, 45]);
|
|
185
185
|
export const GIT_TIMEOUT_MS = 30_000;
|
|
186
186
|
/** The fetch of a commit into the cache: the first one transfers the commit's whole tree, which for a
|
|
187
187
|
* large workspace host takes far longer than GIT_TIMEOUT_MS (awebai/oats#362). */
|
|
@@ -319,7 +319,7 @@ export function parseRepoRef(text, options = undefined) {
|
|
|
319
319
|
|
|
320
320
|
/** The operator's own ssh command (GIT_SSH_COMMAND, else core.sshCommand, else `ssh`),
|
|
321
321
|
* ALWAYS with `-o BatchMode=yes` appended so ssh can never prompt for a passphrase or
|
|
322
|
-
* host key. Resolved once per process; `-o` after the operator's flags is valid for ssh
|
|
322
|
+
* host key. Resolved once per process (per read in a process answering many: resetSshCommand); `-o` after the operator's flags is valid for ssh
|
|
323
323
|
* and for every ssh-compatible wrapper that forwards its argv. */
|
|
324
324
|
let sshCommandCache;
|
|
325
325
|
export function sshCommand() {
|
|
@@ -332,6 +332,9 @@ export function sshCommand() {
|
|
|
332
332
|
sshCommandCache = /(?:^|\s)-o\s*BatchMode=yes(?:\s|$)/i.test(base) ? base : `${base} -o BatchMode=yes`;
|
|
333
333
|
return sshCommandCache;
|
|
334
334
|
}
|
|
335
|
+
/** Resolve the ssh command again at its next use: a process that answers many reads (lib/read-call.mjs)
|
|
336
|
+
* reads core.sshCommand afresh for each, as a fresh CLI does. */
|
|
337
|
+
export function resetSshCommand() { sshCommandCache = undefined; }
|
|
335
338
|
|
|
336
339
|
/** The environment every git child of the kernel that may reach a remote runs under: it never prompts (no
|
|
337
340
|
* terminal prompt, askpass refused, ssh in BatchMode) and never fetches a missing object on its own. */
|
|
@@ -351,6 +354,9 @@ export function gitEnv() {
|
|
|
351
354
|
/** Every git child this module started that has not exited yet (runGit's and the batch readers'): what
|
|
352
355
|
* reapOnExit still has to end when the process exits. */
|
|
353
356
|
const liveChildren = new Set();
|
|
357
|
+
/** How many git children of this module are still live: none once every read session that started them
|
|
358
|
+
* is closed (a process answering many reads holds that after each one; test/read-call-equivalence.test.mjs). */
|
|
359
|
+
export function liveGitChildren() { return liveChildren.size; }
|
|
354
360
|
/** The exit path (`process.on("exit")`, ReadSession.closeNow) cannot wait for a timer, so the graceful kill
|
|
355
361
|
* is done synchronously and bounded: every live git group gets SIGTERM, the process blocks for at most
|
|
356
362
|
* EXIT_GRACE_MS (git removes its lock files on SIGTERM in far less), then SIGKILL ends what is left. A
|
|
@@ -1400,8 +1406,7 @@ export function pruneStores(root, { fingerprint = kernelFingerprint(), limits =
|
|
|
1400
1406
|
if (st && now - st.mtimeMs > L.staleFingerprintMs && remove(dir, { recursive: true })) removed++;
|
|
1401
1407
|
}
|
|
1402
1408
|
}
|
|
1403
|
-
const observed
|
|
1404
|
-
for (const f of list(observed)) {
|
|
1409
|
+
for (const observed of [join(root, ".observed"), join(root, ".observed-facts")]) for (const f of list(observed)) {
|
|
1405
1410
|
const p = join(observed, f), st = stat(p);
|
|
1406
1411
|
if (st && now - st.mtimeMs > (f.endsWith(".tmp") ? L.staleTempMs : L.staleObservationMs) && remove(p)) removed++;
|
|
1407
1412
|
}
|
|
@@ -1430,6 +1435,39 @@ function writeObservation(root, ref, atArgs, obs) {
|
|
|
1430
1435
|
writeAtomicQuiet(observationFile(root, ref, atArgs), JSON.stringify({ v: 1, key: ref.key, args: atArgs, urlDigest: sha256(ref.url), commit: obs.commit, ref: obs.ref, observedAt: obs.observedAt }));
|
|
1431
1436
|
}
|
|
1432
1437
|
|
|
1438
|
+
/** --max-age over a remote fact that is not a head (awebai/oats#1630: the gh login a status display places
|
|
1439
|
+
* automations with; lib/automations.mjs ghLogin's `lookup`), reused as a head is. `kind` names the fact; `parts`
|
|
1440
|
+
* everything its answer depends on: a record is reused only under the same parts, and the digest of `kind` and
|
|
1441
|
+
* `parts` names the record, which holds no part. A record is reusable while it is at most the session's maxAge
|
|
1442
|
+
* old (and dated at most 5 s ahead); a successful live answer is recorded, and a failed one removes the record
|
|
1443
|
+
* (forget), so the next read asks again. A reused fact counts in the session's observation block as a reused
|
|
1444
|
+
* head does (`reused: true`, `observedAt` the oldest); a live one does not. Records live beside the head
|
|
1445
|
+
* observations (`<cache>/.observed-facts`), private and written atomically.
|
|
1446
|
+
* → { reuse() → value | undefined, record(value), forget() }, or null without a session. */
|
|
1447
|
+
export function factObservation(options, kind, parts) {
|
|
1448
|
+
const session = sessionOf(options);
|
|
1449
|
+
if (!session) return null;
|
|
1450
|
+
const digest = sha256([kind, ...parts].join("\0"));
|
|
1451
|
+
const file = join(cacheRootOf(options), ".observed-facts", `${digest}.json`);
|
|
1452
|
+
return {
|
|
1453
|
+
reuse() {
|
|
1454
|
+
if (session.maxAge <= 0) return undefined;
|
|
1455
|
+
const rec = readStoreFile(file);
|
|
1456
|
+
if (!rec || typeof rec !== "object" || rec.v !== 1 || rec.kind !== kind || rec.digest !== digest || !("value" in rec)) return undefined;
|
|
1457
|
+
const at = typeof rec.observedAt === "string" ? Date.parse(rec.observedAt) : NaN, now = session.now();
|
|
1458
|
+
if (!Number.isFinite(at) || at > now + 5000 || now - at > session.maxAge * 1000) return undefined;
|
|
1459
|
+
session.used.set(`fact\0${digest}`, { observedAt: rec.observedAt, reused: true });
|
|
1460
|
+
return rec.value;
|
|
1461
|
+
},
|
|
1462
|
+
record(value) {
|
|
1463
|
+
writeAtomicQuiet(file, JSON.stringify({ v: 1, kind, digest, value, observedAt: new Date(session.now()).toISOString() }));
|
|
1464
|
+
},
|
|
1465
|
+
forget() {
|
|
1466
|
+
try { rmSync(file, { force: true }); } catch { /* a record that cannot be removed is still read only within --max-age */ }
|
|
1467
|
+
},
|
|
1468
|
+
};
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1433
1471
|
/** The COMMIT <oid> peels to, when <oid> is present in the cache and is a commit or an
|
|
1434
1472
|
* annotated tag chain ending in one; null on a missing object, a pruned store, or a
|
|
1435
1473
|
* tag/tree/blob that does not peel to a commit. (`rev-parse <oid>^{commit}` peels.)
|
|
@@ -1581,7 +1619,7 @@ const olderGitNotice = (version, ref) =>
|
|
|
1581
1619
|
|
|
1582
1620
|
/** One strict probe per exec: share in-flight work and retain only parsed success. A failed or abandoned
|
|
1583
1621
|
* probe cannot authorize rebuilding a cache, nor erase a newer probe installed by a retry. */
|
|
1584
|
-
|
|
1622
|
+
let gitVersions = new WeakMap();
|
|
1585
1623
|
async function probeGitVersion(exec, opts = undefined) {
|
|
1586
1624
|
if (opts?.signal?.aborted) throw abortError(opts.signal);
|
|
1587
1625
|
let version = gitVersions.get(exec);
|
|
@@ -1968,7 +2006,10 @@ const isHeadAt = (at) => at === undefined || at === null || at === "" || at ===
|
|
|
1968
2006
|
* `git config --get`, in the observation's own environment): asked once per command (its session) and exec, or
|
|
1969
2007
|
* once per exec without a session. Unset (exit 1) → false; any value, or a read that fails otherwise (an abort
|
|
1970
2008
|
* included) → true: today's argv, never an error. */
|
|
1971
|
-
|
|
2009
|
+
let protocolPins = new WeakMap();
|
|
2010
|
+
/** Ask git's version and the protocol pin again at their next use: a process that answers many reads
|
|
2011
|
+
* (lib/read-call.mjs) probes them afresh for each, as a fresh CLI does (a git upgraded meanwhile). */
|
|
2012
|
+
export function resetGitProbes() { gitVersions = new WeakMap(); protocolPins = new WeakMap(); }
|
|
1972
2013
|
function protocolPinned(exec, session) {
|
|
1973
2014
|
const memo = session?.protocolPins ?? protocolPins;
|
|
1974
2015
|
let pinned = memo.get(exec);
|
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* The resolvers report the deployment directory they found: `loadLocal` (lib/workspace.mjs) the
|
|
5
5
|
* directory of the oats-local.yaml its walk up found, as spelled; `ensureRoot` (lib/agents-root.mjs) the
|
|
6
6
|
* directory of the canonical agents root, `canonical`. The observer is called once, when the
|
|
7
|
-
* process exits,
|
|
7
|
+
* process exits (or, in a process answering many reads, when each read ends: lib/read-call.mjs), with
|
|
8
|
+
* the root the command settled on: the first canonical one reported, else the
|
|
8
9
|
* first one, and whether it is canonical. So a command that resolves its canonical root is compared
|
|
9
10
|
* with that root, never with an earlier spelling of the same deployment. Nothing happens until the
|
|
10
11
|
* CLI sets an observer for this process (the commands in its one table): library callers and tests
|
|
@@ -14,11 +15,18 @@
|
|
|
14
15
|
let observer = null;
|
|
15
16
|
const reported = { canonical: null, spelled: null };
|
|
16
17
|
|
|
17
|
-
/** Observe the deployment this process resolves; called once, at exit.
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
/** Observe the deployment this process resolves; called once, at exit. `atExit: false`: the caller
|
|
19
|
+
* settles it itself (settleResolvedDeployment), as a process answering many reads does at the end of
|
|
20
|
+
* each one (lib/read-call.mjs). */
|
|
21
|
+
export function observeResolvedDeployment(fn, { atExit = true } = {}) {
|
|
22
|
+
if (!observer && atExit) process.once("exit", settleResolvedDeployment);
|
|
20
23
|
observer = fn;
|
|
21
24
|
}
|
|
25
|
+
/** Forget what the resolvers reported, keeping the observer: the start of one read in a process that
|
|
26
|
+
* answers many (lib/read-call.mjs). */
|
|
27
|
+
export function resetResolvedDeployment() {
|
|
28
|
+
reported.canonical = reported.spelled = null;
|
|
29
|
+
}
|
|
22
30
|
|
|
23
31
|
/** A resolver found the deployment directory `dir` (`canonical`: its canonical spelling). */
|
|
24
32
|
export function resolvedDeployment(dir, { canonical = false } = {}) {
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/** lib/roster-read.mjs — `oats status`, the roster read (awebai/oats#1630): the deployment's agents and
|
|
2
|
+
* instances, each instance's workspace drift, and its workspace identity. One implementation behind the
|
|
3
|
+
* CLI (bin/oats.mjs status) and a process that answers it many times (lib/read-call.mjs, whose header
|
|
4
|
+
* describes the context and the answer). `statusAnswer(ctx)` is the `--json` answer, a bare document
|
|
5
|
+
* (never an envelope) or a failure envelope; `statusView(ctx)` the data bin's text renderer reads. A
|
|
6
|
+
* leaf a hot read loads (lib/hot-reads.mjs): never core.mjs. Kernel-private, not exported from `./core`. */
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { ensureRoot } from "./agents-root.mjs";
|
|
10
|
+
import { legacyCapturedHomes, legacyLocalAgents, listInstances } from "./instance-listing.mjs";
|
|
11
|
+
import { KERNEL_FEATURES } from "./kernel-features.mjs";
|
|
12
|
+
import { readLockIfPresent } from "./packages.mjs";
|
|
13
|
+
import { answerWarnings, refuse, runRead } from "./read-call.mjs";
|
|
14
|
+
import { lastObservedCommit, parseRepoRef, peekAtCommit } from "./remote.mjs";
|
|
15
|
+
import { readSessionViewer } from "./session-viewer.mjs";
|
|
16
|
+
import { teamModel } from "./teams.mjs";
|
|
17
|
+
import { loadLocal, memberRowByKey } from "./workspace.mjs";
|
|
18
|
+
|
|
19
|
+
/** `oats status --json`: → `{ exit, answer, stderr }` (lib/read-call.mjs). `ctx.team`: `--team` was given. */
|
|
20
|
+
export function statusAnswer(ctx) {
|
|
21
|
+
return runRead(ctx, async (call) => ({ answer: statusDocument(call, await statusFacts(call, ctx)) }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** `oats status` in text mode: → `{ exit, answer, view, stderr }`, `view` `{ root, agents, ws, problems }`
|
|
25
|
+
* (`ws`: statusDrift's answer) when it did not refuse, `answer` the failure envelope when it did. */
|
|
26
|
+
export function statusView(ctx) {
|
|
27
|
+
return runRead(ctx, async (call) => ({ view: await statusFacts(call, ctx) }));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The problems doctor and status share for a v2 deployment: what OATS 0.25 left
|
|
31
|
+
* under local-agents/ (named, never read), and the captured homes under the agents root
|
|
32
|
+
* (`records`: legacyCapturedHomes'). */
|
|
33
|
+
export function legacyLayoutProblems(root, { records } = {}) {
|
|
34
|
+
return [legacyLocalAgents(root), legacyCapturedHomes(root, { records })].filter(Boolean);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function statusFacts(call, { dir, team = false }) {
|
|
38
|
+
if (team) refuse("E_BAD_ARGS", "status --team was removed with the classic team scope: `oats status` in the deployment lists every instance, and `oats workspace status` shows the members");
|
|
39
|
+
let root;
|
|
40
|
+
try { root = ensureRoot(dir); }
|
|
41
|
+
catch (e) { if (e?.code === "E_NO_DEPLOYMENT") refuse("E_NO_DEPLOYMENT", e.message, e.details ?? e.provenance); throw e; }
|
|
42
|
+
// Each home's instance.json, as the listing read it: parsed once for the whole read.
|
|
43
|
+
const records = new Map();
|
|
44
|
+
const data = listInstances(root, undefined, undefined, { records });
|
|
45
|
+
const ws = await statusDrift(data, call, dir);
|
|
46
|
+
const problems = legacyLayoutProblems(root, { records });
|
|
47
|
+
return { root, agents: data, ws, problems };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function statusDocument(call, { root, agents: data, ws, problems }) {
|
|
51
|
+
// The soul key (feature launch-preference): what souls.launch and `oats soul teams <key>` use —
|
|
52
|
+
// from the instances' records, so it needs no remote.
|
|
53
|
+
for (const a of data) a.key = agentSoulKey(a);
|
|
54
|
+
if (ws) for (const a of data) {
|
|
55
|
+
const stamp = ws.souls.get(a.name);
|
|
56
|
+
if (stamp) a.soulSource = { repoKey: stamp.repoKey, commit: stamp.commit, path: stamp.path, ...(stamp.current ? { current: stamp.current, status: stamp.current === stamp.commit ? "current" : "moved" } : {}) };
|
|
57
|
+
for (const i of a.instances || []) {
|
|
58
|
+
const key = i.home ?? `${a.name}/${i.instance}`;
|
|
59
|
+
const rows = ws.drift.get(key);
|
|
60
|
+
if (rows) i.modules = rows.map((r) => ({ name: r.module, from: r.from, commit: r.recorded?.commit ?? null, current: r.current, status: r.status, ...(r.reason ? { reason: r.reason } : {}) }));
|
|
61
|
+
const s = ws.soul.get(key);
|
|
62
|
+
if (s) i.soul = { repoKey: s.repoKey, commit: s.commit, current: s.current?.commit ?? null, status: s.status, ...(s.reason ? { reason: s.reason } : {}), ...(s.package ? { package: s.package, version: s.version, currentVersion: s.current?.version ?? null } : {}) };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const observation = call.maxAge === null ? {} : { observation: call.observation() };
|
|
66
|
+
// `features` (feature server-probe-features): this kernel's own list, as `version --json` answers
|
|
67
|
+
// it, so a remote roster relays the host's without probing it. Never part of a reused observation.
|
|
68
|
+
return { root, agents: data, ...observation, features: KERNEL_FEATURES, sessionViewer: readSessionViewer(), ...(ws ? { workspace: { ...(ws.unreachable ? { reachable: false, ...ws.unreachable } : { reachable: true }), ...workspaceIdentity(ws.local, ws.discovery, call.remoteOptions) } } : {}), ...(problems.length ? { problems } : {}), ...answerWarnings() };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Workspace drift for `oats status` (decision 17: shown, not prevented). ONE discovery over
|
|
72
|
+
* the remotes serves every instance; `driftOf` compares each instance's recorded modules to
|
|
73
|
+
* the members' current state (and package modules to the lock), `soulDriftOf` the instance's
|
|
74
|
+
* recorded SOUL SOURCE (instance.json.workspace.soul) to its member's current commit. Offline →
|
|
75
|
+
* { unreachable }. Returns null when the deployment is not a workspace deployment (no
|
|
76
|
+
* oats-local.yaml). `souls` maps each workspace soul NAME (agents/<name>/.oats-soul-source.json
|
|
77
|
+
* present) to its stamp — the roster's `repo:` column for a workspace soul. */
|
|
78
|
+
async function statusDrift(data, call, dir) {
|
|
79
|
+
let ctx;
|
|
80
|
+
try { ctx = loadLocal(dir); }
|
|
81
|
+
catch (e) {
|
|
82
|
+
if (e?.code === "E_LOCAL_MISSING") return null;
|
|
83
|
+
// A 0.25 oats-config.yaml inside the deployment: the typed migration error, never a stack.
|
|
84
|
+
if (e?.code === "E_CONFIG_BROKEN") refuse(e.code, e.message, e.details);
|
|
85
|
+
throw e;
|
|
86
|
+
}
|
|
87
|
+
const hasModules = (i) => i.modules && typeof i.modules === "object" && Object.keys(i.modules).length > 0;
|
|
88
|
+
const hasSoul = (i) => i.workspace && typeof i.workspace === "object" && i.workspace.soul && typeof i.workspace.soul === "object" && typeof i.workspace.soul.repoKey === "string";
|
|
89
|
+
// Workspace souls of this roster: the stamp ensureWorkspaceSoul leaves beside the soul pointer.
|
|
90
|
+
const souls = new Map();
|
|
91
|
+
for (const a of data) {
|
|
92
|
+
if (!a.dir) continue;
|
|
93
|
+
try { const stamp = JSON.parse(readFileSync(join(a.dir, ".oats-soul-source.json"), "utf8")); if (stamp && typeof stamp.repoKey === "string") souls.set(a.name, { repoKey: stamp.repoKey, commit: typeof stamp.commit === "string" ? stamp.commit : null, path: stamp.path ?? null, ...(typeof stamp.package === "string" ? { package: stamp.package, version: stamp.version ?? null } : {}) }); }
|
|
94
|
+
catch { /* not a workspace soul (classic, or an unreadable stamp) */ }
|
|
95
|
+
}
|
|
96
|
+
const anything = data.some((a) => (a.instances || []).some((i) => hasModules(i) || hasSoul(i)));
|
|
97
|
+
if (!anything) return { drift: new Map(), soul: new Map(), souls, unreachable: null, local: ctx.local, discovery: null };
|
|
98
|
+
const deploymentDir = dirname(ctx.path);
|
|
99
|
+
let lock = null;
|
|
100
|
+
try { lock = readLockIfPresent(deploymentDir); } catch { lock = null; }
|
|
101
|
+
let discovery;
|
|
102
|
+
// The standalone view (decisions 10/25) is a discovery too: drift of a standalone
|
|
103
|
+
// instance is computed against its member's current state, not reported "unreachable".
|
|
104
|
+
try { const { discoverOrStandalone } = await import("./member-clone.mjs"); discovery = await discoverOrStandalone(ctx.local, { lock, remoteOptions: call.remoteOptions() }); }
|
|
105
|
+
catch (e) {
|
|
106
|
+
const reason = e?.details?.reason ? `${e.code}: ${e.details.reason}` : (e?.code || e?.message || "unknown");
|
|
107
|
+
return { drift: new Map(), soul: new Map(), souls, unreachable: { code: e?.code ?? null, reason, message: e?.message ?? String(e) }, local: ctx.local, discovery: null };
|
|
108
|
+
}
|
|
109
|
+
const { driftOf, soulDriftOf } = await import("./drift.mjs");
|
|
110
|
+
const drift = new Map();
|
|
111
|
+
const soul = new Map();
|
|
112
|
+
for (const a of data) for (const i of a.instances || []) {
|
|
113
|
+
const key = i.home ?? `${a.name}/${i.instance}`;
|
|
114
|
+
if (hasModules(i)) { try { drift.set(key, driftOf(i, discovery, { lock })); } catch { /* an unreadable module record shows as no drift rows */ } }
|
|
115
|
+
if (hasSoul(i)) { try { const row = soulDriftOf(i, discovery); if (row) soul.set(key, row); } catch { /* an unreadable soul record shows as no soul row */ } }
|
|
116
|
+
}
|
|
117
|
+
// The roster's soul row reflects the CURRENT member commit too (the pointer may lag a moved member).
|
|
118
|
+
// First match per key, as `find` gave, from indexes built once (not a scan per agent).
|
|
119
|
+
const packageSoulAt = new Map();
|
|
120
|
+
for (const p of discovery.packageSouls || []) { const k = `${p.package}\0${p.path}`; if (!packageSoulAt.has(k)) packageSoulAt.set(k, p); }
|
|
121
|
+
for (const [, stamp] of souls) {
|
|
122
|
+
if (typeof stamp.package === "string") { const now = packageSoulAt.get(`${stamp.package}\0${stamp.path}`); if (now) stamp.current = now.commit; continue; }
|
|
123
|
+
const member = memberRowByKey(discovery.members, stamp.repoKey);
|
|
124
|
+
if (member && typeof member.commit === "string" && (member.confirmed || (discovery.standalone === true && member.key === discovery.key))) stamp.current = member.commit;
|
|
125
|
+
}
|
|
126
|
+
return { drift, soul, souls, unreachable: null, local: ctx.local, discovery };
|
|
127
|
+
}
|
|
128
|
+
/** The deployment's workspace identity in `oats status --json` (feature workspace-identity), read
|
|
129
|
+
* OFFLINE. `key` is the workspace HOST's canonical repo key (parseRepoRef(...).key) and `ref` the
|
|
130
|
+
* reference as oats-local.yaml writes it. The host is the one this run observed, else the one this
|
|
131
|
+
* machine's parsed cache knows: `ref` itself when the cache holds its workspace file, or the host its
|
|
132
|
+
* cached oats-membership.yaml names when `ref` is a member ("workspace"). A member whose host is not
|
|
133
|
+
* known keys as itself ("member"); a ref nothing is known of is taken as the host, as the schema
|
|
134
|
+
* defines `workspace:` ("workspace"). The team model resolves as teamModel resolves it (the default is
|
|
135
|
+
* the local one the workspace allows, else the workspace's; a committed team wins a collision) over the shared teams of, in order, the workspace
|
|
136
|
+
* file this run observed (`teamsFrom: "observed"`), the cached file ("cache": no git process), or none
|
|
137
|
+
* ("local"). `standalone` is the CONFIGURED standalone view only (oats-local.yaml `standalone:`): it
|
|
138
|
+
* reads no workspace file, so its local teams are the whole team model. A run that fell back to the
|
|
139
|
+
* standalone view (the host unreadable) is not: its team model is the workspace's, and its
|
|
140
|
+
* discovery is the member's, never the host's key. */
|
|
141
|
+
function workspaceIdentity(local, discovery, remoteOptions) {
|
|
142
|
+
const ref = local.workspace;
|
|
143
|
+
const standalone = typeof local.standalone === "string" && local.standalone !== "";
|
|
144
|
+
const observed = discovery && discovery.standalone !== true && discovery.workspace ? discovery : null;
|
|
145
|
+
const cached = observed ? null : cachedWorkspace(ref, remoteOptions);
|
|
146
|
+
const keyOf = (r) => { try { return parseRepoRef(r).key; } catch { return null; } };
|
|
147
|
+
let key, keyFrom;
|
|
148
|
+
if (observed) [key, keyFrom] = [observed.key, "workspace"];
|
|
149
|
+
else if (cached && cached.host === null) [key, keyFrom] = [keyOf(ref), "member"];
|
|
150
|
+
else [key, keyFrom] = [keyOf(cached?.host ?? ref), "workspace"];
|
|
151
|
+
if (key === null) keyFrom = null; // a reference parseRepoRef refuses: unusable, never matched
|
|
152
|
+
let shared = null, teamsFrom = "local";
|
|
153
|
+
if (!standalone) {
|
|
154
|
+
if (observed) [shared, teamsFrom] = [observed.workspace, "observed"];
|
|
155
|
+
else if (cached?.file) [shared, teamsFrom] = [cached.file, "cache"];
|
|
156
|
+
}
|
|
157
|
+
const model = teamModel(shared, local);
|
|
158
|
+
// A soul with no souls: default of its own lives here (team model 3: the local default the workspace allows, else the workspace's).
|
|
159
|
+
const deploymentDefault = model.localDefault ?? model.workspaceDefault;
|
|
160
|
+
const labels = [...model.labels.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
161
|
+
return {
|
|
162
|
+
key, ref, keyFrom, standalone,
|
|
163
|
+
defaultTeam: deploymentDefault === null ? null : { label: deploymentDefault, team: model.labels.get(deploymentDefault)?.team ?? null },
|
|
164
|
+
teams: Object.fromEntries(labels.map((l) => [l, model.labels.get(l).team])),
|
|
165
|
+
teamsFrom,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** What this machine's parsed cache knows of the workspace `ref` names (the values observeWorkspace and
|
|
169
|
+
* confirmMembership stored, each at its repo's last observed commit): { host, file } — `host` the ref
|
|
170
|
+
* of the workspace host, `file` its workspace file or null — when `ref` is the host (its workspace file
|
|
171
|
+
* is cached) or a member whose cached oats-membership.yaml names it (discoverOrStandalone follows the
|
|
172
|
+
* same backlink). A member's backlink is cached whether its own workspace slot was observed (missing)
|
|
173
|
+
* or never was (the host's discovery confirmed it). { host: null, file: null } for a ref cached as
|
|
174
|
+
* having no workspace file and no backlink; null when nothing is known. */
|
|
175
|
+
export function cachedWorkspace(ref, remoteOptions) {
|
|
176
|
+
const options = remoteOptions();
|
|
177
|
+
const cached = (r, item) => {
|
|
178
|
+
const commit = lastObservedCommit(r, options);
|
|
179
|
+
const value = commit ? peekAtCommit(r, commit, item, options) : undefined;
|
|
180
|
+
return value && typeof value === "object" ? value : null;
|
|
181
|
+
};
|
|
182
|
+
const fileOf = (read) => (read && !read.missing && !read.problems && read.value && typeof read.value === "object" ? read.value : null);
|
|
183
|
+
const read = cached(ref, "workspace");
|
|
184
|
+
if (read && !read.missing) return { host: ref, file: fileOf(read) };
|
|
185
|
+
const membership = cached(ref, "membership");
|
|
186
|
+
const host = membership?.kind === "ok" && typeof membership.value?.workspace === "string" ? membership.value.workspace : null;
|
|
187
|
+
if (host !== null) return { host, file: fileOf(cached(host, "workspace")) };
|
|
188
|
+
return read ? { host: null, file: null } : null;
|
|
189
|
+
}
|
|
190
|
+
/** A roster agent's soul key: the qualified name of a package soul, else the recorded agent (soul) name;
|
|
191
|
+
* null when no instance records a workspace soul. Exactly soulKeyOf for the soul it was spawned from. */
|
|
192
|
+
function agentSoulKey(a) {
|
|
193
|
+
for (const i of a.instances || []) {
|
|
194
|
+
const soul = i?.workspace?.soul;
|
|
195
|
+
if (!soul || typeof soul !== "object") continue;
|
|
196
|
+
return soul.package && typeof soul.qualifiedName === "string" ? soul.qualifiedName : (typeof i.agent === "string" ? i.agent : a.name);
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
package/lib/session-input.mjs
CHANGED
|
@@ -56,6 +56,9 @@ export function inspectSessionTarget(target, io, { includeSize = false, includeP
|
|
|
56
56
|
const state = createSessionPaneInspector(io)(rows, { includeSize, name: target.window });
|
|
57
57
|
return includePanes ? { ...state, panes: rows.length } : state;
|
|
58
58
|
}
|
|
59
|
+
/** The shell/descendant rule's answer when the process table cannot establish it (#1641): unknown,
|
|
60
|
+
* never a fallback shell, with the reason status carries as `runtimeError`. */
|
|
61
|
+
const unestablished = (why) => new Error(`${why}, so whether the harness runs cannot be told`);
|
|
59
62
|
/** Interpret one window's panes: resolve the agent's pane (resolveAgentPane, `name` the window's
|
|
60
63
|
* instance name), then judge that pane alone with the lifecycle's shell/descendant rule; the other
|
|
61
64
|
* panes never make it unknown. Each row is `id, dead, command, pid[, cols, rows], mark` (the mark may
|
|
@@ -63,17 +66,27 @@ export function inspectSessionTarget(target, io, { includeSize = false, includeP
|
|
|
63
66
|
* process scans cost one child. */
|
|
64
67
|
export function createSessionPaneInspector(io) {
|
|
65
68
|
let processRead;
|
|
69
|
+
// Rows are `{ pid, ppid, name }`, `name` "" when ps printed none. A line that is not a process row
|
|
70
|
+
// is never dropped silently: `malformed` keeps the snapshot from proving a fallback shell.
|
|
66
71
|
const readProcesses = () => {
|
|
67
72
|
if (!processRead) {
|
|
68
73
|
try {
|
|
69
74
|
const output = (io?.exec || execFileSync)("ps", ["-axo", "pid=,ppid=,comm="], {
|
|
70
75
|
encoding: "utf8", timeout: 10000, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"],
|
|
71
76
|
});
|
|
72
|
-
|
|
77
|
+
const rows = [];
|
|
78
|
+
let malformed = false;
|
|
79
|
+
for (const line of output.split("\n")) {
|
|
80
|
+
if (!line.trim()) continue;
|
|
81
|
+
const row = line.trim().match(/^(\d+)\s+(\d+)(?:\s+(.*))?$/);
|
|
82
|
+
if (row) rows.push({ pid: row[1], ppid: row[2], name: row[3] ?? "" });
|
|
83
|
+
else malformed = true;
|
|
84
|
+
}
|
|
85
|
+
processRead = { rows, malformed };
|
|
73
86
|
} catch (error) { processRead = { error }; }
|
|
74
87
|
}
|
|
75
88
|
if (processRead.error) throw processRead.error;
|
|
76
|
-
return processRead
|
|
89
|
+
return processRead;
|
|
77
90
|
};
|
|
78
91
|
return (rows, { includeSize = false, name } = {}) => {
|
|
79
92
|
if (!rows.length) return { backend: "tmux", present: false, state: "stopped" };
|
|
@@ -95,26 +108,37 @@ export function createSessionPaneInspector(io) {
|
|
|
95
108
|
// A missing tmux label can still be a fallback shell. Only the pane's
|
|
96
109
|
// own comm can establish that; an optional failed read stays unknown.
|
|
97
110
|
try {
|
|
98
|
-
const own = readProcesses().find((
|
|
99
|
-
shell = own ? isShellProcess(own
|
|
111
|
+
const own = readProcesses().rows.find((p) => p.pid === panePid);
|
|
112
|
+
shell = own ? isShellProcess(own.name) : false;
|
|
100
113
|
} catch { /* missing process information is not proof of a fallback shell */ }
|
|
101
114
|
}
|
|
102
115
|
if (dead === "0" && shell) {
|
|
103
|
-
//
|
|
104
|
-
//
|
|
116
|
+
// tmux names the pane's foreground process group's leader: the launch's own shell
|
|
117
|
+
// (default-shell -c) while the harness runs as its child, on macOS and Linux alike.
|
|
118
|
+
// Only the pane's own process, in the snapshot as a shell, with no non-shell
|
|
119
|
+
// descendant, is a fallback prompt. A live non-shell process is the harness running;
|
|
120
|
+
// anything else is unknown, never the prompt (#1641).
|
|
105
121
|
if (!/^\d+$/.test(panePid)) throw new Error("tmux returned no pane process id");
|
|
106
|
-
const processes = readProcesses();
|
|
122
|
+
const { rows: processes, malformed } = readProcesses();
|
|
123
|
+
const own = processes.find((p) => p.pid === panePid);
|
|
124
|
+
// A ps that cannot see the pane (another PID namespace, a sandbox) or a pane respawned since
|
|
125
|
+
// tmux answered.
|
|
126
|
+
if (!own) throw unestablished(`the process table has no process ${panePid}, the agent's pane's own`);
|
|
107
127
|
const descendants = new Set([panePid]);
|
|
108
|
-
let active =
|
|
128
|
+
let active = !isShellProcess(own.name) && own.name !== "", unnamed = own.name === "" ? own.pid : null;
|
|
109
129
|
for (let changed = true; changed;) {
|
|
110
130
|
changed = false;
|
|
111
|
-
for (const
|
|
112
|
-
if (descendants.has(
|
|
131
|
+
for (const { pid, ppid, name } of processes) {
|
|
132
|
+
if (descendants.has(ppid) && !descendants.has(pid)) {
|
|
113
133
|
descendants.add(pid); changed = true;
|
|
114
|
-
if (
|
|
134
|
+
if (name === "") unnamed ??= pid;
|
|
135
|
+
else if (!isShellProcess(name)) active = true;
|
|
115
136
|
}
|
|
116
137
|
}
|
|
117
138
|
}
|
|
139
|
+
if (!active && unnamed !== null) throw unestablished(`process ${unnamed} in the agent's pane has no command name in the process table`);
|
|
140
|
+
// A line that is not a process row may be one of the pane's processes.
|
|
141
|
+
if (!active && malformed) throw unestablished("the process table has a line that is not a process");
|
|
118
142
|
state = active ? "unknown" : "shell";
|
|
119
143
|
}
|
|
120
144
|
return { backend: "tmux", present: dead === "0", state, paneId,
|