@awebai/oats 0.69.12 → 0.69.15
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 +254 -201
- package/docs/capabilities.md +58 -13
- package/docs/configuration.md +63 -5
- package/docs/container.md +291 -0
- package/docs/design/2026-09-23-workspace-module-contracts.md +2 -0
- package/docs/desktop-cli-api.md +590 -55
- package/docs/desktop-instance-start.md +4 -1
- package/docs/desktop.md +58 -12
- package/docs/execution-targets.md +84 -9
- package/docs/first-team.md +4 -3
- package/docs/implementation.md +99 -32
- 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/release-notes/v0.69.15.md +444 -0
- package/docs/schedules.md +159 -5
- package/docs/servers.md +241 -7
- package/docs/souls-and-instances.md +223 -14
- package/docs/tui.md +1 -1
- package/docs/upgrading.md +36 -5
- package/docs/workspaces.md +31 -5
- package/lib/claim.mjs +20 -5
- package/lib/command-flags.mjs +240 -0
- package/lib/core.mjs +1004 -633
- package/lib/deployments.mjs +4 -3
- package/lib/dir-lock.mjs +145 -33
- package/lib/errors.mjs +3 -2
- package/lib/harness-token.mjs +110 -0
- package/lib/host-run.mjs +218 -0
- package/lib/host-stop-child.mjs +21 -0
- package/lib/hot-reads.mjs +4 -3
- package/lib/instance-events.mjs +28 -6
- package/lib/instance-git.mjs +165 -14
- package/lib/instance-inspect.mjs +6 -1
- package/lib/instance-lifecycle.mjs +4 -3
- package/lib/instance-listing.mjs +114 -43
- package/lib/instance-resolution.mjs +56 -3
- package/lib/instance-upgrade.mjs +16 -20
- package/lib/kernel-features.mjs +4 -1
- 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 +4 -1
- package/lib/reader.mjs +3 -2
- package/lib/refused-text.mjs +3 -2
- package/lib/remote.mjs +126 -31
- 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 +239 -21
- package/lib/servers.mjs +161 -28
- package/lib/session-end.mjs +28 -8
- package/lib/session-resume.mjs +63 -56
- package/lib/session-seen.mjs +3 -14
- package/lib/start-env.mjs +13 -7
- package/lib/status-words.mjs +11 -4
- package/lib/system-tools.mjs +1 -36
- package/lib/teams.mjs +11 -4
- package/lib/upgrade-state.mjs +13 -2
- package/lib/worktree-hooks.mjs +6 -175
- package/lib/worktree.mjs +68 -10
- package/package-catalog.json +1 -1
- package/package.json +5 -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/packages/record/README.md +56 -21
- package/packages/record/docs/capture-service.md +8 -5
- package/packages/record/docs/turn-record-sot.md +9 -0
- package/packages/record/lib/capture-health.mjs +6 -4
- package/packages/record/lib/capture-lock.mjs +31 -27
- package/packages/record/lib/capture-retained-scratch.mjs +4 -3
- package/packages/record/lib/capture-scratch.mjs +2 -1
- package/packages/record/lib/derived-state.mjs +4 -2
- package/packages/record/lib/index-db.mjs +4 -2
- package/packages/record/lib/lock-holder.mjs +21 -0
- package/packages/record/lib/private-files.mjs +18 -0
- package/packages/record/lib/process-identity.mjs +310 -0
- package/packages/record/lib/store.mjs +31 -25
- package/share/oats-login-receive +204 -0
- package/skills/oats-getting-started/SKILL.md +93 -26
- package/lib/tmux-config.mjs +0 -35
package/lib/session-seen.mjs
CHANGED
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
* rename wins whole).
|
|
18
18
|
* - Whether a loss is resumed is one pure function, resumeEligible.
|
|
19
19
|
* Dependency-free. */
|
|
20
|
-
import { execFileSync } from "node:child_process";
|
|
21
20
|
import { createHash, randomBytes } from "node:crypto";
|
|
22
21
|
import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
23
22
|
import { homedir } from "node:os";
|
|
24
23
|
import { dirname, join, resolve } from "node:path";
|
|
24
|
+
import { thisBoot } from "../packages/record/lib/process-identity.mjs";
|
|
25
|
+
|
|
26
|
+
export { bootId, identityHolderState, namesIdentity, takenInAnotherBoot, thisBoot, validPid } from "../packages/record/lib/process-identity.mjs";
|
|
25
27
|
|
|
26
28
|
/** A loss first seen this long ago or more is not resumed. */
|
|
27
29
|
export const FIRST_SEEN_MAX_MS = 24 * 60 * 60_000;
|
|
@@ -34,19 +36,6 @@ const oatsHomeDir = () => process.env.OATS_HOME_DIR || join(homedir(), ".oats");
|
|
|
34
36
|
/** The kernel-private directory of the sweep's lock, its per-boot note and this record. */
|
|
35
37
|
export const resumeStateDir = () => join(oatsHomeDir(), "session-resume");
|
|
36
38
|
|
|
37
|
-
/** This boot's identity, or null where the kernel cannot read one: Linux's boot id, macOS's boot
|
|
38
|
-
* time (`sysctl -n kern.boottime`, its `sec`/`usec`). */
|
|
39
|
-
export function bootId({ platform = process.platform, read = (p) => readFileSync(p, "utf8"), sysctl = () => execFileSync("sysctl", ["-n", "kern.boottime"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }) } = {}) {
|
|
40
|
-
try {
|
|
41
|
-
if (platform === "linux") return read("/proc/sys/kernel/random/boot_id").trim() || null;
|
|
42
|
-
if (platform === "darwin") { const m = /sec = (\d+), usec = (\d+)/.exec(sysctl()); return m ? `${m[1]}.${m[2]}` : null; }
|
|
43
|
-
} catch { /* unknown */ }
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
let processBoot;
|
|
47
|
-
/** bootId, read once per process: a process never outlives its boot. */
|
|
48
|
-
export const thisBoot = () => (processBoot === undefined ? (processBoot = bootId()) : processBoot);
|
|
49
|
-
|
|
50
39
|
const realOrResolved = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
|
|
51
40
|
/** The key of `home` in a record: its real path, so a deployment reached through a symlink (an
|
|
52
41
|
* explicit `--deployment` spelled so, a cwd under one) reads and writes the same entry. */
|
package/lib/start-env.mjs
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
/** What a start's launch environment was (feature session-resume, #1559): the record that lets a
|
|
2
|
-
* resume refuse to start under a
|
|
2
|
+
* resume refuse to start under a reference value that changed since the start it brings back.
|
|
3
3
|
* Kernel-private files in the home, not a contract:
|
|
4
4
|
* - `.oats-start-env.key`: 32 random bytes, mode 0600, made once, at the first start that records.
|
|
5
5
|
* It never leaves the home: never logged, answered or put in an event.
|
|
6
|
-
* - `.oats-start-env.json`: `{ startId, digests: { <
|
|
6
|
+
* - `.oats-start-env.json`: `{ startId, digests: { <reference source (env name or file:path)>: <hex HMAC-SHA256(key,
|
|
7
7
|
* value)> } }`, written whole (tmp + rename) at every start that renders a recipe, for that
|
|
8
8
|
* start's id; `digests` is `{}` for a launch with no reference. A value is never written: a
|
|
9
|
-
*
|
|
9
|
+
* reference value may be a credential, and only its keyed one-way digest is kept.
|
|
10
10
|
* The record is best effort: a write that fails leaves the previous record (for another start) or
|
|
11
11
|
* none, which a resume reads as unverified. A retire's recovery copy of the home leaves both out
|
|
12
|
-
* (lib/core.mjs copyRecoveryHome).
|
|
12
|
+
* (lib/core.mjs copyRecoveryHome). Uses only Node built-ins and kernel helpers: the start, the spawn and the sweep's
|
|
13
13
|
* `--plan` read and write it through here. */
|
|
14
|
+
import { fileReferenceProblems, fileReferenceRemedy } from "./launch-env.mjs";
|
|
14
15
|
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
15
16
|
import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
16
17
|
import { join } from "node:path";
|
|
@@ -29,8 +30,13 @@ export function fromEnvNames(recipeEnv) {
|
|
|
29
30
|
}
|
|
30
31
|
|
|
31
32
|
/** The message of a resume refused for references that are not set (E_LAUNCH_ENV_MISSING). */
|
|
32
|
-
export function launchEnvMissingMessage(names) {
|
|
33
|
-
|
|
33
|
+
export function launchEnvMissingMessage(names, harness) {
|
|
34
|
+
const files = fileReferenceProblems(names);
|
|
35
|
+
if (files.length) {
|
|
36
|
+
const variables = names.filter((name) => !name.startsWith("file:"));
|
|
37
|
+
return [...(variables.length ? [`launch references ${variables.join(", ")}, not set on this host`] : []), ...files, "nothing was created or started"].join("; ") + fileReferenceRemedy(names, harness);
|
|
38
|
+
}
|
|
39
|
+
return `this home's launch references ${names.join(", ")}, not set on this host; nothing was started${fileReferenceRemedy(names, harness)}`;
|
|
34
40
|
}
|
|
35
41
|
/** The message of a resume refused for a changed value (E_LAUNCH_ENV_CHANGED): names only, sorted. */
|
|
36
42
|
export function launchEnvChangedMessage(names) {
|
|
@@ -64,7 +70,7 @@ function writeWhole(path, bytes) {
|
|
|
64
70
|
}
|
|
65
71
|
|
|
66
72
|
/** Record the launch environment of start `startId` of `home`: the digest of each of `names` (source
|
|
67
|
-
* names, fromEnvNames) as `env` holds it. A home without a usable key gets a new one first, and its
|
|
73
|
+
* names, fromEnvNames or launchEnvRefs source fields) as `env` holds it. A home without a usable key gets a new one first, and its
|
|
68
74
|
* old record goes before the key is replaced, so no record is ever read with a key it was not made
|
|
69
75
|
* with. Never throws: → true when the record was written. */
|
|
70
76
|
export function recordStartEnv(home, startId, names, env) {
|
package/lib/status-words.mjs
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
* in, strings out: the row is a `status --json` instance row, this kernel's or a host's (the roster
|
|
4
4
|
* relays its `sessionEnd`), read as it is. A host on a kernel before `sessionEnd` (feature
|
|
5
5
|
* session-resume) sends none, and its rows read `idle` as before. The JSON is never changed here.
|
|
6
|
-
* Dependency-free. */
|
|
6
|
+
* Rows in, strings out, but for one read: a local lost row's reason (lostLine). Dependency-free. */
|
|
7
7
|
import { terminalText } from "./refused-text.mjs";
|
|
8
8
|
import { shellWord } from "./shell-word.mjs";
|
|
9
|
+
import { HOST_STOP_REASON, lostReasonOf } from "./session-end.mjs";
|
|
9
10
|
import { SESSION_END } from "./session-resume-contract.mjs";
|
|
10
11
|
|
|
11
12
|
const isLost = (i) => i.running === false && i.sessionEnd === SESSION_END.LOST;
|
|
@@ -50,13 +51,19 @@ export function waitingLine(i, { now = Date.now(), timeZone } = {}) {
|
|
|
50
51
|
return `! needs input (${claim.reason ?? "unknown"})${timing}${claim.message ? `: ${claim.message}` : ""}`;
|
|
51
52
|
}
|
|
52
53
|
|
|
54
|
+
/** What a lost row says of why it was lost, by the reason its home records (lib/session-end.mjs). */
|
|
55
|
+
const LOST_REASON_SAID = Object.freeze({ [HOST_STOP_REASON]: "stopped with the host" });
|
|
56
|
+
|
|
53
57
|
/** The one line under a LOST row that says how to bring it back, or null for any other row. Local:
|
|
54
|
-
* the resume by hand, or the next sweep
|
|
55
|
-
*
|
|
58
|
+
* the resume by hand, or the next sweep, after why it was lost when its home records that (read
|
|
59
|
+
* here from the home: the row carries no reason). `host` (a `--server` or roster row): both refuse
|
|
60
|
+
* `--server` (E_BAD_ARGS), so the line says to run them on that host; its home is not read. */
|
|
56
61
|
export function lostLine(i, { host } = {}) {
|
|
57
62
|
if (i.retirePending || !isLost(i)) return null;
|
|
58
63
|
const start = typeof i.home === "string" && i.home ? `oats session start --resume --home ${shellWord(i.home)}` : null;
|
|
59
64
|
if (host !== undefined) return terminalText(`lost: on ${host}, run ${start ? `${start} there, or its next oats session resume` : "oats session resume there"}`);
|
|
65
|
+
const why = start ? LOST_REASON_SAID[lostReasonOf(i.home, i)] : undefined;
|
|
66
|
+
const lost = why ? `lost (${why})` : "lost";
|
|
60
67
|
const sweep = "the next oats session resume (run when OATS Desktop or oats tui opens)";
|
|
61
|
-
return terminalText(start ?
|
|
68
|
+
return terminalText(start ? `${lost}: ${start} brings it back; so does ${sweep} if it can vouch for the loss` : `${lost}: ${sweep} brings it back if it can vouch for the loss`);
|
|
62
69
|
}
|
package/lib/system-tools.mjs
CHANGED
|
@@ -1,39 +1,4 @@
|
|
|
1
1
|
/** System tools: programs the kernel runs from the system's own directories, never from the
|
|
2
2
|
* caller's PATH. A job, a shell or an instance may have changed PATH; what a system tool does
|
|
3
3
|
* (read a process's start, start the OATS tmux server in its own scope) must not depend on it. */
|
|
4
|
-
|
|
5
|
-
import { isAbsolute, join } from "node:path";
|
|
6
|
-
|
|
7
|
-
/** Where a system tool is looked for, in order. */
|
|
8
|
-
export const SYSTEM_TOOL_DIRS = Object.freeze(["/usr/bin", "/bin"]);
|
|
9
|
-
|
|
10
|
-
/** The directories a system tool is looked for in → { dirs } | { reason }. SYSTEM_TOOL_DIRS, or for a
|
|
11
|
-
* test only, OATS_TEST_SYSTEM_TOOL_DIRS: absolute directories separated by `:`. A seam with any other
|
|
12
|
-
* value names no tool at all, never a PATH-like lookup. */
|
|
13
|
-
export function systemToolDirs() {
|
|
14
|
-
const seam = process.env.OATS_TEST_SYSTEM_TOOL_DIRS;
|
|
15
|
-
if (seam === undefined) return { dirs: SYSTEM_TOOL_DIRS };
|
|
16
|
-
const dirs = seam.split(":");
|
|
17
|
-
if (dirs.some((dir) => !isAbsolute(dir))) return { reason: `OATS_TEST_SYSTEM_TOOL_DIRS is ${JSON.stringify(seam)}, not absolute directories` };
|
|
18
|
-
return { dirs };
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
/** `name` in the system directories (`dirs`, else systemToolDirs) → { file } (the first regular
|
|
22
|
-
* executable file, an absolute path) or { reason } (none, and where it looked). Nothing is run. */
|
|
23
|
-
export function systemTool(name, { dirs } = {}) {
|
|
24
|
-
if (typeof name !== "string" || !/^[A-Za-z0-9._+-]+$/.test(name) || name === "." || name === "..") return { reason: `${JSON.stringify(name)} is not a tool name` };
|
|
25
|
-
if (dirs === undefined) {
|
|
26
|
-
const where = systemToolDirs();
|
|
27
|
-
if (where.reason) return { reason: where.reason };
|
|
28
|
-
dirs = where.dirs;
|
|
29
|
-
}
|
|
30
|
-
for (const dir of dirs) {
|
|
31
|
-
const file = join(dir, name);
|
|
32
|
-
try {
|
|
33
|
-
if (!statSync(file).isFile()) continue;
|
|
34
|
-
accessSync(file, constants.X_OK);
|
|
35
|
-
return { file };
|
|
36
|
-
} catch { /* not here */ }
|
|
37
|
-
}
|
|
38
|
-
return { reason: `no executable ${name} in ${dirs.join(", ")}` };
|
|
39
|
-
}
|
|
4
|
+
export { SYSTEM_TOOL_DIRS, systemTool, systemToolDirs } from "../packages/record/lib/process-identity.mjs";
|
package/lib/teams.mjs
CHANGED
|
@@ -128,6 +128,9 @@ export function discoveredTeamKeys(discovery) {
|
|
|
128
128
|
|
|
129
129
|
/** The `souls:` patterns that apply to `key`, most specific first. */
|
|
130
130
|
const patternsOf = (key) => (key === "*" ? ["*"] : [key, `${key.slice(0, key.lastIndexOf("/"))}/*`, "*"]);
|
|
131
|
+
/** Whether the pattern `<prefix>/*` applies to at least one of `soulKeys` (each `<member|package>/<soul>`).
|
|
132
|
+
* The slash is compared too, so `oats.eng/*` does not match `oats.engineering/x`. */
|
|
133
|
+
const patternMatchesAny = (pattern, soulKeys) => { const prefix = `${pattern.slice(0, -2)}/`; return [...soulKeys].some((k) => k.startsWith(prefix)); };
|
|
131
134
|
|
|
132
135
|
const unknown = (label, at) => fail("E_TEAM_UNKNOWN", `team ${JSON.stringify(label)} is not declared (${at}): declare it with \`oats teams add\`, or in oats-workspace.yaml teams: for a shared team`, { label, at });
|
|
133
136
|
const closedMessage = (keys) => `${LOCAL_FILE} declares ${keys.join(", ")}, but oats-workspace.yaml does not allow local teams (localTeams: true): ${CLOSED_FIX}`;
|
|
@@ -204,8 +207,9 @@ const unconfiguredProblem = (model) => ({ code: "E_TEAM_UNCONFIGURED", severity:
|
|
|
204
207
|
: `run \`oats aweb setup\` to create a team, then commit it in oats-workspace.yaml as defaultTeam (or as a soul's default in souls:)${model.localTeams ? ", or record it here with `oats teams add <label> --team <id>`" : ""}` });
|
|
205
208
|
const refusalProblem = (e) => ({ code: e.code, ...e.details, severity: "failure", message: e.message,
|
|
206
209
|
fix: "declare the team (`oats teams add`), or choose another default (`oats teams default`)" });
|
|
207
|
-
const soulUnknownProblem = (key, at) => ({ code: "team-soul-unknown", severity: "warning", key, at,
|
|
208
|
-
message: `souls: ${key}
|
|
210
|
+
const soulUnknownProblem = (key, at, pattern = false) => ({ code: "team-soul-unknown", severity: "warning", key, at,
|
|
211
|
+
...(pattern ? { message: `souls: ${key} is a pattern that matches no soul of this workspace`, fix: "correct the prefix to a member's or package's name (oats souls lists them), or remove the key" }
|
|
212
|
+
: { message: `souls: ${key} names no soul of this workspace (a pattern is "*" or <member|package>/*)`, fix: "correct the key to a soul's qualified name (oats souls lists them), or remove it" }) });
|
|
209
213
|
/** local-teams-closed as a problem (oats teams, readiness, doctor): the refusal's facts, never thrown. */
|
|
210
214
|
export const localTeamsClosedProblem = (keys) => ({ code: "E_WORKSPACE_SCHEMA", severity: "failure", condition: "local-teams-closed", path: LOCAL_FILE, keys: [...keys],
|
|
211
215
|
message: closedMessage(keys), fix: CLOSED_FIX });
|
|
@@ -216,7 +220,8 @@ export const localTeamsClosedProblem = (keys) => ({ code: "E_WORKSPACE_SCHEMA",
|
|
|
216
220
|
* With `key`: only what concerns that soul (`default` marks ITS default). Local teams the workspace does
|
|
217
221
|
* not allow are the one problem either way. `messaging`: a messaging layer is active, so no default is
|
|
218
222
|
* E_TEAM_UNCONFIGURED. `soulKeys` (discoveredTeamKeys; null when the souls are not known): a `souls:` key
|
|
219
|
-
* that is
|
|
223
|
+
* that is not one of them, or a `<prefix>/*` pattern that matches none of them, is `team-soul-unknown` (a typo
|
|
224
|
+
* guard, either way); `"*"` never is.
|
|
220
225
|
*/
|
|
221
226
|
export function teamProblems(model, { key = null, messaging = false, soulKeys = null } = {}) {
|
|
222
227
|
if (model.closedKeys.length) return [localTeamsClosedProblem(model.closedKeys)];
|
|
@@ -229,7 +234,9 @@ export function teamProblems(model, { key = null, messaging = false, soulKeys =
|
|
|
229
234
|
for (const label of labels) { const d = model.labels.get(label); if (d.team === null) problems.push(unmappedProblem(d, t)); }
|
|
230
235
|
if (messaging && t.defaultTeam === null && model.localDefault === null) problems.push(unconfiguredProblem(model));
|
|
231
236
|
if (soulKeys !== null) for (const k of Object.keys(model.souls).sort(byCodepoint)) {
|
|
232
|
-
if (k
|
|
237
|
+
if (k === "*") continue;
|
|
238
|
+
const pattern = k.endsWith("/*");
|
|
239
|
+
if (pattern ? !patternMatchesAny(k, soulKeys) : !soulKeys.has(k)) problems.push(soulUnknownProblem(k, `${model.soulsAt}/${pointerKey(k)}`, pattern));
|
|
233
240
|
}
|
|
234
241
|
return problems;
|
|
235
242
|
}
|
package/lib/upgrade-state.mjs
CHANGED
|
@@ -49,8 +49,9 @@ function retryFor(home, receipt) {
|
|
|
49
49
|
return { instance, command: `oats instance upgrade ${shellWord(instance)}${receipt.undo === true ? " --undo" : ""} --plan-revision ${shellWord(receipt.planRevision)} --idempotency-key ${shellWord(receipt.idempotencyKey)}` };
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
/** The
|
|
53
|
-
*
|
|
52
|
+
/** The command that finishes the upgrade whose regular file is at the home's `.oats-start.lock`,
|
|
53
|
+
* or null when no regular file is there (a start makes nothing at that path). A start never
|
|
54
|
+
* reclaims an upgrade's file, even if its owner died during the initial write. */
|
|
54
55
|
export function upgradeMutexRetry(home) {
|
|
55
56
|
const path = join(home, ".oats-start.lock");
|
|
56
57
|
try { if (!lstatSync(path).isFile()) return null; }
|
|
@@ -99,3 +100,13 @@ export function packageUpgradeDrift(meta, { lock } = {}) {
|
|
|
99
100
|
locked: { version: row.current.version ?? null, commit: row.current.commit ?? null },
|
|
100
101
|
}));
|
|
101
102
|
}
|
|
103
|
+
|
|
104
|
+
/** The start's line for package modules an upgrade cannot move: their package is no longer locked, or no
|
|
105
|
+
* longer provides the capability. An upgrade keeps them; a respawn moves the home onto the lock.
|
|
106
|
+
* → a warning string, or null when there are none. */
|
|
107
|
+
export function packageRespawnWarning(meta, { lock } = {}) {
|
|
108
|
+
const rows = driftOf(meta, null, { lock }).filter((row) => row.from.kind === "package" && row.status === "missing");
|
|
109
|
+
if (!rows.length) return null;
|
|
110
|
+
const why = (row) => row.reason === "capability-absent" ? `package ${row.recorded.package} no longer provides it` : `package ${row.recorded.package} is no longer locked`;
|
|
111
|
+
return `${rows.length} package module(s) cannot move in place (${rows.map((row) => `${row.module}: ${why(row)}`).join("; ")}); an upgrade keeps them as they are, so respawn this instance to move it onto the lock`;
|
|
112
|
+
}
|
package/lib/worktree-hooks.mjs
CHANGED
|
@@ -15,11 +15,13 @@
|
|
|
15
15
|
* `warning` is read, and `env` is a contract error (as at retire).
|
|
16
16
|
* The timeout is fixed (WORKTREE_HOOK_TIMEOUT_MS). OATS_TEST_WORKTREE_HOOK_TIMEOUT_MS
|
|
17
17
|
* is a test seam, not a setting. */
|
|
18
|
-
import { spawn as spawnProcess, execFileSync
|
|
19
|
-
import { closeSync,
|
|
20
|
-
import { dirname,
|
|
18
|
+
import { spawn as spawnProcess, execFileSync } from "node:child_process";
|
|
19
|
+
import { closeSync, fchmodSync, mkdirSync, openSync, realpathSync, writeSync } from "node:fs";
|
|
20
|
+
import { dirname, join } from "node:path";
|
|
21
21
|
import { terminateGroup, watchGroup, TERM_GRACE_MS } from "./process-group.mjs";
|
|
22
|
-
import {
|
|
22
|
+
import { isStartToken, processLiveness, processStart, processStartToken } from "../packages/record/lib/process-identity.mjs";
|
|
23
|
+
|
|
24
|
+
export { PS_ENV, isStartToken, processLiveness, processStart, processStartToken, runPs } from "../packages/record/lib/process-identity.mjs";
|
|
23
25
|
|
|
24
26
|
export const WORKTREE_HOOK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
25
27
|
/** The fixed timeout, or the test seam's value (a positive integer of milliseconds). */
|
|
@@ -34,183 +36,12 @@ const SIGNAL_NUMBERS = { SIGHUP: 1, SIGINT: 2, SIGTERM: 15 };
|
|
|
34
36
|
/** The exit status of a process ended by `signal`: 128 + its number. */
|
|
35
37
|
export const interruptExitStatus = (signal) => 128 + (SIGNAL_NUMBERS[signal] ?? 15);
|
|
36
38
|
|
|
37
|
-
// ---------- process identity: a pid is verified by its start time ----------
|
|
38
|
-
|
|
39
|
-
/** Where a start time is read: /proc when this host has procfs, else `ps`. The test seam
|
|
40
|
-
* OATS_TEST_PROCESS_START_PS (not a setting; a launch configuration cannot set it) takes the `ps`
|
|
41
|
-
* path on any host: `1` runs the system `ps`, an absolute path runs that file as `ps`, and any
|
|
42
|
-
* other value reads no start at all (psProgram). */
|
|
43
|
-
const readsProc = () => process.env.OATS_TEST_PROCESS_START_PS === undefined && existsSync("/proc/self/stat");
|
|
44
|
-
/** `ps` runs with a fixed environment, nothing inherited (runPs). Its PATH is the system directories only (SYSTEM_TOOL_DIRS),
|
|
45
|
-
* never the caller's: what `ps` reports is the identity a claim is held or taken over on, so the
|
|
46
|
-
* caller's PATH must not choose the program, and a caller whose PATH holds no `ps` reads the same
|
|
47
|
-
* start as any other. `lstart` is local time in the locale's format, and two readers with another
|
|
48
|
-
* TZ or LANG would otherwise read one live process's start differently, and take it for another. */
|
|
49
|
-
export const PS_ENV = Object.freeze({ PATH: SYSTEM_TOOL_DIRS.join(":"), LC_ALL: "C", TZ: "UTC" });
|
|
50
|
-
/** The `ps` a start is read with → { file, name } | { reason }: the system one, or the file the
|
|
51
|
-
* test seam names by absolute path, run directly (no shell). A seam that names neither is never a
|
|
52
|
-
* fallback to /proc or to a `ps` found on PATH; nor is a named file that cannot be run (readStart). */
|
|
53
|
-
function psProgram() {
|
|
54
|
-
const seam = process.env.OATS_TEST_PROCESS_START_PS;
|
|
55
|
-
if (seam === undefined || seam === "1") return { file: "ps", name: "ps" };
|
|
56
|
-
if (isAbsolute(seam)) return { file: seam, name: `the ps OATS_TEST_PROCESS_START_PS names (${seam})` };
|
|
57
|
-
return { reason: `OATS_TEST_PROCESS_START_PS is ${JSON.stringify(seam)}, neither 1 nor an absolute path` };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** Whether `pid` exists, from the kernel itself: kill(pid, 0). ESRCH is gone; EPERM (another user's
|
|
61
|
-
* process) and success are "exists"; anything else is unknown. Never from how procfs or `ps`
|
|
62
|
-
* word an absence: macOS's `ps` answers a pid that does not exist with an error and exit 1, which
|
|
63
|
-
* says nothing a failing `ps` does not also say. */
|
|
64
|
-
function existence(pid) {
|
|
65
|
-
try { process.kill(pid, 0); return { state: "exists" }; }
|
|
66
|
-
catch (e) {
|
|
67
|
-
if (e.code === "ESRCH") return { state: "gone" };
|
|
68
|
-
if (e.code === "EPERM") return { state: "exists" };
|
|
69
|
-
return { state: "unknown", reason: `kill(${pid}, 0) failed (${e.code || e.message})` };
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Run the system `ps` once: `ps -o <column>= … <selection>`, each column without its header.
|
|
74
|
-
* → { out } — its stdout as it was written, when it exited 0 and answered something;
|
|
75
|
-
* → { reason } — it could not be run, was ended, failed or answered nothing: one line saying which.
|
|
76
|
-
* The one way the kernel calls `ps` (awebai/oats#870, #882): the program (psProgram), the fixed
|
|
77
|
-
* environment (PS_ENV), the time it is given and how its answer is classified are decided here.
|
|
78
|
-
* `selection` is the rest of its arguments (`["-p", "<pid>"]`, `["-ax"]`). The environment is
|
|
79
|
-
* PS_ENV whoever calls: what `ps` answers under it is the same for every reader. `path`, when
|
|
80
|
-
* given, is the PATH the program is found on, in place of PS_ENV's and of nothing else in it: an
|
|
81
|
-
* explicit argument, never read from the caller's environment here. The start reader passes
|
|
82
|
-
* none, so the caller's PATH never chooses the program an identity is read with (#878). */
|
|
83
|
-
export function runPs(columns, selection, { path } = {}) {
|
|
84
|
-
const ps = psProgram();
|
|
85
|
-
if (ps.reason) return { reason: ps.reason };
|
|
86
|
-
const argv = [...columns.flatMap((column) => ["-o", `${column}=`]), ...selection];
|
|
87
|
-
const r = spawnSync(ps.file, argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: path === undefined ? PS_ENV : { ...PS_ENV, PATH: path }, timeout: 10_000, maxBuffer: 4 * 1024 * 1024 });
|
|
88
|
-
if (r.error) return { reason: `${ps.name} could not be run (${r.error.code || r.error.message})` };
|
|
89
|
-
const out = String(r.stdout ?? ""), err = String(r.stderr ?? "").trim();
|
|
90
|
-
if (r.status === 0 && out.trim()) return { out };
|
|
91
|
-
return { reason: `ps ${argv.join(" ")} answered ${r.status === null ? `signal ${r.signal}` : `exit ${r.status}`}${err ? `: ${err.split("\n")[0]}` : out.trim() ? " with output" : " with no output"}` };
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
/** The start of a pid that exists, and whether it is a zombie (it exited, or was killed, and its
|
|
95
|
-
* parent has not reaped it): one read gives both.
|
|
96
|
-
* Linux: /proc/<pid>/stat, field 22 (clock ticks since boot) and field 3 (its state: `Z`, or `X`,
|
|
97
|
-
* a process being removed). Elsewhere `ps -o lstart= -o stat=` (runPs): the start, then a state
|
|
98
|
-
* that begins with `Z` (procps `Z`, macOS `Z` and `Z+`).
|
|
99
|
-
* → { state: "alive", token, zombie? } | { state: "unknown", reason }. `zombie` is set only when
|
|
100
|
-
* it is true. A state that cannot be read makes no zombie, and the start is what it was before
|
|
101
|
-
* there was a second column: whatever `ps` prints as a state (`?` included) is only ever cut off
|
|
102
|
-
* the start, and a `ps` that answers the start alone gives the start.
|
|
103
|
-
* The token is what released kernels recorded, byte for byte (`proc:<ticks>`, `ps:<lstart>`): a
|
|
104
|
-
* claim, a tree record or a marker written by an older kernel names its live holder by it, and a
|
|
105
|
-
* reader that gave that holder another token would take it for a reused pid, which is gone. */
|
|
106
|
-
function readStart(pid) {
|
|
107
|
-
if (readsProc()) {
|
|
108
|
-
let stat;
|
|
109
|
-
try { stat = readFileSync(`/proc/${pid}/stat`, "utf8"); }
|
|
110
|
-
catch (e) { return { state: "unknown", reason: `/proc/${pid}/stat could not be read (${e.code || e.message})` }; }
|
|
111
|
-
// comm (field 2) is in parentheses and may hold spaces or parentheses itself.
|
|
112
|
-
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
113
|
-
const start = fields[19]; // field 22 overall: after pid, comm and the 19 before it
|
|
114
|
-
if (!/^[0-9]+$/.test(start ?? "")) return { state: "unknown", reason: `/proc/${pid}/stat has no start time` };
|
|
115
|
-
return { state: "alive", token: `proc:${start}`, ...(fields[0] === "Z" || fields[0] === "X" ? { zombie: true } : {}) };
|
|
116
|
-
}
|
|
117
|
-
const r = runPs(["lstart", "stat"], ["-p", String(pid)]);
|
|
118
|
-
if (r.reason) return { state: "unknown", reason: r.reason };
|
|
119
|
-
// `Thu Jan 1 00:00:00 2026 Ss`: the state is the last field, one word whatever it says, and the
|
|
120
|
-
// start before it is taken whole, as `ps -o lstart=` alone prints it. A start ends with its year,
|
|
121
|
-
// so a last field of digits only is the start's own: that `ps` answered no state.
|
|
122
|
-
const out = r.out.trim();
|
|
123
|
-
const column = /^(.*\S)\s+(\S+)$/s.exec(out);
|
|
124
|
-
if (!column || /^[0-9]+$/.test(column[2])) return { state: "alive", token: `ps:${out}` };
|
|
125
|
-
return { state: "alive", token: `ps:${column[1]}`, ...(column[2].startsWith("Z") ? { zombie: true } : {}) };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** Whether `token` has a shape readStart writes: `proc:` and a count of clock ticks (64 bits: at
|
|
129
|
-
* most 20 digits), or `ps:` and a start as `ps -o lstart=` prints it under PS_ENV
|
|
130
|
-
* (`Thu Jan 1 00:00:00 2026`). The shape is said here, beside its writer, and nowhere else.
|
|
131
|
-
* It decides only what of a record may be SHOWN: a record is a file that others than its writer
|
|
132
|
-
* can write, and text that is not the kernel's enters an answer only as an id or a code. It is
|
|
133
|
-
* never a liveness decision: processLiveness compares the recorded string as it is, and a real
|
|
134
|
-
* token this does not know (a `ps` that prints a start otherwise) is shown as none, never read
|
|
135
|
-
* as gone. */
|
|
136
|
-
const START_TOKEN = /^(?:proc:[0-9]{1,20}|ps:[A-Z][a-z]{2} [A-Z][a-z]{2} [ 0-9][0-9] [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4})$/;
|
|
137
|
-
export const isStartToken = (token) => typeof token === "string" && START_TOKEN.test(token);
|
|
138
|
-
|
|
139
|
-
/** When `pid` started, read three ways apart (lessons/observation-must-not-harm-the-observer.md:
|
|
140
|
-
* "absent" never collapses with "unreadable"). One rule on every host: whether the pid exists is
|
|
141
|
-
* the kernel's answer (existence), and only a pid that exists has its start read.
|
|
142
|
-
* → { state: "alive", token, zombie? } — an opaque token for its start; two processes that held
|
|
143
|
-
* one pid at different times never share it, so a pid is only ever compared WITH its token;
|
|
144
|
-
* → { state: "gone" } — kill(pid, 0) answers ESRCH, before the read or (it exited in between)
|
|
145
|
-
* after a read that failed;
|
|
146
|
-
* → { state: "unknown", reason } — anything else: the pid exists and its start could not be read,
|
|
147
|
-
* or kill(pid, 0) failed otherwise. Every caller fails safe on it.
|
|
148
|
-
*
|
|
149
|
-
* This answers WHOSE the pid is, and a zombie still holds its pid and its start: it is "alive"
|
|
150
|
-
* here, with `zombie: true` as a fact beside it. That is what a recorded process group needs
|
|
151
|
-
* (terminateRecordedGroup): while its leader is a zombie the group's id cannot be reused, so a
|
|
152
|
-
* zombie leader with the recorded start is the best proof there is that the group is still that
|
|
153
|
-
* run's, and its members are ended. Whether a process can still ACT is another question, and
|
|
154
|
-
* processLiveness answers it (awebai/oats#870). */
|
|
155
|
-
export function processStart(pid) {
|
|
156
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
|
|
157
|
-
const before = existence(pid);
|
|
158
|
-
if (before.state !== "exists") return before;
|
|
159
|
-
const read = readStart(pid);
|
|
160
|
-
if (read.state === "alive") return read;
|
|
161
|
-
return existence(pid).state === "gone" ? { state: "gone" } : read;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/** The token of `processStart(pid)` when it is running, else null: for recording a process. A
|
|
165
|
-
* liveness decision never uses this, since null merges "gone" with "unknown" (processLiveness). */
|
|
166
|
-
export function processStartToken(pid) {
|
|
167
|
-
const s = processStart(pid);
|
|
168
|
-
return s.state === "alive" ? s.token : null;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
39
|
/** This process, as a record names it: { pid, processStart } (null when its start cannot be read;
|
|
172
40
|
* the callers that need it refuse then). */
|
|
173
41
|
export function selfIdentity() {
|
|
174
42
|
return { pid: process.pid, processStart: processStartToken(process.pid) };
|
|
175
43
|
}
|
|
176
44
|
|
|
177
|
-
/** Whether the COMMAND a record names (`{ pid, processStart }`) can still act:
|
|
178
|
-
* → { state: "alive" } — its pid runs with the recorded start;
|
|
179
|
-
* → { state: "gone", zombie? } — its pid does not run, or runs with another start (a reused pid),
|
|
180
|
-
* or is a zombie (`zombie: true`): it exited or was killed and its parent has not reaped it;
|
|
181
|
-
* → { state: "unknown", reason } — the start could not be read, or the record has none to
|
|
182
|
-
* compare while its pid runs. Every caller fails safe on it: nothing is taken over, rolled back,
|
|
183
|
-
* retired or signalled, and the refusal names the way out.
|
|
184
|
-
*
|
|
185
|
-
* A zombie is gone here (awebai/oats#870), though processStart still reads its pid and start. It
|
|
186
|
-
* will never run again, and a parent that never waits for it would otherwise keep its claim or
|
|
187
|
-
* marker refused for ever, with the advice to wait for it. Taking over from it is as safe as from
|
|
188
|
-
* a holder that was killed and reaped: a process's children are re-parented when it exits, not
|
|
189
|
-
* when it is reaped, so what a zombie leaves behind is exactly what that holder leaves: the steps
|
|
190
|
-
* it recorded, which each takeover ends (lib/claim.mjs `endHolderStep`; the hook group of a tree
|
|
191
|
-
* record or a spawn's marker), and for a retire its hook children (awebai/oats#865). The zombie
|
|
192
|
-
* adds nothing to that; it only delays the takeover until a reap that may never come.
|
|
193
|
-
* It is decided before the start is compared: a pid that is a zombie now is not a running
|
|
194
|
-
* holder whichever start the record names (it is that holder, or the pid was reused), and so
|
|
195
|
-
* neither when the record names none.
|
|
196
|
-
*
|
|
197
|
-
* WHOM THIS MAY BE ASKED ABOUT: the process of an `oats` command itself, which is what every
|
|
198
|
-
* record read with it names (a claim's holder, the adder of a tree record, a spawn's `inProgress`,
|
|
199
|
-
* a self-retire's completion). That is what makes "a zombie cannot act" true. On Linux a process
|
|
200
|
-
* whose main thread has exited while other threads run also reads `Z` in /proc/<pid>/stat, and
|
|
201
|
-
* it still acts; Node exits as a whole, so it does not arise for those records. Never ask this
|
|
202
|
-
* about a hook's or a harness's pid: for a process that is not the kernel's own, a `Z` does not
|
|
203
|
-
* say it is finished. (A recorded group's leader is asked through processStart, not through this.) */
|
|
204
|
-
export function processLiveness(record) {
|
|
205
|
-
const pid = record?.pid;
|
|
206
|
-
if (!Number.isSafeInteger(pid) || pid <= 0) return { state: "gone" };
|
|
207
|
-
const s = processStart(pid);
|
|
208
|
-
if (s.state !== "alive") return s;
|
|
209
|
-
if (s.zombie) return { state: "gone", zombie: true };
|
|
210
|
-
if (typeof record.processStart !== "string" || !record.processStart) return { state: "unknown", reason: `pid ${pid} runs, and the record names no start time to compare it with` };
|
|
211
|
-
return s.token === record.processStart ? { state: "alive" } : { state: "gone" };
|
|
212
|
-
}
|
|
213
|
-
|
|
214
45
|
/** Whether a record's process is verifiably the one still running (processLiveness "alive"). */
|
|
215
46
|
export const verifiedAlive = (record) => processLiveness(record).state === "alive";
|
|
216
47
|
|
package/lib/worktree.mjs
CHANGED
|
@@ -26,12 +26,14 @@ import { checkHolderByHand, ifItDoesNotEnd, lifecycleBusy, nothingAfter, oatsErr
|
|
|
26
26
|
import { appendEvent } from "./instance-events.mjs";
|
|
27
27
|
import { attachedToTree } from "./instance-lifecycle.mjs";
|
|
28
28
|
import { recordedTeams } from "./teams.mjs";
|
|
29
|
-
import { canonicalCloneKey, memberCloneOf } from "./
|
|
29
|
+
import { canonicalCloneKey, conventionCloneDir, memberCloneOf, parsedCloneKey } from "./member-clone.mjs";
|
|
30
|
+
import { shellWord } from "./shell-word.mjs";
|
|
30
31
|
import { loadLocal } from "./workspace.mjs";
|
|
31
32
|
import { GIT_FETCH_TIMEOUT_MS } from "./remote.mjs";
|
|
32
33
|
import { terminateGroup, watchGroup } from "./process-group.mjs";
|
|
33
34
|
import { CLAIM_WAIT_MS, acquireClaim, claimUnavailable, recordInClaim, releaseClaim, shownHolder } from "./claim.mjs";
|
|
34
35
|
import { writeThroughPrivateFile } from "./write-through-private-file.mjs";
|
|
36
|
+
import { NO_FILE_MONITOR, workTreeOverrides } from "./instance-git.mjs";
|
|
35
37
|
import {
|
|
36
38
|
cloneOfMember, instanceSoulDir, isCapturedHome, isWorkspaceHome, capturedHomeRefusal, preWorkspaceHome, lifecycleHookEnv,
|
|
37
39
|
refuseBesideRetire, retirePendingMarkerPath, stableSoulId, workspaceOf,
|
|
@@ -190,12 +192,16 @@ export function resolveTreeClone(meta, repo) {
|
|
|
190
192
|
} else if (isAbsolute(repo) || repo.startsWith(".") || repo.startsWith("~")) {
|
|
191
193
|
path = repo.startsWith("~") ? join(process.env.HOME ?? "", repo.slice(1)) : resolve(repo);
|
|
192
194
|
} else {
|
|
193
|
-
const
|
|
195
|
+
const parsed = parsedCloneKey(repo);
|
|
196
|
+
const key = parsed ?? canonicalCloneKey(repo);
|
|
194
197
|
const deployment = meta.workspace?.deployment;
|
|
195
198
|
if (typeof deployment !== "string" || !deployment) throw oatsError("E_CLONE_MISSING", `--repo ${repo}: this home records no deployment to look its clone up in; pass a clone path instead`);
|
|
196
199
|
let local = {};
|
|
197
200
|
try { local = loadLocal(deployment)?.local ?? {}; } catch (e) { throw Object.assign(oatsError(e.code || "E_CONFIG_BROKEN", e.message), { details: e.details }); }
|
|
198
|
-
|
|
201
|
+
let found;
|
|
202
|
+
try { found = memberCloneOf(deployment, local, key); }
|
|
203
|
+
catch (e) { if (parsed === null && e?.code === "E_CLONE_MISMATCH") throw notAKeyMismatch(repo, key, e); throw e; }
|
|
204
|
+
if (!found.path && parsed === null) throw Object.assign(oatsError("E_CLONE_MISSING", `--repo ${repo}: ${key} is not a repository key, and names no clone on this machine (nothing at its convention path ${conventionCloneDir(deployment, key)}); ${NOT_A_KEY_REMEDY}`), { details: { repoKey: key, deployment } });
|
|
199
205
|
if (!found.path) throw Object.assign(oatsError("E_CLONE_MISSING", `--repo ${repo}: this machine has no clone of ${key} — clone it to <deployment>/<member name> or name it in oats-local.yaml clones: { ${key}: <abs path> }; or pass a clone path`), { details: { repoKey: key, deployment } });
|
|
200
206
|
path = found.path;
|
|
201
207
|
member = key;
|
|
@@ -217,6 +223,29 @@ export function resolveTreeClone(meta, repo) {
|
|
|
217
223
|
if (!origin.ok || !origin.out.trim()) throw Object.assign(oatsError("E_CLONE_MISMATCH", `${clone} has no "origin" remote; a tree starts from origin's branch`), { details: { path: clone } });
|
|
218
224
|
return { clone, member, remote: scrubRemoteUrl(origin.out.trim()) };
|
|
219
225
|
}
|
|
226
|
+
|
|
227
|
+
const NOT_A_KEY_REMEDY = "pass a member's key (<host>/<org>/<repo>) or a clone path";
|
|
228
|
+
|
|
229
|
+
/** E_CLONE_MISMATCH for a `--repo` that is not a repository key (a member's name, `org/name`;
|
|
230
|
+
* oats-project/oats#1781), with the code and details memberCloneOf gave it. Such a string matches no
|
|
231
|
+
* remote, so the Git remedy that refusal ends with would repoint a good clone at a URL that does not
|
|
232
|
+
* exist. Instead: the clone's remotes whose key is `name` or ends in `/<name>` (`.git` aside) are the
|
|
233
|
+
* key to pass, and the clone's path is the other spelling that works. */
|
|
234
|
+
function notAKeyMismatch(repo, written, e) {
|
|
235
|
+
const { path, via, found } = e.details ?? {};
|
|
236
|
+
const bare = (k) => k.replace(/\.git$/i, "");
|
|
237
|
+
const name = bare(written);
|
|
238
|
+
const matches = [...new Set((Array.isArray(found) ? found : []).filter((k) => !k.startsWith("?/") && (bare(k) === name || bare(k).endsWith(`/${name}`))))];
|
|
239
|
+
const head = `--repo ${repo}: ${written} is not a repository key`;
|
|
240
|
+
let message;
|
|
241
|
+
if (matches.length) {
|
|
242
|
+
message = `${head}; the clone at ${path} (${via}) has ${matches.length > 1 ? "remotes" : "a remote"} ${matches.join(", ")}: pass ${matches.map((k) => `--repo ${shellWord(k)}`).join(" or ")}, or its path, --repo ${shellWord(path)}`;
|
|
243
|
+
} else {
|
|
244
|
+
const seen = !Array.isArray(found) ? e.message : `${via}: ${path} ${found.length ? `has remotes ${found.join(", ")}` : "has no remotes"}, none of them ${written}`;
|
|
245
|
+
message = `${head}, and matches no clone (${seen}); ${NOT_A_KEY_REMEDY}`;
|
|
246
|
+
}
|
|
247
|
+
return Object.assign(oatsError("E_CLONE_MISMATCH", message, e.provenance), { details: e.details });
|
|
248
|
+
}
|
|
220
249
|
const realpathOr = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
|
|
221
250
|
|
|
222
251
|
// ---------- the record ----------
|
|
@@ -343,7 +372,7 @@ const worktreeFields = (out, field) => out.split("\0").filter((f) => f.startsWit
|
|
|
343
372
|
* and a recovery never acts on a tree made after it read. A live adder's own record is left to it
|
|
344
373
|
* (others refuse it as busy), so the claim is not held while hooks run.
|
|
345
374
|
*
|
|
346
|
-
*
|
|
375
|
+
* A claim left by a process that died (SIGKILL in the middle of a
|
|
347
376
|
* recovery) is taken over, so a killed command can always be run again: the owner is named by
|
|
348
377
|
* pid AND start time (processLiveness), never by a pid alone, and a holder whose start cannot be
|
|
349
378
|
* read is never taken for gone. A claim held by a live process is
|
|
@@ -543,17 +572,25 @@ export async function worktreeAdd(homeArg, o = {}) {
|
|
|
543
572
|
return Object.assign(oatsError(code, `${message}${note}`), { details: { purpose, path: tree, rolledBack: rb.owed.length === 0, branchKept: rb.branchKept, ...(rb.branchKeptReason ? { branchKeptReason: rb.branchKeptReason } : {}), ...(rb.owed.length ? { owed: rb.owed } : {}), ...(warned.length ? { warnings: warned } : {}), ...details } });
|
|
544
573
|
};
|
|
545
574
|
|
|
546
|
-
|
|
575
|
+
// The checkouts below (worktree add, switch) write the tree's files: no filter driver the
|
|
576
|
+
// repository's configuration defines runs in either, nor the file monitor it names
|
|
577
|
+
// (lib/instance-git.mjs workTreeOverrides, read before each).
|
|
578
|
+
const addFilters = workTreeOverrides(["-C", clone], gitEnv());
|
|
579
|
+
if (!addFilters.ok) throw await fail("E_GIT_FAILED", `git worktree add failed in ${clone}: ${addFilters.err}`);
|
|
580
|
+
const add = await trackedGit([...addFilters.args, "-C", clone, "worktree", "add", "--detach", "--end-of-options", tree], { track });
|
|
547
581
|
if (!add.ok) throw await fail("E_GIT_FAILED", `git worktree add failed in ${clone}: ${firstLine(add.err) || "unknown error"}`);
|
|
548
582
|
const treeReal = realpathOr(tree);
|
|
549
|
-
|
|
583
|
+
// The fetch writes no file of the tree, and reads its index (for submodules): no file monitor.
|
|
584
|
+
const fetch = await trackedGit([...NO_FILE_MONITOR, "-C", tree, "fetch", "--refmap=", "--end-of-options", "origin", base], { track, timeout: worktreeFetchTimeoutMs() });
|
|
550
585
|
if (!fetch.ok) throw await fail("E_REMOTE_UNREADABLE", `cannot fetch ${base} from origin (${remote}): ${firstLine(fetch.err) || "timeout"}`, { base, remote });
|
|
551
586
|
const fetched = git(["-C", tree, "rev-parse", "--verify", "--quiet", "FETCH_HEAD^{commit}"]);
|
|
552
587
|
const oid = fetched.out.trim();
|
|
553
588
|
if (!fetched.ok || !/^[0-9a-f]{40,64}$/.test(oid)) throw await fail("E_BASE_UNKNOWN", `the fetch of ${base} from origin left no commit in FETCH_HEAD`, { base });
|
|
554
589
|
rec = { ...rec, baseOid: oid };
|
|
555
590
|
writeRecord(recPath, rec); // before the branch exists: a rollback deletes it only at this oid, and only if this add made it
|
|
556
|
-
const
|
|
591
|
+
const switchFilters = workTreeOverrides(["-C", tree], gitEnv());
|
|
592
|
+
if (!switchFilters.ok) throw await fail("E_GIT_FAILED", `git switch failed in ${tree}: ${switchFilters.err}`, { branch });
|
|
593
|
+
const sw = await trackedGit([...switchFilters.args, "-C", tree, "switch", "--no-guess", "-c", branch, "--end-of-options", oid], { track });
|
|
557
594
|
if (!sw.ok) {
|
|
558
595
|
// Another add created the branch first (the precheck passed for both): that is E_BRANCH_EXISTS; any other failure is git's.
|
|
559
596
|
const taken = git(["-C", clone, "rev-parse", "--verify", "--quiet", "--end-of-options", `refs/heads/${branch}`]).ok;
|
|
@@ -610,6 +647,20 @@ export async function worktreeAdd(homeArg, o = {}) {
|
|
|
610
647
|
|
|
611
648
|
const manualResidueRemedy = (tree, purpose) => `save any work and remove ${tree} by hand, then run \`oats worktree remove --purpose ${purpose}\` to drop its record`;
|
|
612
649
|
|
|
650
|
+
/** The `-c` arguments that keep a removal's Git from running a filter driver
|
|
651
|
+
* (`filter.<name>.clean`, `.process`) of the repository at `where` (`-C <dir>`), whose
|
|
652
|
+
* configuration whoever works in a tree can write: Git runs one when it compares a tree's file
|
|
653
|
+
* that carries the `filter` attribute, and the removal reads the tree's files as their bytes are
|
|
654
|
+
* (lib/instance-git.mjs filterOverrides, which says what its read covers and what it does not).
|
|
655
|
+
* They keep it from running the file monitor that configuration names too (workTreeOverrides).
|
|
656
|
+
* Throws `refused(why)` when the drivers cannot be read or one cannot be overridden: the caller
|
|
657
|
+
* then runs no Git on the tree, and never takes it for a clean one. */
|
|
658
|
+
function removalOverrides(where, refused) {
|
|
659
|
+
const filters = workTreeOverrides(where, gitEnv());
|
|
660
|
+
if (!filters.ok) throw refused(filters.err);
|
|
661
|
+
return filters.args;
|
|
662
|
+
}
|
|
663
|
+
|
|
613
664
|
/** Git removes its admin entry even when deleting ignored output fails. A later remove
|
|
614
665
|
* has no index to ask: compare the surviving files with the recorded branch in a private
|
|
615
666
|
* index, never the clone's index. Missing files are expected after partial deletion. */
|
|
@@ -627,10 +678,13 @@ function checkRemovalResidue(clone, tree, rec, refuse) {
|
|
|
627
678
|
} catch (e) { throw refuse(`the unregistered tree's .git file could not be checked (${e.message}); ${manualResidueRemedy(tree, rec.purpose)}`); }
|
|
628
679
|
if (!missingGitdir) throw refuse(`the unregistered tree has no .git file pointing at a missing gitdir; ${manualResidueRemedy(tree, rec.purpose)}`);
|
|
629
680
|
|
|
681
|
+
// The refresh and diff-files below read the surviving files: no filter driver the clone's
|
|
682
|
+
// configuration defines runs in them (removalOverrides).
|
|
683
|
+
const filters = removalOverrides(["-C", clone], (err) => refuse(`the surviving files could not be checked (${err})`));
|
|
630
684
|
const scratch = mkdtempSync(join(tmpdir(), "oats-worktree-remove-"));
|
|
631
685
|
try {
|
|
632
686
|
const env = { GIT_INDEX_FILE: join(scratch, "index") };
|
|
633
|
-
const args = ["-C", clone, "--work-tree", tree];
|
|
687
|
+
const args = [...filters, "-C", clone, "--work-tree", tree];
|
|
634
688
|
const read = git([...args, "read-tree", `refs/heads/${rec.branch}`], { env });
|
|
635
689
|
if (!read.ok) throw refuse(`the recorded branch ${rec.branch} could not be read (${firstLine(read.err)})`);
|
|
636
690
|
// read-tree has no stat cache. Refresh it before diff-files so identical survivors
|
|
@@ -731,9 +785,13 @@ export async function worktreeRemove(homeArg, o = {}) {
|
|
|
731
785
|
if (!registered()) {
|
|
732
786
|
checkRemovalResidue(clone, tree, rec, refuse);
|
|
733
787
|
} else {
|
|
734
|
-
|
|
788
|
+
// The status, and the clean check inside `git worktree remove` (a `git status` Git starts
|
|
789
|
+
// in the tree, which the `-c` settings reach), compare the tree's files: no filter driver
|
|
790
|
+
// the tree's configuration defines runs in either (removalOverrides).
|
|
791
|
+
const filters = removalOverrides(["-C", tree], (err) => refuse(`whether the tree is clean could not be read (${err})`));
|
|
792
|
+
const status = git([...filters, "-C", tree, "status", "--porcelain", "--ignore-submodules=none"]);
|
|
735
793
|
started = true;
|
|
736
|
-
const r = await trackedGit(["-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
|
|
794
|
+
const r = await trackedGit([...filters, "-C", clone, "worktree", "remove", "--end-of-options", tree], { track });
|
|
737
795
|
if (!r.ok && registered()) {
|
|
738
796
|
if (status.ok && status.out.trim()) throw Object.assign(oatsError("E_WORKTREE_DIRTY", `git refused to remove ${tree}: ${firstLine(r.err)}; commit and push its changes, or discard them, then retry (the record is kept)`), { details: { purpose, path: tree, git: r.err } });
|
|
739
797
|
throw refuse(`git could not finish removing the tree (${firstLine(r.err)})`, r.err);
|