@awebai/oats 0.69.12 → 0.69.14
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/README.md +216 -178
- package/bin/oats.mjs +176 -184
- package/docs/capabilities.md +4 -1
- package/docs/configuration.md +63 -5
- package/docs/container.md +246 -0
- package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
- package/docs/desktop-cli-api.md +376 -37
- package/docs/desktop-instance-start.md +4 -1
- package/docs/desktop.md +58 -12
- package/docs/execution-targets.md +69 -6
- package/docs/implementation.md +86 -29
- package/docs/integrations.md +3 -2
- package/docs/knowledge-and-learning.md +72 -0
- package/docs/oats-local.schema.json +11 -2
- package/docs/official-catalog.md +39 -5
- package/docs/packages.md +93 -14
- package/docs/release-lane.md +2 -1
- package/docs/release-notes/v0.69.13.md +767 -0
- package/docs/release-notes/v0.69.14.md +83 -0
- package/docs/schedules.md +26 -3
- package/docs/servers.md +181 -5
- package/docs/souls-and-instances.md +140 -11
- package/docs/tui.md +1 -1
- package/docs/upgrading.md +24 -5
- package/docs/workspaces.md +31 -5
- package/lib/claim.mjs +21 -5
- package/lib/command-flags.mjs +238 -0
- package/lib/core.mjs +791 -563
- package/lib/deployments.mjs +4 -3
- package/lib/dir-lock.mjs +126 -31
- package/lib/errors.mjs +1 -1
- package/lib/harness-token.mjs +110 -0
- package/lib/hot-reads.mjs +4 -3
- package/lib/instance-events.mjs +28 -6
- package/lib/instance-git.mjs +138 -13
- package/lib/instance-inspect.mjs +6 -1
- package/lib/instance-listing.mjs +80 -38
- package/lib/instance-resolution.mjs +56 -3
- package/lib/instance-upgrade.mjs +16 -20
- package/lib/launch-env-exec.sh +7 -0
- package/lib/launch-env.mjs +74 -0
- package/lib/launch-preference.mjs +19 -12
- package/lib/member-clone.mjs +7 -1
- package/lib/packages.mjs +74 -2
- package/lib/read-call.mjs +3 -0
- package/lib/reader.mjs +3 -2
- package/lib/refused-text.mjs +3 -2
- package/lib/remote.mjs +119 -27
- package/lib/retained-after-retire.mjs +2 -7
- package/lib/retire-git-forms.mjs +41 -0
- package/lib/retire-incomplete.mjs +96 -0
- package/lib/schedule.mjs +2 -1
- package/lib/servers.mjs +78 -23
- package/lib/session-resume.mjs +68 -53
- package/lib/session-seen.mjs +54 -5
- package/lib/start-env.mjs +13 -7
- package/lib/system-tools.mjs +1 -1
- package/lib/teams.mjs +11 -4
- package/lib/upgrade-state.mjs +13 -2
- package/lib/worktree.mjs +56 -7
- package/package-catalog.json +1 -1
- package/package.json +2 -1
- package/packages/client/instance-lifecycle.mjs +1 -1
- package/packages/client/lifecycle-contract.mjs +3 -1
- package/packages/client/session-resume-cli.mjs +2 -1
- package/packages/client/session-start.mjs +10 -7
- package/packages/client/workspace-cli.mjs +5 -1
- package/share/oats-login-receive +204 -0
- package/skills/oats-getting-started/SKILL.md +92 -25
- package/lib/tmux-config.mjs +0 -35
package/lib/deployments.mjs
CHANGED
|
@@ -16,8 +16,9 @@
|
|
|
16
16
|
* inside it), under the same lock, and records `imports["agents-dir"]` even when there is nothing
|
|
17
17
|
* to import. A command whose import could not run fails: it never answers a list that skipped it.
|
|
18
18
|
*
|
|
19
|
-
* Concurrency: every read-modify-write holds `config/deployments.lock` (withDirLock
|
|
20
|
-
*
|
|
19
|
+
* Concurrency: every read-modify-write holds `config/deployments.lock` (withDirLock: a file that
|
|
20
|
+
* names its holder, taken over when that process is gone), waits up to 3 s for a holder that runs
|
|
21
|
+
* and re-reads inside it; each write replaces the file atomically. Readers take no lock:
|
|
21
22
|
* they read a regular file only, without following a link, up to 1 MiB. A row's `state` is an
|
|
22
23
|
* existence check: no deployment's content is read here.
|
|
23
24
|
*/
|
|
@@ -144,7 +145,7 @@ function updateDeployments(change, { wait = LOCK_WAIT_MS } = {}) {
|
|
|
144
145
|
}, { retryMs: wait, busy: (why) => deploymentsError("E_DEPLOYMENTS_BUSY", `this computer's deployments list is locked (${why}); if no oats process is changing it, remove ${lock} and retry; nothing was changed`, { file, lock }) });
|
|
145
146
|
} catch (e) {
|
|
146
147
|
if (typeof e?.code === "string" && e.code.startsWith("E_")) throw e;
|
|
147
|
-
// The lock
|
|
148
|
+
// The lock itself could not be made or written: the list was not touched.
|
|
148
149
|
if (typeof e?.code === "string") throw writeFailed(file, e);
|
|
149
150
|
throw e;
|
|
150
151
|
}
|
package/lib/dir-lock.mjs
CHANGED
|
@@ -1,39 +1,134 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* processes share (the host schedule state, the server registry
|
|
2
|
+
* The lock for short read-modify-write sections over files several oats
|
|
3
|
+
* processes share (the host schedule state, the server registry, this
|
|
4
|
+
* computer's deployments list, a deployment's oats-local.yaml).
|
|
5
|
+
*
|
|
6
|
+
* It is a claim (lib/claim.mjs): one file at the lock's path that names its
|
|
7
|
+
* holder by pid and process start. One process holds it at a time. A lock
|
|
8
|
+
* whose holder is verifiably gone (killed, exited, its pid reused by another
|
|
9
|
+
* process) is taken over by the next acquirer; one whose holder lives, or
|
|
10
|
+
* cannot be judged, never is.
|
|
11
|
+
*
|
|
12
|
+
* A SIGINT or SIGTERM that arrives while a section runs waits for it: the
|
|
13
|
+
* section completes, the lock is released, and then the signal is raised
|
|
14
|
+
* again, so it ends the process as it would have (holdSignals).
|
|
15
|
+
*
|
|
16
|
+
* A holder that keeps the lock across asynchronous work (the machine's resume
|
|
17
|
+
* sweep, lib/session-resume.mjs) takes it with acquireDirLock and releases it
|
|
18
|
+
* itself. No signal is held back for it: a holder a signal ends leaves its
|
|
19
|
+
* lock, and the next acquirer takes it over.
|
|
4
20
|
*/
|
|
5
21
|
|
|
6
|
-
import {
|
|
7
|
-
import { dirname
|
|
22
|
+
import { lstatSync, mkdirSync } from "node:fs";
|
|
23
|
+
import { dirname } from "node:path";
|
|
24
|
+
import { acquireClaim, claimUnheld, releaseClaim, shownHolder } from "./claim.mjs";
|
|
8
25
|
|
|
9
|
-
|
|
10
|
-
const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
26
|
+
const isDirectory = (path) => { try { return lstatSync(path).isDirectory(); } catch { return false; } };
|
|
11
27
|
|
|
12
|
-
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
28
|
+
/** The claim's refusals (lib/claim.mjs) for the lock `path`, each made with the caller's
|
|
29
|
+
* `busy(why, { found })`: `why` is a clause that says what was found, for the caller's own
|
|
30
|
+
* sentence, which names `path` as what to remove; `found` is one word for it:
|
|
31
|
+
* running a holder that lives
|
|
32
|
+
* unknown a holder whose liveness cannot be established
|
|
33
|
+
* own-start-unreadable this process's own start cannot be read, so it could not hold the lock
|
|
34
|
+
* directory a directory at `path`, the lock of an earlier kernel
|
|
35
|
+
* unreadable a record that does not parse
|
|
36
|
+
* cannot-take-over a gone holder's record that cannot be taken over
|
|
37
|
+
* held-again a lock found without a live holder and taken again, every time
|
|
38
|
+
* `at` is the file a refusal is about: `path`, or the claim of a takeover of it
|
|
39
|
+
* (`<path>.reclaim-<nonce>`), which is then named in full. A holder is named as shownHolder
|
|
40
|
+
* allows: text of a record is never part of `why`. */
|
|
41
|
+
function refusals(path, busy) {
|
|
42
|
+
const pid = (holder) => shownHolder(holder).pid ?? "?";
|
|
43
|
+
const held = (at) => (at === path ? "it" : `${at}, the claim of a takeover of it`);
|
|
44
|
+
return {
|
|
45
|
+
busy: (holder, unknown, at) => (unknown
|
|
46
|
+
? busy(`whether pid ${pid(holder)}, which holds ${held(at)}, still runs cannot be established: ${unknown}`, { found: "unknown" })
|
|
47
|
+
: busy(`pid ${pid(holder)} holds ${held(at)}`, { found: "running" })),
|
|
48
|
+
ownStartUnreadable: (reason) => busy(`this process's own start time cannot be read (${reason}), so it cannot hold the lock verifiably`, { found: "own-start-unreadable" }),
|
|
49
|
+
// A directory is the lock of a kernel that locked with one. It is never removed here and its
|
|
50
|
+
// owner is never judged: while that kernel runs it holds the directory, which excludes this
|
|
51
|
+
// one; once it is gone the operator removes the directory, as the caller's sentence says.
|
|
52
|
+
unreadableClaim: (at) => (isDirectory(at)
|
|
53
|
+
? busy(`${at} is a lock directory written by an earlier kernel`, { found: "directory" })
|
|
54
|
+
: busy(`the record at ${at} is unreadable`, { found: "unreadable" })),
|
|
55
|
+
cannotTakeOver: (holder, at, why) => busy(`the holder of ${at}, pid ${pid(holder)}, is gone, and that file cannot be taken over (${why}); it must be removed`, { found: "cannot-take-over" }),
|
|
56
|
+
heldAgain: (holder, at, times) => busy(`${at} was found without a live holder ${times} times and was taken again each time, the last time by a process that is gone; retry`, { found: "held-again" }),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** What stops the lock `path` from being taken, read and not taken → `{ why, found }` as an
|
|
61
|
+
* acquirer's `busy` is handed them (refusals), or null when nobody holds it: no lock is there, or
|
|
62
|
+
* its holder is gone and the next acquirer takes it over. A lock that cannot be read for a reason
|
|
63
|
+
* of the system's is `unreadable`. Nothing is written, removed or waited for. `holderGone` as
|
|
64
|
+
* acquireDirLock takes it. */
|
|
65
|
+
export function dirLockHeld(path, { holderGone } = {}) {
|
|
66
|
+
const found = refusals(path, (why, { found }) => ({ why, found }));
|
|
67
|
+
try { claimUnheld(path, { holderGone, ...found }, found.unreadableClaim(path)); }
|
|
68
|
+
catch (held) {
|
|
69
|
+
if (typeof held?.found === "string") return held;
|
|
70
|
+
throw held;
|
|
32
71
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The signals a section is not cut short by. */
|
|
76
|
+
const HELD_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
77
|
+
let sections = 0, listening = false, idle = null;
|
|
78
|
+
function stopListening() {
|
|
79
|
+
if (idle) { clearImmediate(idle); idle = null; }
|
|
80
|
+
if (!listening) return;
|
|
81
|
+
listening = false;
|
|
82
|
+
for (const signal of HELD_SIGNALS) process.off(signal, onHeldSignal);
|
|
83
|
+
}
|
|
84
|
+
/** A section is synchronous, so a signal that arrived during one reaches this listener after it,
|
|
85
|
+
* the lock released. The signal is raised again without this listener: it ends the process by its
|
|
86
|
+
* default action when nothing else listens for it, and reaches the listeners that do otherwise. */
|
|
87
|
+
function onHeldSignal(signal) {
|
|
88
|
+
stopListening();
|
|
89
|
+
process.kill(process.pid, signal);
|
|
90
|
+
}
|
|
91
|
+
/** Listen for HELD_SIGNALS while a section runs: a listener keeps a signal's default action from
|
|
92
|
+
* ending the process inside it. → the function to call when the section is over. The listeners
|
|
93
|
+
* stay until the event loop has turned once with no section running, which is when a signal that
|
|
94
|
+
* arrived during the section is delivered; taking them off at the section's end would drop it. */
|
|
95
|
+
function holdSignals() {
|
|
96
|
+
sections += 1;
|
|
97
|
+
if (idle) { clearImmediate(idle); idle = null; }
|
|
98
|
+
if (!listening) { listening = true; for (const signal of HELD_SIGNALS) process.on(signal, onHeldSignal); }
|
|
99
|
+
return () => { if (--sections === 0) idle = setImmediate(stopListening); };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Take the lock `path` → the function that releases it, only while the lock still names this
|
|
103
|
+
* holding. `facts` is what the lock's record says besides its holder.
|
|
104
|
+
*
|
|
105
|
+
* A holder that lives is waited for up to `retryMs`, then refused with `busy(why, { found })`,
|
|
106
|
+
* the caller's own error (`found`: refusals). Refused the same way, without waiting, and left as it is:
|
|
107
|
+
* a holder whose liveness cannot be read, a record that does not parse, a directory at `path`
|
|
108
|
+
* (the lock of an earlier kernel) and a gone holder's record that cannot be taken over. A lock
|
|
109
|
+
* whose holder is gone is taken over, so a process killed while it holds the lock stops nobody;
|
|
110
|
+
* `holderGone(holder)` is the caller's own reading of a record that says so (lib/claim.mjs).
|
|
111
|
+
*
|
|
112
|
+
* A failure of the system's to make the lock (its directory, its file) is thrown as the system's
|
|
113
|
+
* own error, for the caller to answer in its own words. */
|
|
114
|
+
export function acquireDirLock(path, facts, { retryMs = 0, busy, holderGone } = {}) {
|
|
115
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
116
|
+
let me;
|
|
117
|
+
try { me = acquireClaim(path, { waitMs: retryMs, facts, holderGone, ...refusals(path, busy) }); }
|
|
118
|
+
catch (e) {
|
|
119
|
+
// acquireClaim answers an error that is not the kernel's as E_LIFECYCLE_FAILED, holding it as `cause`.
|
|
120
|
+
throw e?.code === "E_LIFECYCLE_FAILED" && Object.hasOwn(e, "cause") ? e.cause : e;
|
|
121
|
+
}
|
|
122
|
+
return () => releaseClaim(path, me);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Run `fn` holding the lock `path` (acquireDirLock: how it is taken, and its refusals) → what
|
|
126
|
+
* `fn` returns; an error `fn` throws propagates once the lock is released. `what` says in the
|
|
127
|
+
* lock's record what the holder is doing. A SIGINT or SIGTERM during `fn` ends the process only
|
|
128
|
+
* once `fn` has returned and the lock is released (holdSignals). */
|
|
129
|
+
export function withDirLock(path, what, fn, { retryMs = 0, busy } = {}) {
|
|
130
|
+
const release = acquireDirLock(path, { what }, { retryMs, busy });
|
|
131
|
+
const sectionOver = holdSignals();
|
|
37
132
|
try { return fn(); }
|
|
38
|
-
finally {
|
|
133
|
+
finally { release(); sectionOver(); }
|
|
39
134
|
}
|
package/lib/errors.mjs
CHANGED
|
@@ -192,7 +192,7 @@ export const ifItDoesNotEnd = (what, at) => `if it does not end, ${checkHolderBy
|
|
|
192
192
|
* after the verb's first effect is never answered (afterFirstEffect). The docs table of
|
|
193
193
|
* docs/desktop-cli-api.md is checked against this constant, and a client's own set must lie
|
|
194
194
|
* inside it (test/lifecycle-before-effect-codes.test.mjs). */
|
|
195
|
-
const BEFORE_EFFECT = Object.freeze(["E_BAD_ARGS", "E_PLAN_STALE", "E_INSTANCE_RETIRING", "E_LIFECYCLE_BUSY", "E_HOME_MISMATCH", "E_SESSION_UNKNOWN",
|
|
195
|
+
const BEFORE_EFFECT = Object.freeze(["E_BAD_ARGS", "E_USAGE", "E_PLAN_STALE", "E_INSTANCE_RETIRING", "E_LIFECYCLE_BUSY", "E_HOME_MISMATCH", "E_SESSION_UNKNOWN",
|
|
196
196
|
"E_AMBIGUOUS_INSTANCE", "E_UNIDENTIFIED_INSTANCE_HOME", "E_REMOTE_INCOMPATIBLE", "E_AMBIGUOUS", "E_SNAPSHOT_UNKNOWN"]);
|
|
197
197
|
export const BEFORE_EFFECT_CODES = Object.freeze({ "instance stop": BEFORE_EFFECT, retire: BEFORE_EFFECT });
|
|
198
198
|
/** The defect afterFirstEffect makes. Its name is on the prototype, so that it is in the stack's
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** Operator-only client for the pinned oats-login-receive forced-command protocol.
|
|
2
|
+
* Its response is metadata, never a remote OATS envelope or shell output to forward. */
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import { readStreamBounded } from "./attachments.mjs";
|
|
6
|
+
import { getServer, operatorSshArgv, readServerOperatorRoutes, runRemote, serverError, targetOf } from "./servers.mjs";
|
|
7
|
+
import { shellWord } from "./shell-word.mjs";
|
|
8
|
+
|
|
9
|
+
const HARNESSES = new Set(["claude", "codex", "pi", "opencode"]);
|
|
10
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
11
|
+
const FINGERPRINT = /^sha256:[a-f0-9]{16}$/;
|
|
12
|
+
const delivery = (message) => serverError("E_HARNESS_TOKEN_DELIVERY", message);
|
|
13
|
+
const unexpected = () => delivery("Unexpected reply from the server's credential receiver.");
|
|
14
|
+
function replacedAt(value) {
|
|
15
|
+
return typeof value === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(value)
|
|
16
|
+
&& Number.isFinite(Date.parse(value)) && new Date(value).toISOString().replace(".000Z", "Z") === value;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function receiverReply(call, action, harness, name, secret = "") {
|
|
20
|
+
// Hitting maxBuffer also signals the child; it is a bad reply, not a failed hop.
|
|
21
|
+
if (call.code === "ENOBUFS") throw unexpected();
|
|
22
|
+
if (call.status === 255 || ["ENOENT", "ETIMEDOUT"].includes(call.code) || call.signal) throw delivery("Couldn't reach the server. Check the operator SSH alias and connection.");
|
|
23
|
+
let reply;
|
|
24
|
+
try {
|
|
25
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(call.stdout ?? "")).trim();
|
|
26
|
+
if (/[\r\n]/.test(text)) throw unexpected();
|
|
27
|
+
reply = JSON.parse(text);
|
|
28
|
+
} catch { throw unexpected(); }
|
|
29
|
+
if (!reply || reply.harness !== harness || reply.name !== name || typeof reply.ok !== "boolean") throw unexpected();
|
|
30
|
+
if (!reply.ok) {
|
|
31
|
+
if (call.status !== 1 || typeof reply.error !== "string" || !reply.error || reply.error.length > 2048) throw unexpected();
|
|
32
|
+
const reason = secret ? reply.error.replaceAll(secret, "<redacted>") : reply.error;
|
|
33
|
+
throw delivery(`The server refused the credential: ${reason.replace(/[\x00-\x1f\x7f]/g, " ")}`);
|
|
34
|
+
}
|
|
35
|
+
if (call.status !== 0 || !replacedAt(reply.replacedAt) || (action === "remove" ? reply.fingerprint !== null : typeof reply.fingerprint !== "string" || !FINGERPRINT.test(reply.fingerprint))) throw unexpected();
|
|
36
|
+
return { fingerprint: reply.fingerprint, replacedAt: reply.replacedAt };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function credentialBytes(input, harness) {
|
|
40
|
+
const bad = (message) => serverError("E_HARNESS_TOKEN_INPUT", message);
|
|
41
|
+
if (input === undefined) throw serverError("E_HARNESS_TOKEN_UNSUPPORTED", harness === "claude"
|
|
42
|
+
? "Interactive Claude token setup is not available. Pipe an existing inference-only setup-token with --stdin."
|
|
43
|
+
: harness === "opencode" ? "Interactive opencode sign-in is not supported. Pipe a provider API key with --stdin."
|
|
44
|
+
: "Browser sign-in needs refreshing credentials and an agent-writable auth file, which the read-only operator route cannot support. Pipe a non-refreshing provider API key with --stdin.");
|
|
45
|
+
if (input?.isTTY) throw bad("Pipe the credential with --stdin; terminal input would show it.");
|
|
46
|
+
if (!Buffer.isBuffer(input) && (!input || typeof input[Symbol.asyncIterator] !== "function")) throw bad("Supply credential bytes or a readable stdin stream.");
|
|
47
|
+
let raw;
|
|
48
|
+
try { raw = Buffer.isBuffer(input) ? input : await readStreamBounded(input, 65536); }
|
|
49
|
+
catch (e) { throw bad(e?.code === "E_UPLOAD_TOO_LARGE" ? "The credential input is larger than 64 KiB." : "Couldn't read the credential from stdin."); }
|
|
50
|
+
if (raw.length > 65536) throw bad("The credential input is larger than 64 KiB.");
|
|
51
|
+
let value;
|
|
52
|
+
try { value = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(raw).replace(/^[\x09-\x0d\x20]+|[\x09-\x0d\x20]+$/g, ""); }
|
|
53
|
+
catch { throw bad("The credential must be UTF-8 text."); }
|
|
54
|
+
if (!value || /[\0\r\n]/.test(value)) throw bad("Give one non-empty credential line with no NUL bytes.");
|
|
55
|
+
const bytes = Buffer.from(value);
|
|
56
|
+
if (bytes.length > 65535) throw bad("The credential must leave room for its final newline within 64 KiB.");
|
|
57
|
+
if (harness === "claude" && (!value.startsWith("sk-ant-oat") || bytes.length > 512)) throw bad("This is not a Claude setup-token. Pipe an inference-only token beginning with sk-ant-oat.");
|
|
58
|
+
return bytes;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function olderSessions(registration, server, harness, at, secret, io) {
|
|
62
|
+
const { envelope } = runRemote(targetOf(registration), ["status", "--json", "--dir", registration.workspace], { execFileSync: io.execFileSync, serverId: server, timeoutMs: 60000 });
|
|
63
|
+
if (!envelope.ok || !Array.isArray(envelope.result?.agents)) throw unexpected();
|
|
64
|
+
// The receiver truncates to whole seconds; starts during that second may still
|
|
65
|
+
// have read the previous file. Include them rather than silently miss a session.
|
|
66
|
+
const before = Date.parse(at) + 1000;
|
|
67
|
+
const out = [];
|
|
68
|
+
for (const agent of envelope.result.agents) for (const row of agent.instances ?? []) {
|
|
69
|
+
if ((row.harness ?? row.runtime ?? agent.harness ?? agent.runtime) !== harness || row.startedAt === null) continue;
|
|
70
|
+
if (typeof row.startedAt !== "string" || !Number.isFinite(Date.parse(row.startedAt))) throw unexpected();
|
|
71
|
+
if (Date.parse(row.startedAt) >= before) continue;
|
|
72
|
+
const item = { instance: row.instance, agent: agent.name, home: row.home, startedAt: row.startedAt };
|
|
73
|
+
if (Object.values(item).some((v) => typeof v !== "string" || !v || v.includes(secret))) throw unexpected();
|
|
74
|
+
out.push(item);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The operator transport is chosen and validated before any input is consumed or SSH runs. */
|
|
80
|
+
export async function harnessToken({ action, harness, server, name, input }, io = {}) {
|
|
81
|
+
if (!["set", "status", "remove"].includes(action) || !HARNESSES.has(harness) || typeof server !== "string" || !server || (action !== "set" && input !== undefined)) throw serverError("E_BAD_ARGS", "Give set, status or remove, a harness, and --server <id>. Only set reads stdin.");
|
|
82
|
+
const registration = getServer(server), routes = readServerOperatorRoutes();
|
|
83
|
+
const route = Object.hasOwn(routes, server) ? routes[server] : undefined;
|
|
84
|
+
if (!route) {
|
|
85
|
+
const command = ["oats", "server", "add", server, "--ssh", registration.sshHost, "--workspace", registration.workspace];
|
|
86
|
+
for (const [key, flag] of [["label", "--label"], ["oatsPath", "--oats"], ["path", "--path"]]) {
|
|
87
|
+
if (registration[key] !== undefined) command.push(flag, registration[key]);
|
|
88
|
+
}
|
|
89
|
+
throw serverError("E_HARNESS_TOKEN_ROUTE", `Server ${server} has no operator SSH route. Register one with ${command.map(shellWord).join(" ")} --operator-ssh <alias> --replace. Credentials never use the agent route.`);
|
|
90
|
+
}
|
|
91
|
+
const selectedName = name ?? registration.label;
|
|
92
|
+
if (typeof selectedName !== "string" || !NAME.test(selectedName)) throw serverError("E_BAD_ARGS", "Give --name <team>: lowercase letters, digits and dashes, starting with a letter or digit, at most 63 characters. A server label is used only when it follows these rules.");
|
|
93
|
+
const credential = action === "set" ? await credentialBytes(input, harness) : undefined;
|
|
94
|
+
const [bin, ...args] = operatorSshArgv(route.operatorSshHost, [action === "set" ? "install" : action, harness, selectedName]);
|
|
95
|
+
let call;
|
|
96
|
+
try {
|
|
97
|
+
call = { status: 0, stdout: (io.execFileSync ?? execFileSync)(bin, args, { stdio: [credential ? "pipe" : "ignore", "pipe", "pipe"], ...(credential ? { input: credential } : {}), maxBuffer: 65536, timeout: 60000 }) };
|
|
98
|
+
} catch (error) { call = { status: error.status, stdout: error.stdout, code: error.code, signal: error.signal }; }
|
|
99
|
+
// Even debug output must not forward a receiver that unexpectedly echoes input, including a
|
|
100
|
+
// truncated prefix that cannot be safely redacted. Transport facts are enough to diagnose the hop.
|
|
101
|
+
io.debug?.(`operator SSH: exit ${Number.isInteger(call.status) ? call.status : "unknown"}${["ENOENT", "ETIMEDOUT", "ENOBUFS", "EACCES"].includes(call.code) ? ", " + call.code : ""}`);
|
|
102
|
+
const secret = credential?.toString("utf8") ?? "";
|
|
103
|
+
const result = { server, action, harness, name: selectedName, ...receiverReply(call, action, harness, selectedName, secret), warnings: [] };
|
|
104
|
+
if (credential) {
|
|
105
|
+
if (result.fingerprint !== "sha256:" + createHash("sha256").update(credential).digest("hex").slice(0, 16)) throw unexpected();
|
|
106
|
+
try { result.staleInstances = olderSessions(registration, server, harness, result.replacedAt, secret, io); }
|
|
107
|
+
catch { result.staleInstances = null; result.warnings.push("The credential was installed, but older sessions could not be listed. Existing sessions pick it up at their next start; nothing was restarted."); }
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
package/lib/hot-reads.mjs
CHANGED
|
@@ -14,9 +14,9 @@
|
|
|
14
14
|
* test/cli-hot-reads.test.mjs runs each read and pins the modules it must not load. Kernel-private,
|
|
15
15
|
* not exported from `./core`. Dependency-free. */
|
|
16
16
|
|
|
17
|
-
/** The dispatch's own modules: argv's `--flag=value` expansion, the
|
|
18
|
-
* the resume feature, the inherited captured context's refusal. */
|
|
19
|
-
const DISPATCH = { argv: ["argv"], deprecation: ["deprecation"], errors: ["errors"], "session-resume-contract": ["session-resume-contract"], "captured-context": ["captured-context"] };
|
|
17
|
+
/** The dispatch's own modules: argv's `--flag=value` expansion, the flags each state-changing command defines,
|
|
18
|
+
* the deprecated-name warning, the typed failures, the resume feature, the inherited captured context's refusal. */
|
|
19
|
+
const DISPATCH = { argv: ["argv"], "command-flags": ["command-flags"], deprecation: ["deprecation"], errors: ["errors"], "session-resume-contract": ["session-resume-contract"], "captured-context": ["captured-context"] };
|
|
20
20
|
/** A read that lists its deployment (LISTS_ITS_DEPLOYMENT in bin/oats.mjs): the observer and the list. */
|
|
21
21
|
const LISTS = { "resolved-deployment": ["resolved-deployment"], deployments: ["deployments"] };
|
|
22
22
|
/** The deployment reads (status and workspace status): their call scope (lib/read-call.mjs: the remote budget,
|
|
@@ -42,6 +42,7 @@ const LEAVES = {
|
|
|
42
42
|
argv: () => import("./argv.mjs"),
|
|
43
43
|
"automation-api": () => import("./automation-api.mjs"),
|
|
44
44
|
"captured-context": () => import("./captured-context.mjs"),
|
|
45
|
+
"command-flags": () => import("./command-flags.mjs"),
|
|
45
46
|
deployments: () => import("./deployments.mjs"),
|
|
46
47
|
deprecation: () => import("./deprecation.mjs"),
|
|
47
48
|
errors: () => import("./errors.mjs"),
|
package/lib/instance-events.mjs
CHANGED
|
@@ -42,13 +42,22 @@
|
|
|
42
42
|
* that checks "the rows' home is the home I asked for" keeps holding. */
|
|
43
43
|
import { appendFileSync, closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "node:fs";
|
|
44
44
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
45
|
-
import { REFUSED_TEXT } from "./refused-text.mjs";
|
|
45
|
+
import { REFUSED_TEXT, safeText } from "./refused-text.mjs";
|
|
46
46
|
|
|
47
47
|
export const EVENTS_API = 2;
|
|
48
48
|
const HOME_LOG = ".oats-events.jsonl";
|
|
49
49
|
const MAX_BYTES = 4 * 1024 * 1024;
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
/** The kind of the row a retire hook's warning is recorded as (#1749): the one name the writer
|
|
52
|
+
* (retireInstance) and its tests use. */
|
|
53
|
+
export const RETIRE_HOOK_WARNING_KIND = "retire-warning";
|
|
54
|
+
/** The kinds whose `data.message` is a hook's or the kernel's warning text, and the longest one a
|
|
55
|
+
* row stores, in UTF-16 code units: the Desktop events reader's default detail bound
|
|
56
|
+
* (`eventsDetail`), which refuses the WHOLE read past it, as for RETIRE_REFUSED_REASON_MAX. */
|
|
57
|
+
const WARNING_KINDS = ["launch-warning", RETIRE_HOOK_WARNING_KIND];
|
|
58
|
+
export const WARNING_MESSAGE_MAX = 2048;
|
|
59
|
+
|
|
60
|
+
export const EVENT_KINDS = ["spawned", "launched", "restarted", "stopped", "stop-refused", "retire-planned", "retired", "retire-refused", RETIRE_HOOK_WARNING_KIND, "worktree-retained", "worktree-removed", "worktree-added", "branch-deleted", "child-spawn-refused", "launch-warning", "launch-prompt", "recomposed", "modules-upgraded", "upgrade-refused", "waiting", "wake-held"];
|
|
52
61
|
|
|
53
62
|
/** The longest `reason` a `retire-refused` row carries, in UTF-16 code units. The bound is not the
|
|
54
63
|
* kernel's: the Desktop's events reader refuses a whole read that holds a longer detail
|
|
@@ -60,9 +69,13 @@ export const RETIRE_REFUSED_REASON_MAX = 2048;
|
|
|
60
69
|
* units. A longer one is cut and ends with `…`, the mark counted in the bound, and never through a
|
|
61
70
|
* surrogate pair. */
|
|
62
71
|
export function retireRefusedReason(sentence) {
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
72
|
+
return cutToUnits(String(sentence).replace(/\s+/g, " ").trim(), RETIRE_REFUSED_REASON_MAX);
|
|
73
|
+
}
|
|
74
|
+
/** `text` at most `max` UTF-16 code units: a longer one is cut and ends with `…`, the mark counted
|
|
75
|
+
* in the bound, and never through a surrogate pair. */
|
|
76
|
+
function cutToUnits(text, max) {
|
|
77
|
+
if (text.length <= max) return text;
|
|
78
|
+
const cut = text.slice(0, max - 1);
|
|
66
79
|
const last = cut.charCodeAt(cut.length - 1);
|
|
67
80
|
// A high surrogate at the end was the first half of a pair the cut went through.
|
|
68
81
|
return `${last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut}…`;
|
|
@@ -193,7 +206,16 @@ function append(a, event, { workspaceOnly = false, incarnation, at } = {}) {
|
|
|
193
206
|
// `at`: the time the fact became true, when it is recorded later (a start
|
|
194
207
|
// boundary reconciled from its receipt); readers order rows by it.
|
|
195
208
|
if (at !== undefined && !validTime(at)) return { ok: false, reason: `invalid event time ${at}` };
|
|
196
|
-
|
|
209
|
+
// A warning's message is text from outside (a hook's own words, or a kernel line quoting them):
|
|
210
|
+
// stored made safe and bounded here, where no writer can skip it, and never interpreted. A value
|
|
211
|
+
// that is not a string is stored as its JSON. The answer that carried the warning keeps it as given.
|
|
212
|
+
let data = event.data;
|
|
213
|
+
if (WARNING_KINDS.includes(event.kind) && data && typeof data === "object" && Object.hasOwn(data, "message")) {
|
|
214
|
+
const m = data.message;
|
|
215
|
+
// safeText with no bound only replaces; the cut counts the units the Desktop reader counts.
|
|
216
|
+
data = { ...data, message: cutToUnits(safeText(typeof m === "string" ? m : JSON.stringify(m), Infinity), WARNING_MESSAGE_MAX) };
|
|
217
|
+
}
|
|
218
|
+
const row = { eventsApi: EVENTS_API, at: at ?? new Date().toISOString(), instance: a.instance, home: a.home, incarnation: incarnation === undefined ? a.incarnation : incarnation, producer: event.producer || "kernel", kind: event.kind, ...(data !== undefined ? { data } : {}) };
|
|
197
219
|
const line = JSON.stringify(row) + "\n";
|
|
198
220
|
const results = [];
|
|
199
221
|
// Retirement fingerprints the home against its baseline and preserves any
|
package/lib/instance-git.mjs
CHANGED
|
@@ -25,21 +25,136 @@ export const INSTANCE_GIT_API = 1;
|
|
|
25
25
|
* (GIT_NO_LAZY_FETCH=1): an object a promisor repository lacks is a failed
|
|
26
26
|
* read, never fetched through the remote, helper, ssh command or credential
|
|
27
27
|
* helper the repository's configuration names, and never written into it.
|
|
28
|
-
* Git before 2.44 ignores the variable.
|
|
28
|
+
* Git before 2.44 ignores the variable.
|
|
29
|
+
*
|
|
30
|
+
* Filter drivers (`filter.<name>.clean`, `.process`, `.smudge`): Git runs a
|
|
31
|
+
* clean or process filter when a status or a diff compares a work-tree file
|
|
32
|
+
* that carries the `filter` attribute, and it has no switch that turns
|
|
33
|
+
* filters off. Their names are the repository's to choose, so a command
|
|
34
|
+
* is preceded by one read of the configuration Git would use
|
|
35
|
+
* (`git config --list`, which runs nothing and follows `include.path` and
|
|
36
|
+
* `includeIf`), and every driver that read names is overridden to no command
|
|
37
|
+
* and not required (filterOverrides). An observation (observeInstanceGit)
|
|
38
|
+
* makes that read once, before its status, for its status and its line
|
|
39
|
+
* counts. A file with such an attribute is then
|
|
40
|
+
* compared as its bytes are in the work tree, unfiltered. A driver whose
|
|
41
|
+
* name `-c` cannot carry (it holds `=`, or is not UTF-8) is not overridden:
|
|
42
|
+
* the command is not run and the read fails. What this does not cover:
|
|
43
|
+
* - a driver added to the configuration between that read and the command
|
|
44
|
+
* (two processes; Git reads its configuration itself). For an observation
|
|
45
|
+
* that is until its last command that reads a work-tree file, the line
|
|
46
|
+
* counts' diff, which runs after the status and the reads of HEAD, the
|
|
47
|
+
* index and the refs;
|
|
48
|
+
* - a submodule's own configuration. A status or a diff of the work tree
|
|
49
|
+
* runs Git inside each populated submodule to learn whether it is dirty,
|
|
50
|
+
* and that Git reads the submodule's configuration: the overrides reach it
|
|
51
|
+
* (as fsmonitor's, the hooks' and the external diff's do), but they name
|
|
52
|
+
* this repository's drivers, not the submodule's.
|
|
53
|
+
*
|
|
54
|
+
* Commands that read no file of the work tree are not preceded by that
|
|
55
|
+
* read: the reads of HEAD and of refs (readHead, gitRefPresence,
|
|
56
|
+
* worktreeCommitUnreached: `symbolic-ref`, `rev-parse`, `for-each-ref`), and
|
|
57
|
+
* this module's own READS_NO_WORK_TREE_FILE commands. A command another
|
|
58
|
+
* module passes (gitRead, gitRepoRead, gitRepoRun) always is. */
|
|
29
59
|
const READ_ONLY_GIT = ["--no-optional-locks",
|
|
30
60
|
"-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-c", "diff.external=", "-c", "core.pager=cat",
|
|
31
61
|
"-c", "core.untrackedCache=false", "-c", "index.threads=1", "-c", "safe.bareRepository=explicit"];
|
|
62
|
+
/** The subcommands this module runs (git) that read refs, objects, the index or the configuration,
|
|
63
|
+
* and no file of the work tree: no filter can run in them. */
|
|
64
|
+
const READS_NO_WORK_TREE_FILE = new Set(["rev-parse", "symbolic-ref", "merge-base", "rev-list", "ls-files", "config", "remote"]);
|
|
32
65
|
function gitEnv() {
|
|
33
66
|
const env = { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", LANG: "C", LC_ALL: "C", GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1", GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" };
|
|
34
67
|
// The user's global config may name helpers too; observations do not need it.
|
|
35
68
|
env.GIT_CONFIG_GLOBAL = "/dev/null";
|
|
36
69
|
return env;
|
|
37
70
|
}
|
|
38
|
-
|
|
71
|
+
/** The `filter.<name>.<variable>` keys of a `git config --list -z` listing → [{ name, variable }].
|
|
72
|
+
* A record is "<key>\n<value>", or "<key>" alone. A driver's name is any text, dots and the empty
|
|
73
|
+
* one included (`filter..clean`); a variable holds no dot, and Git prints it in lower case. */
|
|
74
|
+
export function filterDriverKeys(listing) {
|
|
75
|
+
const keys = [];
|
|
76
|
+
for (const record of listing.split("\0")) {
|
|
77
|
+
const nl = record.indexOf("\n");
|
|
78
|
+
const m = /^filter\.(.*)\.([^.]+)$/s.exec(nl < 0 ? record : record.slice(0, nl));
|
|
79
|
+
if (m) keys.push({ name: m[1], variable: m[2] });
|
|
80
|
+
}
|
|
81
|
+
return keys;
|
|
82
|
+
}
|
|
83
|
+
/** The filter drivers the configuration of the repository at `where` (`-C <tree>` or `--git-dir <dir>`)
|
|
84
|
+
* defines, and the `-c` arguments that keep Git from running any of them
|
|
85
|
+
* → { ok: true, count, args } | { ok: false, refused, err }.
|
|
86
|
+
* `refused: true`: a driver is defined whose name `-c` cannot carry, so nothing can be run safely.
|
|
87
|
+
* `refused: false`: the configuration could not be read (`err` is Git's own words); the command it
|
|
88
|
+
* was read for would fail the same way.
|
|
89
|
+
* The listing is read as bytes (latin1 keeps each one): a name is passed on only when it is UTF-8,
|
|
90
|
+
* since that is how an argument reaches Git.
|
|
91
|
+
* The configuration listed is the repository's own (its local and per-worktree files and what they
|
|
92
|
+
* include), read with gitEnv: a driver that only the operator's own configuration (global, system)
|
|
93
|
+
* defines is not listed, and so not overridden where a caller's Git reads that configuration.
|
|
94
|
+
* `operatorEnv`, for a caller whose Git reads the operator's own configuration (a retire, a
|
|
95
|
+
* worktree removal), is the environment that Git runs with. A driver the repository defines under
|
|
96
|
+
* a name that configuration defines too is then overridden with the operator's own values, not
|
|
97
|
+
* with none: the operator's command runs, as it does for that name everywhere else the operator's
|
|
98
|
+
* Git runs (a retire's recovery copy has no configuration of its own), and the repository's never
|
|
99
|
+
* does. The operator's configuration is the human's; the repository's is the agent's to write. A
|
|
100
|
+
* configuration of the operator's that cannot be read defines nothing.
|
|
101
|
+
* The one reader of a repository's filter drivers: this module's commands, a retire's
|
|
102
|
+
* (lib/core.mjs retireGitArgv) and a worktree removal's (lib/worktree.mjs) take their overrides here. */
|
|
103
|
+
export function filterOverrides(where, { operatorEnv } = {}) {
|
|
104
|
+
const r = spawnSync("git", [...where, ...READ_ONLY_GIT, "config", "--list", "-z"], { encoding: "latin1", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() });
|
|
105
|
+
if (r.error || r.status !== 0) return { ok: false, refused: false, err: String(r.error?.message ?? r.stderr ?? "").trim() || `git config exited with ${r.status}` };
|
|
106
|
+
const names = new Set(filterDriverKeys(r.stdout).map((key) => key.name));
|
|
107
|
+
const operator = names.size > 0 && operatorEnv ? operatorDrivers(operatorEnv) : new Map();
|
|
108
|
+
const args = [];
|
|
109
|
+
for (const raw of names) {
|
|
110
|
+
const bytes = Buffer.from(raw, "latin1");
|
|
111
|
+
const name = bytes.toString("utf8");
|
|
112
|
+
if (name.includes("=") || !Buffer.from(name, "utf8").equals(bytes)) {
|
|
113
|
+
return { ok: false, refused: true, err: "the repository's configuration defines a filter driver whose name cannot be overridden on Git's command line (it holds \"=\" or is not UTF-8), so Git was not run: it would run that filter" };
|
|
114
|
+
}
|
|
115
|
+
const own = operator.get(raw) ?? {};
|
|
116
|
+
for (const command of ["clean", "smudge", "process"]) args.push("-c", `filter.${name}.${command}=${own[command] ?? ""}`);
|
|
117
|
+
args.push("-c", `filter.${name}.required=${own.required ?? "false"}`);
|
|
118
|
+
}
|
|
119
|
+
return { ok: true, count: names.size, args };
|
|
120
|
+
}
|
|
121
|
+
/** The filter drivers the operator's own configuration defines, as the Git that runs with `env`
|
|
122
|
+
* reads it: the system configuration, then the global one (`~/.gitconfig`,
|
|
123
|
+
* `$XDG_CONFIG_HOME/git/config`, or `$GIT_CONFIG_GLOBAL`), whose value wins as it does for Git
|
|
124
|
+
* → Map of a driver's name, as the bytes of the listing, to { clean?, smudge?, process?,
|
|
125
|
+
* required? }, each the last value given. A scope that cannot be read (no such file) defines
|
|
126
|
+
* nothing, and the system one is not read when `env` tells Git not to (GIT_CONFIG_NOSYSTEM, a
|
|
127
|
+
* Git boolean: `git config --system` itself reads the file regardless). Each is read by its
|
|
128
|
+
* scope: no repository's configuration is part of it. */
|
|
129
|
+
function operatorDrivers(env) {
|
|
130
|
+
const drivers = new Map();
|
|
131
|
+
const noSystem = !["", "0", "false", "no", "off"].includes(String(env.GIT_CONFIG_NOSYSTEM ?? "").trim().toLowerCase());
|
|
132
|
+
for (const scope of noSystem ? ["--global"] : ["--system", "--global"]) {
|
|
133
|
+
const r = spawnSync("git", [...READ_ONLY_GIT, "config", scope, "--list", "-z"], { encoding: "latin1", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env });
|
|
134
|
+
if (r.error || r.status !== 0) continue;
|
|
135
|
+
for (const record of r.stdout.split("\0")) {
|
|
136
|
+
const nl = record.indexOf("\n");
|
|
137
|
+
const [key] = filterDriverKeys(nl < 0 ? record : record.slice(0, nl));
|
|
138
|
+
if (!key) continue;
|
|
139
|
+
if (!drivers.has(key.name)) drivers.set(key.name, {});
|
|
140
|
+
drivers.get(key.name)[key.variable] = Buffer.from(nl < 0 ? "true" : record.slice(nl + 1), "latin1").toString("utf8");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return drivers;
|
|
144
|
+
}
|
|
145
|
+
/** `overrides`: a filterOverrides result the caller already has for `cwd` (an observation reads it
|
|
146
|
+
* once for its commands); without it the command is preceded by its own read. */
|
|
147
|
+
function git(cwd, argv, { allowFail = false, input, diffExit = false, overrides } = {}) {
|
|
39
148
|
const [sub, ...rest] = argv;
|
|
40
149
|
const extra = sub === "diff" ? ["--no-ext-diff", "--no-textconv", "--no-color"] : [];
|
|
150
|
+
const filters = READS_NO_WORK_TREE_FILE.has(sub) ? { ok: true, args: [] } : overrides ?? filterOverrides(["-C", cwd]);
|
|
151
|
+
if (!filters.ok) {
|
|
152
|
+
// A refusal is not Git failing: it is never read as "no answer".
|
|
153
|
+
if (allowFail && !filters.refused) return null;
|
|
154
|
+
throw oatsError("E_GIT_FAILED", `git ${sub} failed in ${cwd}: ${filters.err}`);
|
|
155
|
+
}
|
|
41
156
|
try {
|
|
42
|
-
return execFileSync("git", [...READ_ONLY_GIT, "-C", cwd, sub, ...extra, ...rest], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, input, shell: false, timeout: 30_000, env: gitEnv() });
|
|
157
|
+
return execFileSync("git", [...READ_ONLY_GIT, ...filters.args, "-C", cwd, sub, ...extra, ...rest], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, input, shell: false, timeout: 30_000, env: gitEnv() });
|
|
43
158
|
} catch (e) {
|
|
44
159
|
// `git diff --no-index` exits 1 when the inputs differ: that is the answer, not a failure.
|
|
45
160
|
if (diffExit && e.status === 1 && typeof e.stdout === "string") return e.stdout;
|
|
@@ -63,11 +178,15 @@ export function gitRepoRead(gitDir, argv, { input, encoding } = {}) { return git
|
|
|
63
178
|
/** A Git command that changes the repository whose Git directory is `gitDir`
|
|
64
179
|
* (a worktree move, remove or prune), under the same discipline as the
|
|
65
180
|
* reads: the repository's own configuration names no helper that runs
|
|
66
|
-
* (fsmonitor, hooks, external diff; they reach the commands
|
|
67
|
-
* it through GIT_CONFIG_PARAMETERS), and nothing of the
|
|
68
|
-
* environment is passed. → stdout; throws the error
|
|
181
|
+
* (fsmonitor, hooks, external diff, filter drivers; they reach the commands
|
|
182
|
+
* Git starts for it through GIT_CONFIG_PARAMETERS), and nothing of the
|
|
183
|
+
* caller's Git environment is passed. → stdout; throws the error
|
|
184
|
+
* execFileSync throws, or an Error when a filter driver cannot be overridden
|
|
185
|
+
* (filterOverrides), in which case Git was not run. */
|
|
69
186
|
export function gitRepoRun(gitDir, argv) {
|
|
70
|
-
|
|
187
|
+
const filters = filterOverrides(["--git-dir", gitDir]);
|
|
188
|
+
if (!filters.ok) throw new Error(`git ${argv[0]} was not run in ${gitDir}: ${filters.err}`);
|
|
189
|
+
return execFileSync("git", ["--git-dir", gitDir, ...READ_ONLY_GIT, ...filters.args, ...argv], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 120_000, env: gitEnv() });
|
|
71
190
|
}
|
|
72
191
|
/** What the result of a `git rev-parse -q --verify <ref>` (spawnSync's) says
|
|
73
192
|
* of the ref → "there" (status 0), "absent" (status 1 and nothing printed),
|
|
@@ -90,7 +209,9 @@ export function gitRefPresence(cwd, name) {
|
|
|
90
209
|
return gitRefPresenceOf(spawnSync("git", ["-C", cwd, ...READ_ONLY_GIT, "rev-parse", "-q", "--verify", name], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() }));
|
|
91
210
|
}
|
|
92
211
|
function gitProbe(where, argv, input, encoding = "utf8") {
|
|
93
|
-
const
|
|
212
|
+
const filters = filterOverrides(where);
|
|
213
|
+
if (!filters.ok) return { ok: false, out: "", err: filters.err };
|
|
214
|
+
const r = spawnSync("git", [...where, ...READ_ONLY_GIT, ...filters.args, ...argv], { encoding, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input, maxBuffer: GIT_MAX_BUFFER, shell: false, timeout: 30_000, env: gitEnv() });
|
|
94
215
|
return !r.error && r.status === 0 ? { ok: true, out: r.stdout } : { ok: false, out: "", err: String(r.error?.message ?? r.stderr ?? "").trim() || `git ${argv[0]} exited with ${r.status}` };
|
|
95
216
|
}
|
|
96
217
|
|
|
@@ -280,10 +401,10 @@ function remoteOf(work, branch) {
|
|
|
280
401
|
* and `oats instance diff`. An unborn tree counts against the empty tree (`hash-object` without -w writes nothing).
|
|
281
402
|
* → Map path → { additions, deletions, binary }, keyed by the NEW path for a rename; null when git failed.
|
|
282
403
|
* -z records: "A\tD\tpath\0", or "A\tD\t\0old\0new\0" for a rename; "-\t-" is a binary file. */
|
|
283
|
-
function lineCounts(work, headOid) {
|
|
284
|
-
const against = headOid ?? trim(git(work, ["hash-object", "-t", "tree", "/dev/null"], { allowFail: true }));
|
|
404
|
+
function lineCounts(work, headOid, overrides) {
|
|
405
|
+
const against = headOid ?? trim(git(work, ["hash-object", "-t", "tree", "/dev/null"], { allowFail: true, overrides }));
|
|
285
406
|
if (!against) return null;
|
|
286
|
-
const raw = git(work, ["diff", against, "--numstat", "-z", "-M", "--"], { allowFail: true });
|
|
407
|
+
const raw = git(work, ["diff", against, "--numstat", "-z", "-M", "--"], { allowFail: true, overrides });
|
|
287
408
|
if (raw === null) return null;
|
|
288
409
|
const counts = new Map(), recs = raw.split("\0");
|
|
289
410
|
for (let i = 0; i < recs.length;) {
|
|
@@ -343,7 +464,10 @@ export function assertSameWorktreeHead(inspected, now) {
|
|
|
343
464
|
export function observeInstanceGit(home) {
|
|
344
465
|
const { meta, work, mode } = instanceWorkTree(home);
|
|
345
466
|
const headOid = trim(git(work, ["rev-parse", "--verify", "--quiet", "HEAD"], { allowFail: true }));
|
|
346
|
-
|
|
467
|
+
// The repository's filter drivers, read once for the observation's commands that read a
|
|
468
|
+
// work-tree file (the status here, the line counts below).
|
|
469
|
+
const filters = filterOverrides(["-C", work]);
|
|
470
|
+
const raw = git(work, ["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=all", "--ignore-submodules=none"], { overrides: filters });
|
|
347
471
|
const { branch, entries } = parsePorcelainV2(raw);
|
|
348
472
|
// The name comes from headName, not from the status header, which prints
|
|
349
473
|
// "(detached)" and other words where a name would be and is read as text.
|
|
@@ -365,7 +489,7 @@ export function observeInstanceGit(home) {
|
|
|
365
489
|
const counts = mergeBase ? countRange(work, `${base.ref}...HEAD`) : null;
|
|
366
490
|
baseComparison = { ref: base.ref, source: base.source, mergeBase, ahead: counts ? counts.right : null, behind: counts ? counts.left : null };
|
|
367
491
|
}
|
|
368
|
-
const counts = lineCounts(work, headOid);
|
|
492
|
+
const counts = lineCounts(work, headOid, filters);
|
|
369
493
|
const files = entries.filter((e) => e.kind !== "ignored").map((e) => ({ id: fileId(revision, indexOid, e), ...e, ...countsOf(counts, e) }));
|
|
370
494
|
const summary = { changed: 0, renamed: 0, copied: 0, unmerged: 0, untracked: 0 };
|
|
371
495
|
for (const f of files) summary[f.kind]++;
|
|
@@ -383,6 +507,7 @@ export function observeInstanceGit(home) {
|
|
|
383
507
|
...(upstream.ref === null ? ["no upstream configured: upstream ahead/behind are unknown, not zero"] : []),
|
|
384
508
|
...(baseComparison.ref === null ? ["no default branch found (origin/HEAD, origin/main, origin/master, main, master): base comparison unknown"] : []),
|
|
385
509
|
...(counts === null ? ["line counts unavailable (git diff --numstat failed): additions/deletions are unknown, not zero"] : []),
|
|
510
|
+
...(filters.ok && filters.count > 0 ? ["the repository's configuration defines a filter driver, and filters are not run: a file one applies to is compared as its bytes are in the work tree, so it can read as changed, and its diff is against the stored form"] : []),
|
|
386
511
|
],
|
|
387
512
|
};
|
|
388
513
|
}
|