@awebai/oats 0.60.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -19
- package/bin/oats.mjs +68 -21
- package/docs/capabilities.md +1 -1
- package/docs/configuration.md +9 -0
- package/docs/desktop-cli-api.md +28 -5
- package/docs/desktop.md +7 -0
- package/docs/execution-targets.md +49 -3
- package/docs/first-team.md +8 -0
- package/docs/implementation.md +2 -1
- package/docs/named-test-runs.md +382 -0
- package/docs/official-catalog.md +1 -1
- package/docs/packages.md +5 -5
- package/docs/release-notes/v0.61.0.md +155 -0
- package/docs/release-notes/v0.62.0.md +223 -0
- package/docs/tui.md +10 -4
- package/docs/upgrading.md +133 -11
- package/docs/workspaces.md +1 -1
- package/lib/core.mjs +2 -2
- package/lib/doctor-capture.mjs +35 -0
- package/lib/session-viewer.mjs +86 -7
- package/package-catalog.json +1 -1
- package/package.json +1 -1
- package/packages/client/cli-locator.mjs +2 -2
- package/packages/client/instance-presentation.mjs +10 -0
- package/packages/client/instance-tree.mjs +48 -6
- package/packages/record/README.md +87 -13
- package/packages/record/bin/capture-hook.mjs +8 -0
- package/packages/record/bin/capture.mjs +143 -124
- package/packages/record/bin/recall.mjs +8 -3
- package/packages/record/bin/setup.mjs +115 -225
- package/packages/record/bin/turn-record.mjs +2 -2
- package/packages/record/docs/capture-service.md +1443 -28
- package/packages/record/docs/capture-status.schema.json +429 -12
- package/packages/record/lib/capture-admission.mjs +82 -0
- package/packages/record/lib/capture-aw-unit.mjs +137 -0
- package/packages/record/lib/capture-aw.mjs +31 -12
- package/packages/record/lib/capture-budget.mjs +31 -0
- package/packages/record/lib/capture-cc.mjs +39 -6
- package/packages/record/lib/capture-cleanup-queue.mjs +135 -0
- package/packages/record/lib/capture-cleanup-work.mjs +77 -0
- package/packages/record/lib/capture-command-operation.mjs +37 -0
- package/packages/record/lib/capture-command-output.mjs +61 -0
- package/packages/record/lib/capture-command-worker.mjs +6 -0
- package/packages/record/lib/capture-command.mjs +48 -0
- package/packages/record/lib/capture-completion.mjs +152 -0
- package/packages/record/lib/capture-context.mjs +50 -0
- package/packages/record/lib/capture-default-roots.mjs +30 -0
- package/packages/record/lib/capture-discovery.mjs +114 -0
- package/packages/record/lib/capture-failures.mjs +45 -0
- package/packages/record/lib/capture-health-doctor.mjs +13 -0
- package/packages/record/lib/capture-health-installation.mjs +117 -0
- package/packages/record/lib/capture-health.mjs +116 -0
- package/packages/record/lib/capture-hook-ownership.mjs +58 -0
- package/packages/record/lib/capture-hook-runner.mjs +17 -0
- package/packages/record/lib/capture-hook.mjs +26 -0
- package/packages/record/lib/capture-index-inventory.mjs +205 -0
- package/packages/record/lib/capture-index-outcomes.mjs +113 -0
- package/packages/record/lib/capture-index-reset.mjs +109 -0
- package/packages/record/lib/capture-index-work.mjs +77 -0
- package/packages/record/lib/capture-issue-preparation.mjs +73 -0
- package/packages/record/lib/capture-issues.mjs +15 -2
- package/packages/record/lib/capture-lock.mjs +102 -16
- package/packages/record/lib/capture-native-unit.mjs +322 -0
- package/packages/record/lib/capture-pass.mjs +102 -0
- package/packages/record/lib/capture-recovery-snapshot.mjs +182 -0
- package/packages/record/lib/capture-retained-scratch.mjs +213 -0
- package/packages/record/lib/capture-retry.mjs +102 -0
- package/packages/record/lib/capture-run.mjs +125 -0
- package/packages/record/lib/capture-scratch.mjs +12 -3
- package/packages/record/lib/capture-service-definition.mjs +104 -0
- package/packages/record/lib/capture-service-install.mjs +362 -0
- package/packages/record/lib/capture-service-ownership.mjs +137 -0
- package/packages/record/lib/capture-service-runner.mjs +18 -0
- package/packages/record/lib/capture-small-snapshot.mjs +85 -0
- package/packages/record/lib/capture-source-discovery.mjs +319 -0
- package/packages/record/lib/capture-source-queue.mjs +199 -0
- package/packages/record/lib/capture-source-work.mjs +85 -0
- package/packages/record/lib/capture-state.mjs +16 -71
- package/packages/record/lib/capture-status.mjs +171 -0
- package/packages/record/lib/capture-supervisor.mjs +117 -0
- package/packages/record/lib/capture-watch.mjs +32 -0
- package/packages/record/lib/capture-work-session.mjs +238 -0
- package/packages/record/lib/capture-worker.mjs +58 -0
- package/packages/record/lib/derived-state.mjs +28 -15
- package/packages/record/lib/file-lines.mjs +22 -6
- package/packages/record/lib/formats.mjs +4 -3
- package/packages/record/lib/index-capture.mjs +97 -0
- package/packages/record/lib/index-db.mjs +3 -17
- package/packages/record/lib/index-reset.mjs +19 -0
- package/packages/record/lib/store.mjs +36 -11
- package/packages/record/lib/transcript-prefix.mjs +125 -0
- package/packages/tui/lib/client.mjs +2 -2
- package/packages/tui/lib/model.mjs +15 -5
- package/packages/tui/lib/views/palette.mjs +7 -3
- package/skills/oats-getting-started/SKILL.md +1 -1
- package/docs/macos-test-runs.md +0 -246
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Worker-only run accounting. The status FILE is published history; this small
|
|
2
|
+
// derived row holds counters joined to committed work while a pass is running.
|
|
3
|
+
// A stale cache row cannot replace a finished file receipt or a different run.
|
|
4
|
+
import { CAPTURE_POLICY } from "./capture-budget.mjs";
|
|
5
|
+
import { readIssueBacklog } from "./capture-issues.mjs";
|
|
6
|
+
import { CAPTURE_COUNT_FIELDS, captureReclaimedLock, emptyCaptureCounts, emptyCaptureStatus, readCaptureStatus, persistCaptureStatus } from "./capture-status.mjs";
|
|
7
|
+
|
|
8
|
+
const reasons = new Set(["deadline", "rss", "heap", "interrupted", "input", "io"]);
|
|
9
|
+
const messages = Object.freeze({ deadline: "Capture worker exceeded its admitted time allowance.",
|
|
10
|
+
rss: "Capture worker exceeded its sampled memory allowance.", heap: "Capture worker aborted at its heap limit.",
|
|
11
|
+
interrupted: "Capture execution ended before its run receipt was finalized.",
|
|
12
|
+
input: "Capture inputs remain pending, set aside or failed.", io: "Capture could not complete an operational step." });
|
|
13
|
+
const summarize = run => Object.fromEntries(["id", "trigger", "pid", "startedAt", "finishedAt", "counts", "peakRssBytes"].map(key => [key, structuredClone(run[key])]));
|
|
14
|
+
const failureSummary = (run, reason, at) => ({ ...summarize({ ...run, finishedAt: at }), reason,
|
|
15
|
+
message: messages[reason] + " Counters report only durably confirmed unit accounting, not all physical journal writes; zero turnsAppended does not prove that no append reached disk." });
|
|
16
|
+
const maximumPeak = (a, b) => a === null && b === null ? null : Math.max(a ?? 0, b ?? 0);
|
|
17
|
+
|
|
18
|
+
export class CaptureRun {
|
|
19
|
+
constructor(root, state, { id, trigger = "manual", pid = process.pid, reclaimedLock = null,
|
|
20
|
+
previousFailure = null, currentFailure = null, clock = () => new Date().toISOString() } = {}) {
|
|
21
|
+
if (state.depth) throw new Error("capture run starts outside processing transactions");
|
|
22
|
+
if (previousFailure !== null && !reasons.has(previousFailure)) throw new Error("invalid prior capture failure");
|
|
23
|
+
if (currentFailure !== null && (currentFailure?.id !== id || !reasons.has(currentFailure.reason)))
|
|
24
|
+
throw new Error("invalid current capture failure");
|
|
25
|
+
this.root = root; this.state = state; this.clock = clock;
|
|
26
|
+
const at = clock(), backlog = readIssueBacklog(state.db, { pending: true });
|
|
27
|
+
const prior = readCaptureStatus(root) ?? emptyCaptureStatus(backlog), cached = state.get("capture-run", "current");
|
|
28
|
+
if (prior.lastRun?.id === id && prior.lastRun.outcome !== "running") throw new Error("capture run identity already finished");
|
|
29
|
+
this.history = { policy: { ...CAPTURE_POLICY }, lastSuccess: prior.lastSuccess,
|
|
30
|
+
lastFailure: prior.lastFailure, lastProgressAt: prior.lastProgressAt };
|
|
31
|
+
let run;
|
|
32
|
+
if (prior.lastRun?.id === id && prior.lastRun.outcome === "running") {
|
|
33
|
+
// Only the same unfinished, published run may reuse derived counters.
|
|
34
|
+
// Losing its cache cannot promote that run to complete: remember the
|
|
35
|
+
// interruption, then allow independent/rebuild work to progress.
|
|
36
|
+
run = cached?.run?.id === id ? cached.run : prior.lastRun;
|
|
37
|
+
run = { ...run, peakRssBytes: maximumPeak(run.peakRssBytes, prior.lastRun.peakRssBytes) };
|
|
38
|
+
this.history.lastProgressAt = cached?.run?.id === id ? cached.progressAt : prior.lastProgressAt;
|
|
39
|
+
if (!cached || cached.run?.id !== id) previousFailure ??= "interrupted";
|
|
40
|
+
if (previousFailure) this.history.lastFailure = failureSummary(run, previousFailure, at);
|
|
41
|
+
run = { ...run, pid };
|
|
42
|
+
} else {
|
|
43
|
+
if (prior.lastRun?.outcome === "running") {
|
|
44
|
+
const abandoned = cached?.run?.id === prior.lastRun.id ? cached.run : prior.lastRun;
|
|
45
|
+
abandoned.peakRssBytes = maximumPeak(abandoned.peakRssBytes, prior.lastRun.peakRssBytes);
|
|
46
|
+
this.history.lastFailure = failureSummary(abandoned, previousFailure ?? "interrupted", at);
|
|
47
|
+
if (cached?.run?.id === prior.lastRun.id) this.history.lastProgressAt = cached.progressAt;
|
|
48
|
+
}
|
|
49
|
+
run = { id, trigger, pid, startedAt: at, finishedAt: null, outcome: "running", reason: null,
|
|
50
|
+
counts: emptyCaptureCounts(), peakRssBytes: null, reclaimedLock: captureReclaimedLock(reclaimedLock) };
|
|
51
|
+
}
|
|
52
|
+
// Supervisor evidence is explicitly bound to this pass, even if its first
|
|
53
|
+
// child died before publishing a receipt. It must not be attributed to an
|
|
54
|
+
// older abandoned receipt (whose failure alone cannot poison a new pass).
|
|
55
|
+
if (currentFailure) this.history.lastFailure = failureSummary(run, currentFailure.reason, at);
|
|
56
|
+
this.id = id; this.peakRssBytes = run.peakRssBytes; this.finished = false;
|
|
57
|
+
// Publish initial identity BEFORE any processing or new counter-cache
|
|
58
|
+
// initialization. A death here leaves an honest unfinished receipt; a
|
|
59
|
+
// cache leftover from an older pass is never mistaken for this new run.
|
|
60
|
+
persistCaptureStatus(root, { schemaVersion: 1, ...this.history, lastRun: run, backlog });
|
|
61
|
+
state.transaction(() => state.set("capture-run", "current", { run, progressAt: this.history.lastProgressAt }));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
current() {
|
|
65
|
+
if (this.finished) throw new Error("capture run already finalized");
|
|
66
|
+
const row = this.state.get("capture-run", "current");
|
|
67
|
+
if (row?.run?.id !== this.id || row.run.outcome !== "running") throw new Error("capture run accounting changed");
|
|
68
|
+
return row;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Invoke in the processing commit, AFTER journal fsync / index commit. These
|
|
72
|
+
// are confirmed committed-unit counts, not reconstructed guesses about an
|
|
73
|
+
// append whose worker died before its derived checkpoint/count commit.
|
|
74
|
+
record(delta = {}, { progress = false, peakRssBytes = null } = {}) {
|
|
75
|
+
if (!this.state.depth || typeof progress !== "boolean" || !delta || typeof delta !== "object" || Array.isArray(delta) ||
|
|
76
|
+
Object.keys(delta).some(key => !CAPTURE_COUNT_FIELDS.includes(key) || !Number.isSafeInteger(delta[key]) || delta[key] < 0) ||
|
|
77
|
+
peakRssBytes !== null && (!Number.isSafeInteger(peakRssBytes) || peakRssBytes < 0)) throw new Error("invalid committed capture accounting");
|
|
78
|
+
const row = this.current();
|
|
79
|
+
for (const [key, value] of Object.entries(delta)) {
|
|
80
|
+
if (!Number.isSafeInteger(row.run.counts[key] + value)) throw new Error("capture count overflow");
|
|
81
|
+
row.run.counts[key] += value;
|
|
82
|
+
}
|
|
83
|
+
if (peakRssBytes !== null) row.run.peakRssBytes = Math.max(row.run.peakRssBytes ?? 0, peakRssBytes);
|
|
84
|
+
if (progress) row.progressAt = this.clock();
|
|
85
|
+
this.state.set("capture-run", "current", row);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
snapshot({ pending = true, peakRssBytes = null } = {}) {
|
|
89
|
+
if (this.state.depth) throw new Error("capture status cannot publish uncommitted progress");
|
|
90
|
+
const row = this.current();
|
|
91
|
+
if (peakRssBytes !== null) {
|
|
92
|
+
if (!Number.isSafeInteger(peakRssBytes) || peakRssBytes < 0) throw new Error("invalid capture RSS sample");
|
|
93
|
+
this.peakRssBytes = maximumPeak(this.peakRssBytes, peakRssBytes);
|
|
94
|
+
}
|
|
95
|
+
this.peakRssBytes = maximumPeak(this.peakRssBytes, row.run.peakRssBytes);
|
|
96
|
+
row.run.peakRssBytes = this.peakRssBytes;
|
|
97
|
+
this.history.lastProgressAt = row.progressAt;
|
|
98
|
+
return { schemaVersion: 1, ...this.history, lastRun: row.run, backlog: readIssueBacklog(this.state.db, { pending }) };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
publish(options) {
|
|
102
|
+
return persistCaptureStatus(this.root, this.snapshot(options));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
finish({ outcome, reason = null, pending = false, peakRssBytes = null } = {}) {
|
|
106
|
+
if (!["complete", "partial", "failed"].includes(outcome) || reason !== null && !reasons.has(reason) ||
|
|
107
|
+
outcome === "complete" && reason !== null || outcome === "failed" && reason === null) throw new Error("invalid capture run outcome");
|
|
108
|
+
const snapshot = this.snapshot({ pending, peakRssBytes }), at = this.clock();
|
|
109
|
+
// A failure earlier in THIS pass survives later healthy work. Older
|
|
110
|
+
// historical failures are retained but do not forbid a new full success.
|
|
111
|
+
if (snapshot.lastFailure?.id === this.id) { outcome = "failed"; reason = snapshot.lastFailure.reason; }
|
|
112
|
+
if (outcome === "complete" && (snapshot.backlog.pending || snapshot.lastRun.counts.inputsPending ||
|
|
113
|
+
snapshot.lastRun.counts.inputsSetAside || snapshot.lastRun.counts.inputsFailed)) {
|
|
114
|
+
outcome = "partial"; reason = "input";
|
|
115
|
+
}
|
|
116
|
+
snapshot.lastRun = { ...snapshot.lastRun, finishedAt: at, outcome, reason };
|
|
117
|
+
if (outcome === "complete") snapshot.lastSuccess = summarize(snapshot.lastRun);
|
|
118
|
+
if (outcome === "failed") snapshot.lastFailure = failureSummary(snapshot.lastRun, reason, at);
|
|
119
|
+
// No second DB commit is needed for completion. The atomic file is the
|
|
120
|
+
// published receipt; the next run ignores this run's stale counter cache.
|
|
121
|
+
const result = persistCaptureStatus(this.root, snapshot);
|
|
122
|
+
this.finished = true;
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Private same-volume scratch for synchronous capture/receipt work.
|
|
2
|
-
// are never transferred to subprocesses.
|
|
1
|
+
// Private same-volume scratch for synchronous capture/receipt work. These
|
|
2
|
+
// per-call allocations are never transferred to subprocesses. Cleanup reclaims only proven
|
|
3
3
|
// dead local owners; an incomplete marker or reused PID remains conservative.
|
|
4
4
|
import { closeSync, constants, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, opendirSync, readSync, rmSync, rmdirSync, statSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { randomBytes } from "node:crypto";
|
|
@@ -88,8 +88,12 @@ export function cleanupCaptureScratch(root, lock, { liveness = localLiveness } =
|
|
|
88
88
|
const entries = opendirSync(base.path); let removed = 0;
|
|
89
89
|
try {
|
|
90
90
|
for (let entry; (entry = entries.readSync()) !== null;) {
|
|
91
|
-
const match = /^(snapshot|receipt)-[A-Za-z0-9]{6}$/.exec(entry.name);
|
|
91
|
+
const match = /^(snapshot|receipt|recovery)-[A-Za-z0-9]{6}$/.exec(entry.name);
|
|
92
92
|
if (!match || !entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
93
|
+
// Retained command jobs cross worker lifetimes intentionally. This
|
|
94
|
+
// ordinary scavenger has no durable job reference and therefore cannot
|
|
95
|
+
// authorize removal, even when the previous allocator is proven dead.
|
|
96
|
+
if (match[1] === "recovery") continue;
|
|
93
97
|
const path = join(base.path, entry.name); let stat;
|
|
94
98
|
try { stat = directory(path); } catch { continue; }
|
|
95
99
|
const candidate = marker(path), value = candidate?.value;
|
|
@@ -109,3 +113,8 @@ export function cleanupCaptureScratch(root, lock, { liveness = localLiveness } =
|
|
|
109
113
|
} finally { entries.closeSync(); }
|
|
110
114
|
return removed;
|
|
111
115
|
}
|
|
116
|
+
|
|
117
|
+
// Package-private filesystem checks shared with retained command allocations.
|
|
118
|
+
// They do not grant adoption or cleanup authority on their own.
|
|
119
|
+
export { privateRoot as captureScratchRoot, directory as captureScratchDirectory,
|
|
120
|
+
marker as readCaptureScratchMarker, sameMarker as sameCaptureScratchMarker };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Private finite-service request and pure manager definitions. Rendering grants
|
|
2
|
+
// no ownership, replacement or activation authority; setup must preflight those
|
|
3
|
+
// independently before it writes any definition or invokes a manager.
|
|
4
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { captureCommandOptions } from "./capture-command.mjs";
|
|
7
|
+
import { CAPTURE_POLICY } from "./capture-budget.mjs";
|
|
8
|
+
|
|
9
|
+
export const captureServiceLabel = "ai.aweb.turn-record-capture";
|
|
10
|
+
export const captureServiceUnit = "turn-record-capture.service";
|
|
11
|
+
export const captureServiceTimer = "turn-record-capture.timer";
|
|
12
|
+
// Setup's private record, under the record root, that it started activating
|
|
13
|
+
// the service and has not verified it: a rerun tells its own unfinished step
|
|
14
|
+
// from an operator's disable, and health reports the unverified schedule.
|
|
15
|
+
export const capturePendingActivationName = "capture-service-pending.json";
|
|
16
|
+
const marker = "oats-turn-record-service:1";
|
|
17
|
+
const entry = fileURLToPath(new URL("./capture-service-runner.mjs", import.meta.url));
|
|
18
|
+
|
|
19
|
+
export function captureServiceRequest(value) {
|
|
20
|
+
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
21
|
+
Object.keys(value).some(key => !["root", "owner", "plan"].includes(key)) ||
|
|
22
|
+
typeof value.root !== "string" || !value.root || value.root.includes("\0"))
|
|
23
|
+
throw new Error("invalid private capture service request");
|
|
24
|
+
const options = captureCommandOptions({ owner: value.owner, plan: value.plan,
|
|
25
|
+
trigger: "service", indexEnabled: true, retrySetAside: false });
|
|
26
|
+
if (options.plan.sources.length !== 4) throw new Error("capture service requires all sources");
|
|
27
|
+
return { root: resolve(options.plan.cwd, value.root), owner: options.owner, plan: options.plan };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function xml(value) {
|
|
31
|
+
// XML 1.0 forbids these characters even as numeric references. Refuse rather
|
|
32
|
+
// than persist a definition whose parsed arguments differ from the request.
|
|
33
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(value) ||
|
|
34
|
+
/[\ud800-\udfff]/u.test(value)) throw new Error("unrepresentable capture service XML value");
|
|
35
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
|
|
36
|
+
.replace(/\r/g, " ");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function systemd(value, executable = false) {
|
|
40
|
+
if (/[\u0000-\u001f\u007f]/u.test(value) || (executable && /['"\\]/u.test(value)))
|
|
41
|
+
throw new Error("unrepresentable capture service systemd value");
|
|
42
|
+
// Specifiers apply to every word; environment substitution applies to argv,
|
|
43
|
+
// not the executable. Always quote: JSON is one argument, never shell input.
|
|
44
|
+
let escaped = value.replace(/%/g, "%%").replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
45
|
+
if (!executable) escaped = escaped.replace(/\$/g, "$$$$");
|
|
46
|
+
return `"${escaped}"`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// The schedule is the fixed policy interval. intervalSeconds is an internal
|
|
50
|
+
// module seam for guarded real-manager tests only: no CLI, setting or caller
|
|
51
|
+
// passes another value, and its default is the policy's 900 seconds.
|
|
52
|
+
export function captureServiceIntervalText(intervalSeconds) {
|
|
53
|
+
return intervalSeconds % 60 ? `${intervalSeconds}s` : `${intervalSeconds / 60}min`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function captureServiceDefinition({ platform, node, request, intervalSeconds = CAPTURE_POLICY.intervalSeconds } = {}) {
|
|
57
|
+
if (!["darwin", "linux"].includes(platform) || typeof node !== "string" ||
|
|
58
|
+
!isAbsolute(node) || /[\u0000-\u001f\u007f\ud800-\udfff]/u.test(node) ||
|
|
59
|
+
!Number.isSafeInteger(intervalSeconds) || intervalSeconds < 1)
|
|
60
|
+
throw new Error("invalid capture service definition selection");
|
|
61
|
+
const selected = captureServiceRequest(request);
|
|
62
|
+
const argv = [node, entry, JSON.stringify(selected)];
|
|
63
|
+
if (platform === "darwin") {
|
|
64
|
+
const log = join(selected.plan.home, "Library", "Logs", "turn-record-capture.log");
|
|
65
|
+
const contents = `<?xml version="1.0" encoding="UTF-8"?>
|
|
66
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
67
|
+
<!-- ${marker} -->
|
|
68
|
+
<plist version="1.0"><dict>
|
|
69
|
+
<key>Label</key><string>${captureServiceLabel}</string>
|
|
70
|
+
<key>ProgramArguments</key><array>${argv.map(arg => `<string>${xml(arg)}</string>`).join("")}</array>
|
|
71
|
+
<key>RunAtLoad</key><true/>
|
|
72
|
+
<key>StartInterval</key><integer>${intervalSeconds}</integer>
|
|
73
|
+
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
74
|
+
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
75
|
+
</dict></plist>
|
|
76
|
+
`;
|
|
77
|
+
return { argv, files: [{ path: join(selected.plan.home, "Library", "LaunchAgents", `${captureServiceLabel}.plist`), contents }] };
|
|
78
|
+
}
|
|
79
|
+
const directory = join(selected.plan.home, ".config", "systemd", "user");
|
|
80
|
+
const service = `# ${marker}
|
|
81
|
+
[Unit]
|
|
82
|
+
Description=turn-record bounded capture pass
|
|
83
|
+
|
|
84
|
+
[Service]
|
|
85
|
+
Type=exec
|
|
86
|
+
ExecStart=${argv.map((arg, index) => systemd(arg, index === 0)).join(" ")}
|
|
87
|
+
MemoryMax=2G
|
|
88
|
+
RuntimeMaxSec=300
|
|
89
|
+
`;
|
|
90
|
+
const timer = `# ${marker}
|
|
91
|
+
[Unit]
|
|
92
|
+
Description=turn-record periodic capture
|
|
93
|
+
|
|
94
|
+
[Timer]
|
|
95
|
+
OnBootSec=1min
|
|
96
|
+
OnUnitActiveSec=${captureServiceIntervalText(intervalSeconds)}
|
|
97
|
+
Unit=${captureServiceUnit}
|
|
98
|
+
|
|
99
|
+
[Install]
|
|
100
|
+
WantedBy=timers.target
|
|
101
|
+
`;
|
|
102
|
+
return { argv, files: [{ path: join(directory, captureServiceUnit), contents: service },
|
|
103
|
+
{ path: join(directory, captureServiceTimer), contents: timer }] };
|
|
104
|
+
}
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// Setup's two-phase service migration. Preflight is read-only across every
|
|
2
|
+
// target; apply rechecks identities, backs up replacements, then mutates only
|
|
3
|
+
// the named label/units. Manager failure is partial apply, not atomic rollback.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
8
|
+
import { CAPTURE_POLICY } from "./capture-budget.mjs";
|
|
9
|
+
import { capturePendingActivationName, captureServiceDefinition, captureServiceLabel, captureServiceUnit, captureServiceTimer } from "./capture-service-definition.mjs";
|
|
10
|
+
import { captureServiceOwnership, captureServiceArgvOwnership } from "./capture-service-ownership.mjs";
|
|
11
|
+
|
|
12
|
+
export const serviceShellWord = value => /^[A-Za-z0-9_./:@%+,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
|
|
13
|
+
const identity = stat => [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeMs, stat.ctimeMs].join(":");
|
|
14
|
+
function parents(path) {
|
|
15
|
+
const records = [];
|
|
16
|
+
for (let directory = dirname(path); ; directory = dirname(directory)) {
|
|
17
|
+
let stat;
|
|
18
|
+
try { stat = fs.lstatSync(directory); }
|
|
19
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
20
|
+
if (stat) {
|
|
21
|
+
let target = null;
|
|
22
|
+
if (stat.isSymbolicLink()) {
|
|
23
|
+
try { target = fs.statSync(directory); }
|
|
24
|
+
catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
25
|
+
}
|
|
26
|
+
// Even a dangling ancestor link has an identity to retain. Its missing
|
|
27
|
+
// target must not turn a later retargeting into ordinary directory creation.
|
|
28
|
+
records.push([directory, `${stat.dev}:${stat.ino}:${stat.mode}`, stat.isSymbolicLink() ? fs.readlinkSync(directory) : null,
|
|
29
|
+
target ? `${target.dev}:${target.ino}:${target.mode}` : null]);
|
|
30
|
+
} else records.push([directory, null, null, null]);
|
|
31
|
+
if (dirname(directory) === directory) return records;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function captureSetupSnapshot(path) {
|
|
36
|
+
const ancestry = parents(path);
|
|
37
|
+
let stat;
|
|
38
|
+
try { stat = fs.lstatSync(path); }
|
|
39
|
+
catch (error) { if (error.code === "ENOENT") return { path, kind: "absent", parents: ancestry }; throw error; }
|
|
40
|
+
const before = identity(stat);
|
|
41
|
+
let bytes, link;
|
|
42
|
+
if (stat.isSymbolicLink()) link = fs.readlinkSync(path);
|
|
43
|
+
else {
|
|
44
|
+
if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error(`refusing nonregular or oversized setup target ${path}`);
|
|
45
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
46
|
+
try {
|
|
47
|
+
if (identity(fs.fstatSync(fd)) !== before) throw new Error(`setup target changed while opening ${path}`);
|
|
48
|
+
bytes = fs.readFileSync(fd);
|
|
49
|
+
if (identity(fs.fstatSync(fd)) !== before) throw new Error(`setup target changed while reading ${path}`);
|
|
50
|
+
} finally { fs.closeSync(fd); }
|
|
51
|
+
}
|
|
52
|
+
if (identity(fs.lstatSync(path)) !== before) throw new Error(`setup target changed while reading ${path}`);
|
|
53
|
+
return { path, kind: link === undefined ? "file" : "link", identity: before, bytes, link, parents: ancestry };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function recheckParents(snapshot, current, createdParents = new Map()) {
|
|
57
|
+
if (snapshot.parents.some(record => {
|
|
58
|
+
const expected = record[1] === null ? createdParents.get(record[0]) ?? record : record;
|
|
59
|
+
return !current.parents.some(now => JSON.stringify(now) === JSON.stringify(expected));
|
|
60
|
+
}))
|
|
61
|
+
throw new Error(`setup target parent changed since preflight: ${snapshot.path}; re-run setup`);
|
|
62
|
+
}
|
|
63
|
+
export function recheckCaptureSetup(snapshot, createdParents = new Map()) {
|
|
64
|
+
recheckParents(snapshot, { parents: parents(snapshot.path) }, createdParents);
|
|
65
|
+
const current = captureSetupSnapshot(snapshot.path);
|
|
66
|
+
recheckParents(snapshot, current, createdParents);
|
|
67
|
+
if (current.kind !== snapshot.kind || current.identity !== snapshot.identity || current.link !== snapshot.link ||
|
|
68
|
+
(snapshot.bytes && !snapshot.bytes.equals(current.bytes))) throw new Error(`setup target changed since preflight: ${snapshot.path}; re-run setup`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function writeCaptureSetup(snapshot, contents, createdParents = new Map()) {
|
|
72
|
+
recheckCaptureSetup(snapshot, createdParents);
|
|
73
|
+
// A missing ancestor is evidence, not permission to follow whatever appears
|
|
74
|
+
// there later. Create one level at a time, refusing EEXIST, and share only
|
|
75
|
+
// this apply's observed non-link directory identities with subsequent writes.
|
|
76
|
+
for (const record of [...snapshot.parents].reverse()) {
|
|
77
|
+
if (record[1] !== null || createdParents.has(record[0])) continue;
|
|
78
|
+
recheckCaptureSetup(snapshot, createdParents);
|
|
79
|
+
fs.mkdirSync(record[0]);
|
|
80
|
+
const stat = fs.lstatSync(record[0]);
|
|
81
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`setup created parent changed: ${record[0]}; re-run setup`);
|
|
82
|
+
createdParents.set(record[0], [record[0], `${stat.dev}:${stat.ino}:${stat.mode}`, null, null]);
|
|
83
|
+
}
|
|
84
|
+
recheckCaptureSetup(snapshot, createdParents);
|
|
85
|
+
const temporary = `${snapshot.path}.tmp-${randomUUID()}`;
|
|
86
|
+
let temporaryIdentity;
|
|
87
|
+
try {
|
|
88
|
+
fs.writeFileSync(temporary, contents, { flag: "wx", mode: 0o600 });
|
|
89
|
+
temporaryIdentity = identity(fs.lstatSync(temporary));
|
|
90
|
+
recheckCaptureSetup(snapshot, createdParents);
|
|
91
|
+
fs.renameSync(temporary, snapshot.path);
|
|
92
|
+
} finally {
|
|
93
|
+
// A refused ancestor replacement also revokes cleanup through that path.
|
|
94
|
+
// Leave the original scratch file rather than unlink an unrelated target.
|
|
95
|
+
let safe = false;
|
|
96
|
+
try {
|
|
97
|
+
recheckParents(snapshot, { parents: parents(snapshot.path) }, createdParents);
|
|
98
|
+
safe = temporaryIdentity !== undefined && identity(fs.lstatSync(temporary)) === temporaryIdentity;
|
|
99
|
+
} catch { /* absent scratch or changed ancestry: no pathname cleanup */ }
|
|
100
|
+
if (safe) fs.unlinkSync(temporary);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const detail = result => [result.error?.message, result.signal && `signal ${result.signal}`, result.stderr?.trim(),
|
|
105
|
+
result.status !== null && result.status !== undefined && `exit ${result.status}`].filter(Boolean).join("; ") || "no exit status returned";
|
|
106
|
+
const manager = (command, argv) => spawnSync(command, argv, { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024 });
|
|
107
|
+
function call(run, command, argv) {
|
|
108
|
+
const result = run(command, argv);
|
|
109
|
+
if (result.error || result.signal || result.status === null || result.status === undefined)
|
|
110
|
+
throw new Error(`${command} ${argv.map(serviceShellWord).join(" ")} failed (${detail(result)}); check manager availability/access and re-run setup`);
|
|
111
|
+
return result;
|
|
112
|
+
}
|
|
113
|
+
function requireOk(run, command, argv) {
|
|
114
|
+
const result = call(run, command, argv);
|
|
115
|
+
if (result.status !== 0) throw new Error(`${command} ${argv.map(serviceShellWord).join(" ")} failed (${detail(result)}); re-run setup to recover the named service`);
|
|
116
|
+
return result.stdout ?? "";
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function linuxState(run, unit) {
|
|
120
|
+
const output = requireOk(run, "systemctl", ["--user", "show", unit, "--no-pager", "--all",
|
|
121
|
+
"--property=LoadState,UnitFileState,ActiveState,SubState,FragmentPath,DropInPaths,NeedDaemonReload"]);
|
|
122
|
+
const fields = {};
|
|
123
|
+
for (const line of output.trim().split("\n")) {
|
|
124
|
+
const item = /^([A-Za-z]+)=(.*)$/.exec(line);
|
|
125
|
+
if (!item || Object.hasOwn(fields, item[1])) throw new Error(`indeterminate systemctl state for ${unit}`);
|
|
126
|
+
fields[item[1]] = item[2];
|
|
127
|
+
}
|
|
128
|
+
const keys = ["LoadState", "UnitFileState", "ActiveState", "SubState", "FragmentPath", "DropInPaths", "NeedDaemonReload"];
|
|
129
|
+
if (Object.keys(fields).length !== keys.length || keys.some(key => !Object.hasOwn(fields, key)) ||
|
|
130
|
+
!["loaded", "not-found", "masked"].includes(fields.LoadState) ||
|
|
131
|
+
!["", "enabled", "enabled-runtime", "disabled", "static", "masked", "masked-runtime"].includes(fields.UnitFileState) ||
|
|
132
|
+
!["active", "inactive", "failed", "activating", "deactivating"].includes(fields.ActiveState) || !["yes", "no"].includes(fields.NeedDaemonReload))
|
|
133
|
+
throw new Error(`indeterminate systemctl state for ${unit}`);
|
|
134
|
+
if (fields.DropInPaths) throw new Error(`unsupported manager drop-ins for ${unit}; inspect ${fields.DropInPaths}, or use --no-service`);
|
|
135
|
+
if (fields.LoadState === "not-found" && (fields.FragmentPath || fields.UnitFileState || fields.ActiveState !== "inactive"))
|
|
136
|
+
throw new Error(`inconsistent absent systemctl state for ${unit}`);
|
|
137
|
+
if (fields.LoadState === "loaded" && (!isAbsolute(fields.FragmentPath) || !fields.UnitFileState))
|
|
138
|
+
throw new Error(`indeterminate loaded systemctl identity for ${unit}`);
|
|
139
|
+
return fields;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function darwinState(run, domain, target) {
|
|
143
|
+
const disabledText = requireOk(run, "launchctl", ["print-disabled", domain]);
|
|
144
|
+
// Only the one disabled-services block, closed by a brace on its own line, is
|
|
145
|
+
// the override DB. Other blocks (login item associations, for one) carry other
|
|
146
|
+
// syntax and no disable state. launchd has printed both value spellings.
|
|
147
|
+
const blocks = [...disabledText.matchAll(/^[ \t]*disabled services = \{(?:[ \t]*\n([^]*?)^)?[ \t]*\}[ \t]*$/gm)];
|
|
148
|
+
if (blocks.length !== 1) throw new Error("indeterminate launchctl disabled state");
|
|
149
|
+
const disabled = new Map();
|
|
150
|
+
for (const line of (blocks[0][1] ?? "").split("\n").map(value => value.trim()).filter(Boolean)) {
|
|
151
|
+
const item = /^("(?:[^"\\]|\\.)*") => (true|false|disabled|enabled)\s*;?$/.exec(line);
|
|
152
|
+
if (!item) throw new Error("indeterminate launchctl disabled entry");
|
|
153
|
+
const label = JSON.parse(item[1]);
|
|
154
|
+
if (disabled.has(label)) throw new Error("duplicate launchctl disabled entry");
|
|
155
|
+
disabled.set(label, item[2] === "true" || item[2] === "disabled");
|
|
156
|
+
}
|
|
157
|
+
const result = call(run, "launchctl", ["print", target]);
|
|
158
|
+
if (result.status === 113 && /Could not find (?:specified )?service/.test(result.stderr ?? ""))
|
|
159
|
+
return { disabled: disabled.get(captureServiceLabel) === true, registered: false };
|
|
160
|
+
if (result.status !== 0) throw new Error(`launchctl print failed (${detail(result)}); cannot determine registration`);
|
|
161
|
+
const path = /^\s*path = (.+)$/m.exec(result.stdout ?? "")?.[1];
|
|
162
|
+
const block = /^\s*arguments = \{\n([^]*?)^\s*\}/m.exec(result.stdout ?? "");
|
|
163
|
+
if (!path || !block) throw new Error("indeterminate launchctl registered identity");
|
|
164
|
+
const argv = block[1].split("\n").map(line => line.trim()).filter(Boolean);
|
|
165
|
+
const interval = /^\s*run interval = (\d+) seconds\s*$/m.exec(result.stdout ?? "")?.[1];
|
|
166
|
+
return { disabled: disabled.get(captureServiceLabel) === true, registered: true, path, argv, interval: interval ? Number(interval) : null };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function inspect(plan) {
|
|
170
|
+
return plan.platform === "darwin" ? darwinState(plan.run, plan.domain, plan.target) :
|
|
171
|
+
{ service: linuxState(plan.run, captureServiceUnit), timer: linuxState(plan.run, captureServiceTimer) };
|
|
172
|
+
}
|
|
173
|
+
function stateIdentity(state, platform) {
|
|
174
|
+
if (platform === "darwin") return JSON.stringify(state);
|
|
175
|
+
// A normal pass may finish during setup. Its activity is not ownership or
|
|
176
|
+
// enablement, so don't mistake that transition for operator replacement.
|
|
177
|
+
return JSON.stringify(Object.values(state).map(({ LoadState, UnitFileState, FragmentPath, DropInPaths, NeedDaemonReload }) =>
|
|
178
|
+
({ LoadState, UnitFileState, FragmentPath, DropInPaths, NeedDaemonReload })));
|
|
179
|
+
}
|
|
180
|
+
// The recovery is the command the person runs (setupCommand: `oats setup` or
|
|
181
|
+
// `turn-record setup`), so a rerun selects its node the same way this run did.
|
|
182
|
+
function refuse(plan, code, found, replaceable = true) {
|
|
183
|
+
const recovery = `${plan.setupCommand} --owner ${serviceShellWord(plan.request.owner)} --root ${serviceShellWord(plan.request.root)}${plan.noHooks ? " --no-hooks" : ""}`;
|
|
184
|
+
const replacement = replaceable ? `replace only the named capture service with ${recovery} --replace-service` :
|
|
185
|
+
`--replace-service replaces only the named capture plist; remove that registration yourself, then re-run ${recovery}`;
|
|
186
|
+
throw Object.assign(new Error(`${code}: ${found}; ${replacement}, or keep it with ${recovery} --no-service`), { code });
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function preflightCaptureService({ platform, node, request, setupCommand, dry = false, replace = false,
|
|
190
|
+
noHooks = false, uid = process.getuid?.(), run = manager, log = console.log, intervalSeconds = CAPTURE_POLICY.intervalSeconds }) {
|
|
191
|
+
// intervalSeconds is the definition module's internal seam for guarded
|
|
192
|
+
// real-manager tests; ownership and verification expect what was rendered.
|
|
193
|
+
const definition = captureServiceDefinition({ platform, node, request, intervalSeconds }), schedule = { intervalSeconds };
|
|
194
|
+
// All targets are read before a refusal or mutation; no existsSync fallback
|
|
195
|
+
// may turn EACCES, a dangling link, or an unreadable target into absence.
|
|
196
|
+
const files = definition.files.map(file => {
|
|
197
|
+
const snapshot = captureSetupSnapshot(file.path), kind = file.path.endsWith(".plist") ? "plist" : file.path.endsWith(".timer") ? "timer" : "service";
|
|
198
|
+
const ownership = snapshot.kind === "absent" ? "absent" : platform === "linux" && snapshot.kind === "link" && snapshot.link === "/dev/null" ? "masked" : snapshot.kind === "file" &&
|
|
199
|
+
Buffer.from(snapshot.bytes.toString("utf8")).equals(snapshot.bytes) ? captureServiceOwnership(snapshot.bytes.toString("utf8"), kind, schedule) : "foreign";
|
|
200
|
+
return { ...file, snapshot, ownership, changed: snapshot.kind !== "file" || !snapshot.bytes.equals(Buffer.from(file.contents)) };
|
|
201
|
+
});
|
|
202
|
+
const plan = { platform, node, request: JSON.parse(definition.argv[2]), setupCommand, dry, replace, noHooks, run, log, files, intervalSeconds,
|
|
203
|
+
argv: definition.argv, domain: `gui/${uid}`, target: `gui/${uid}/${captureServiceLabel}` };
|
|
204
|
+
if (platform === "darwin" && !Number.isSafeInteger(uid)) throw new Error("cannot determine launchd user domain");
|
|
205
|
+
plan.state = dry ? null : inspect(plan);
|
|
206
|
+
// The marker counts only beside setup's own marked definitions; with no
|
|
207
|
+
// unit, or one without setup's mark, it is stale and authorizes nothing.
|
|
208
|
+
const markerPath = join(plan.request.root, capturePendingActivationName), marker = captureSetupSnapshot(markerPath);
|
|
209
|
+
if (!["absent", "file"].includes(marker.kind)) throw new Error(`cannot safely read the pending-activation marker ${markerPath}`);
|
|
210
|
+
plan.marker = marker;
|
|
211
|
+
plan.pending = marker.kind === "absent" ? null :
|
|
212
|
+
{ path: markerPath, snapshot: marker, stale: !files.every(file => file.ownership === "periodic") };
|
|
213
|
+
// A label registered from any other plist is not a named file: booting it
|
|
214
|
+
// out would not remove that file, which can load it again, and the file is
|
|
215
|
+
// never setup's to unlink. Explicit replacement does not reach it.
|
|
216
|
+
if (platform === "darwin" && plan.state?.registered && plan.state.path !== files[0].path)
|
|
217
|
+
refuse(plan, "E_CAPTURE_SERVICE_FOREIGN", `launchd registration ${captureServiceLabel} is loaded from ${JSON.stringify(plan.state.path)}, not from the named capture plist ${JSON.stringify(files[0].path)}`, false);
|
|
218
|
+
const foreign = files.filter(file => file.ownership === "foreign");
|
|
219
|
+
if (platform === "darwin" && plan.state?.registered && captureServiceArgvOwnership(plan.state.argv) === "foreign") foreign.push({ path: plan.target });
|
|
220
|
+
if (platform === "linux" && plan.state) for (const [i, state] of Object.values(plan.state).entries()) {
|
|
221
|
+
if (state.FragmentPath && state.FragmentPath !== files[i].path && state.LoadState !== "masked") foreign.push({ path: state.FragmentPath });
|
|
222
|
+
}
|
|
223
|
+
if (foreign.length && !replace) refuse(plan, "E_CAPTURE_SERVICE_FOREIGN", `unrecognized definition/registration at ${foreign.map(file => JSON.stringify(file.path)).join(", ")}`);
|
|
224
|
+
// Report what was observed, not a cause: a disabled unit file state alone
|
|
225
|
+
// does not tell an operator's disable from an incomplete earlier activation.
|
|
226
|
+
const disabled = [];
|
|
227
|
+
if (platform === "darwin") {
|
|
228
|
+
if (plan.state?.disabled) disabled.push(`launchctl print-disabled ${plan.domain} lists ${captureServiceLabel} as disabled (named plist ${files[0].snapshot.kind === "absent" ? "absent" : "present"}, label ${plan.state.registered ? "registered" : "not registered"})`);
|
|
229
|
+
} else {
|
|
230
|
+
for (const file of files) if (file.ownership === "masked") disabled.push(`${JSON.stringify(file.path)} links to /dev/null`);
|
|
231
|
+
// A loaded, unmasked disabled unit beside setup's live marker is setup's
|
|
232
|
+
// own unverified activation (a failed enable), not an operator's choice.
|
|
233
|
+
const ownPending = plan.pending && !plan.pending.stale;
|
|
234
|
+
if (plan.state) for (const [i, state] of Object.values(plan.state).entries()) if (state.LoadState === "masked" || state.UnitFileState.startsWith("masked") ||
|
|
235
|
+
(state.UnitFileState === "disabled" && (files[i].snapshot.kind !== "absent" || state.LoadState !== "not-found") && !(ownPending && state.LoadState === "loaded")))
|
|
236
|
+
disabled.push(`${[captureServiceUnit, captureServiceTimer][i]} LoadState=${state.LoadState} UnitFileState=${state.UnitFileState}`);
|
|
237
|
+
}
|
|
238
|
+
if (disabled.length && !replace) refuse(plan, "E_CAPTURE_SERVICE_DISABLED", `named capture service is not enabled: observed ${disabled.join(", ")}; setup enables it only when asked`);
|
|
239
|
+
plan.disabled = disabled.length > 0;
|
|
240
|
+
plan.changed = files.some(file => file.changed) || (platform === "darwin" && plan.state?.registered &&
|
|
241
|
+
(JSON.stringify(plan.state.argv) !== JSON.stringify(plan.argv) || plan.state.interval !== plan.intervalSeconds)) ||
|
|
242
|
+
(platform === "linux" && plan.state && (Object.values(plan.state).some(state => state.NeedDaemonReload === "yes") ||
|
|
243
|
+
["enabled", "enabled-runtime"].includes(plan.state.service.UnitFileState)));
|
|
244
|
+
return plan;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Apply has no atomic rollback. A failure names, on the thrown error's
|
|
248
|
+
// `applied`, every change made before it, as each was logged.
|
|
249
|
+
export function applyCaptureService(plan, createdParents = new Map()) {
|
|
250
|
+
const applied = [];
|
|
251
|
+
try { return applyCaptureServiceSteps(plan, createdParents, applied); }
|
|
252
|
+
catch (error) { if (applied.length) error.applied = [...applied]; throw error; }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function applyCaptureServiceSteps(plan, createdParents, applied) {
|
|
256
|
+
const { files, run, log } = plan;
|
|
257
|
+
const changed = text => { applied.push(text); log(`service: ${text}`); };
|
|
258
|
+
if (plan.dry) {
|
|
259
|
+
for (const file of files) log(`service: would ${file.snapshot.kind === "absent" ? "install" : file.changed ? "update" : "keep"} ${file.path}`);
|
|
260
|
+
if (plan.pending) log(`service: pending-activation marker ${plan.pending.path} is ${plan.pending.stale ? "stale; would remove it" : "present; would retry activation"}`);
|
|
261
|
+
log("service: manager registration/disabled state unexamined (--dry-run); no manager invoked");
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
const recheck = () => files.forEach(file => recheckCaptureSetup(file.snapshot, createdParents));
|
|
265
|
+
recheck();
|
|
266
|
+
const current = inspect(plan);
|
|
267
|
+
if (stateIdentity(current, plan.platform) !== stateIdentity(plan.state, plan.platform)) throw new Error("capture manager identity/enablement changed since preflight; re-run setup");
|
|
268
|
+
const markerPath = join(plan.request.root, capturePendingActivationName);
|
|
269
|
+
// The marker is written like every other setup target: against what
|
|
270
|
+
// preflight saw, never through a link or a replaced file.
|
|
271
|
+
let markerSnapshot = plan.marker;
|
|
272
|
+
if (plan.pending?.stale) {
|
|
273
|
+
recheckCaptureSetup(plan.pending.snapshot, createdParents); fs.rmSync(markerPath);
|
|
274
|
+
markerSnapshot = captureSetupSnapshot(markerPath);
|
|
275
|
+
changed(`removed stale pending-activation marker ${markerPath} (no setup-marked capture definition); it authorizes nothing`);
|
|
276
|
+
}
|
|
277
|
+
// Written before the first manager change or definition write, removed only
|
|
278
|
+
// after activation is verified: a failure in between leaves it for a rerun.
|
|
279
|
+
let marked = false;
|
|
280
|
+
const mark = () => {
|
|
281
|
+
if (marked) return;
|
|
282
|
+
writeCaptureSetup(markerSnapshot, JSON.stringify({ platform: plan.platform, startedAt: new Date().toISOString() }) + "\n", createdParents);
|
|
283
|
+
marked = true;
|
|
284
|
+
changed(`pending-activation marker written: ${markerPath}`);
|
|
285
|
+
};
|
|
286
|
+
const replaced = files.filter(file => file.changed && file.snapshot.kind !== "absent");
|
|
287
|
+
if (replaced.length) {
|
|
288
|
+
// Replacing definitions is activation work: the marker comes first, and its
|
|
289
|
+
// write creates a missing root as a recorded parent the backups then use.
|
|
290
|
+
mark();
|
|
291
|
+
const directory = join(plan.request.root, "service-backups", `${new Date().toISOString().replace(/:/g, "-")}-${randomUUID()}`);
|
|
292
|
+
fs.mkdirSync(dirname(directory), { recursive: true }); fs.mkdirSync(directory);
|
|
293
|
+
changed(`replacement backups at ${directory}`);
|
|
294
|
+
for (const file of replaced) {
|
|
295
|
+
recheck(); const path = join(directory, basename(file.path));
|
|
296
|
+
if (file.snapshot.kind === "link") fs.symlinkSync(file.snapshot.link, path);
|
|
297
|
+
else fs.writeFileSync(path, file.snapshot.bytes, { flag: "wx", mode: 0o600 });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
recheck();
|
|
301
|
+
const command = (name, args) => {
|
|
302
|
+
mark(); requireOk(run, name, args);
|
|
303
|
+
changed(`manager action completed: ${name} ${args.map(serviceShellWord).join(" ")}`);
|
|
304
|
+
};
|
|
305
|
+
const writeDefinition = file => {
|
|
306
|
+
mark(); writeCaptureSetup(file.snapshot, file.contents, createdParents);
|
|
307
|
+
changed(`definition written: ${file.path}`);
|
|
308
|
+
};
|
|
309
|
+
if (plan.platform === "darwin") {
|
|
310
|
+
if (plan.changed && current.registered) command("launchctl", ["bootout", plan.target]);
|
|
311
|
+
for (const file of files) if (file.changed) writeDefinition(file);
|
|
312
|
+
recheckParents(files[0].snapshot, { parents: parents(files[0].path) }, createdParents);
|
|
313
|
+
fs.mkdirSync(join(plan.request.plan.home, "Library", "Logs"), { recursive: true });
|
|
314
|
+
if (plan.disabled) command("launchctl", ["enable", plan.target]);
|
|
315
|
+
if (plan.changed || !current.registered) command("launchctl", ["bootstrap", plan.domain, files[0].path]);
|
|
316
|
+
const after = inspect(plan);
|
|
317
|
+
if (after.disabled || !after.registered || after.path !== files[0].path || after.interval !== plan.intervalSeconds || JSON.stringify(after.argv) !== JSON.stringify(plan.argv))
|
|
318
|
+
throw new Error("capture launchd registration verification failed; inspect the named job and re-run setup");
|
|
319
|
+
} else {
|
|
320
|
+
// Stop the timer first so it cannot launch the old service between writes.
|
|
321
|
+
// An unchanged enabled timer never receives stop/restart, preserving its pass.
|
|
322
|
+
if (plan.changed || plan.disabled) {
|
|
323
|
+
if (current.timer.LoadState !== "not-found") command("systemctl", ["--user", "stop", captureServiceTimer]);
|
|
324
|
+
if (current.service.LoadState !== "not-found") command("systemctl", ["--user", "stop", captureServiceUnit]);
|
|
325
|
+
if (["enabled", "enabled-runtime"].includes(current.service.UnitFileState)) command("systemctl",
|
|
326
|
+
["--user", ...(current.service.UnitFileState === "enabled-runtime" ? ["--runtime"] : []), "disable", captureServiceUnit]);
|
|
327
|
+
if (plan.disabled) for (const [unit, state] of [[captureServiceUnit, current.service], [captureServiceTimer, current.timer]]) {
|
|
328
|
+
if (state.LoadState === "masked" || state.UnitFileState.startsWith("masked")) command("systemctl",
|
|
329
|
+
["--user", ...(state.UnitFileState === "masked-runtime" ? ["--runtime"] : []), "unmask", unit]);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
// unmask may remove the exact named /dev/null links. Reconcile only that
|
|
333
|
+
// expected removal; any other replacement still refuses the file write.
|
|
334
|
+
for (const file of files) {
|
|
335
|
+
if (plan.disabled && file.snapshot.kind === "link" && file.snapshot.link === "/dev/null") {
|
|
336
|
+
const now = captureSetupSnapshot(file.path);
|
|
337
|
+
recheckParents(file.snapshot, now, createdParents);
|
|
338
|
+
if (now.kind === "absent") file.snapshot = now;
|
|
339
|
+
}
|
|
340
|
+
if (file.changed) writeDefinition(file);
|
|
341
|
+
}
|
|
342
|
+
if (plan.changed || plan.disabled || current.service.LoadState !== "loaded" || current.timer.LoadState !== "loaded") command("systemctl", ["--user", "daemon-reload"]);
|
|
343
|
+
if (plan.changed || plan.disabled || current.timer.UnitFileState !== "enabled" || current.timer.ActiveState !== "active")
|
|
344
|
+
command("systemctl", ["--user", "enable", "--now", captureServiceTimer]);
|
|
345
|
+
const after = inspect(plan);
|
|
346
|
+
if (after.service.LoadState !== "loaded" || after.timer.LoadState !== "loaded" ||
|
|
347
|
+
after.service.FragmentPath !== files[0].path || after.timer.FragmentPath !== files[1].path ||
|
|
348
|
+
after.timer.UnitFileState !== "enabled" || after.timer.ActiveState !== "active" ||
|
|
349
|
+
after.service.UnitFileState !== "static" || after.service.NeedDaemonReload !== "no" || after.timer.NeedDaemonReload !== "no")
|
|
350
|
+
throw new Error("capture timer/service verification failed; inspect the named units and re-run setup");
|
|
351
|
+
}
|
|
352
|
+
for (const file of files) {
|
|
353
|
+
const final = captureSetupSnapshot(file.path);
|
|
354
|
+
recheckParents(file.snapshot, final, createdParents);
|
|
355
|
+
if (final.kind !== "file" || !final.bytes.equals(Buffer.from(file.contents))) throw new Error(`capture definition changed during activation: ${file.path}; re-run setup`);
|
|
356
|
+
}
|
|
357
|
+
if (marked || plan.pending && !plan.pending.stale) {
|
|
358
|
+
fs.rmSync(markerPath, { force: true });
|
|
359
|
+
log(`service: activation verified; pending-activation marker removed: ${markerPath}`);
|
|
360
|
+
}
|
|
361
|
+
log(`service: periodic capture scheduled (every 15 minutes)${plan.changed ? "" : "; definitions already installed"}`);
|
|
362
|
+
}
|