faberun 0.23.0 → 0.23.1
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/package.json +1 -1
- package/src/campaign/chain.mjs +21 -8
- package/src/campaign/index.mjs +13 -1
- package/src/campaign/metrics.mjs +1 -1
- package/src/cli/campaign.mjs +3 -2
- package/src/engine/dispatch.mjs +23 -1
- package/src/engine/lifecycle.mjs +5 -6
- package/src/plan/proof-run.mjs +55 -12
- package/src/repo/worktree.mjs +4 -1
- package/src/run/lock.mjs +2 -12
- package/src/run/store.mjs +30 -2
- package/src/util.mjs +10 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "faberun",
|
|
3
|
-
"version": "0.23.
|
|
3
|
+
"version": "0.23.1",
|
|
4
4
|
"description": "Faberun is a development orchestration system that turns intent into verified software: harness- and model-agnostic, it keeps the intent, coordinates the work, verifies the result and decides what happens next.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/campaign/chain.mjs
CHANGED
|
@@ -32,7 +32,7 @@ import { execFileSync } from "node:child_process";
|
|
|
32
32
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
33
33
|
import { hostname, tmpdir } from "node:os";
|
|
34
34
|
import { dirname, join, relative, resolve } from "node:path";
|
|
35
|
-
import { assertContractManifestIntact, parkCampaign, promoteRunInCampaign } from "./index.mjs";
|
|
35
|
+
import { assertContractManifestIntact, parkCampaign, promoteRunInCampaign, recordOperatorCommand } from "./index.mjs";
|
|
36
36
|
import { readCampaign } from "./record.mjs";
|
|
37
37
|
import { validateContract } from "../contract/index.mjs";
|
|
38
38
|
import { defaultControllerIdentity, storedContractDigest, verifyControllerIdentity } from "../engine/run-identity.mjs";
|
|
@@ -386,6 +386,7 @@ function storedContractId(stored) {
|
|
|
386
386
|
* maxTicks?: number,
|
|
387
387
|
* coordination?: boolean,
|
|
388
388
|
* controllerIdentity?: ControllerIdentity,
|
|
389
|
+
* refreshController?: boolean,
|
|
389
390
|
* launch?: (contractPath: string, context: {baseRef: string|undefined, controllerIdentity: ControllerIdentity, runDir: string, contract: ValidatedContract}) => Promise<void>|void,
|
|
390
391
|
* validate?: (entry: CampaignContract, context: {repo: string|undefined, baseRef: string|undefined, contractPath: string}) => ValidatedContract,
|
|
391
392
|
* progress?: (runDir: string) => RunProgress,
|
|
@@ -551,13 +552,25 @@ export async function driveCampaignChain(campaignPath, options = {}) {
|
|
|
551
552
|
try {
|
|
552
553
|
verifyControllerIdentity(controllerIdentity);
|
|
553
554
|
} catch (error) {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
555
|
+
// A campaign whose contracts change faberun's own src/ changes the
|
|
556
|
+
// controller between launches (measured on evidence-you-can-recompute).
|
|
557
|
+
// Adopting the new snapshot is the operator's call, so it happens only
|
|
558
|
+
// under --refresh-controller and is recorded as an operator command.
|
|
559
|
+
if (options.refreshController === true && errorCode(error) === "controller_snapshot_changed") {
|
|
560
|
+
controllerIdentity = defaultControllerIdentity();
|
|
561
|
+
recordOperatorCommand(campaignPath, "campaign supervise --refresh-controller");
|
|
562
|
+
emit(`[campaign] controller snapshot refreshed · ${controllerIdentity.sha.slice(0, 12)}`);
|
|
563
|
+
} else {
|
|
564
|
+
return park({
|
|
565
|
+
code: errorCode(error) ?? "controller_snapshot_changed",
|
|
566
|
+
message: errorCode(error) === "controller_snapshot_changed"
|
|
567
|
+
? `${errorMessage(error)}: \`faberun campaign supervise ${readCampaign(campaignPath).id} --refresh-controller\``
|
|
568
|
+
: errorMessage(error),
|
|
569
|
+
contractPath: entry.path,
|
|
570
|
+
contractId: id,
|
|
571
|
+
runId: id,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
561
574
|
}
|
|
562
575
|
try {
|
|
563
576
|
await launch(entry.path, { baseRef, controllerIdentity, runDir, contract });
|
package/src/campaign/index.mjs
CHANGED
|
@@ -401,10 +401,22 @@ export function addContractToCampaign(campaignPath, contractPath, { at = new Dat
|
|
|
401
401
|
: campaign.contracts.map((existing, index) => (index === existingIndex ? entry : existing));
|
|
402
402
|
const updated = /** @type {Campaign} */ ({ ...campaign, contracts, updatedAt: at });
|
|
403
403
|
writeJsonAtomic(join(campaignPath, CAMPAIGN_FILE), updated);
|
|
404
|
-
|
|
404
|
+
recordOperatorCommand(campaignPath, "campaign add-contract", at);
|
|
405
405
|
return { campaign: updated, added: true };
|
|
406
406
|
}
|
|
407
407
|
|
|
408
|
+
/**
|
|
409
|
+
* The one writer of `operator.command` (docs/FIELD-OWNERSHIP.md): an operator
|
|
410
|
+
* command that changed campaign state, which `humanTouches` counts.
|
|
411
|
+
*
|
|
412
|
+
* @param {string} campaignPath
|
|
413
|
+
* @param {string} command
|
|
414
|
+
* @param {string} [at]
|
|
415
|
+
*/
|
|
416
|
+
export function recordOperatorCommand(campaignPath, command, at = new Date().toISOString()) {
|
|
417
|
+
appendJournal(campaignPath, { type: "operator.command", eventId: randomUUID(), at, command });
|
|
418
|
+
}
|
|
419
|
+
|
|
408
420
|
/**
|
|
409
421
|
* Replace a manifest entry -- matched by its current, recorded path -- with a
|
|
410
422
|
* freshly authored contract. Re-authoring a phase after a blocked or failed
|
package/src/campaign/metrics.mjs
CHANGED
|
@@ -311,7 +311,7 @@ function humanTouchesOf(journal, events) {
|
|
|
311
311
|
/** @param {JsonObject} entry @returns {boolean} */
|
|
312
312
|
function isRecordedJournalTouch(entry) {
|
|
313
313
|
return entry.type === "question.resolved"
|
|
314
|
-
|| (entry.type === "operator.command" &&
|
|
314
|
+
|| (entry.type === "operator.command" && ["campaign add-contract", "campaign supervise --refresh-controller"].includes(String(entry.command)));
|
|
315
315
|
}
|
|
316
316
|
|
|
317
317
|
/** @param {JsonObject} entry @returns {boolean} */
|
package/src/cli/campaign.mjs
CHANGED
|
@@ -84,7 +84,7 @@ const OPERATION_OPTIONS = {
|
|
|
84
84
|
},
|
|
85
85
|
close: { cwd: { type: "string" }, "event-id": { type: "string" } },
|
|
86
86
|
reledger: { cwd: { type: "string" } },
|
|
87
|
-
supervise: { cwd: { type: "string" }, "allow-main": { type: "boolean" } },
|
|
87
|
+
supervise: { cwd: { type: "string" }, "allow-main": { type: "boolean" }, "refresh-controller": { type: "boolean" } },
|
|
88
88
|
unpark: { cwd: { type: "string" }, force: { type: "boolean" }, "event-id": { type: "string" } },
|
|
89
89
|
"add-contract": { cwd: { type: "string" }, path: { type: "string" } },
|
|
90
90
|
"replace-contract": { cwd: { type: "string" }, path: { type: "string" }, replace: { type: "string" } },
|
|
@@ -94,7 +94,7 @@ const OPERATION_OPTIONS = {
|
|
|
94
94
|
ack: { cwd: { type: "string" }, "session-id": { type: "string" }, "event-id": { type: "string" } },
|
|
95
95
|
};
|
|
96
96
|
|
|
97
|
-
/** @typedef {{cwd?: string, goal?: string, contract?: string[], landBranch?: string, tool?: string, sessionId?: string, transcript?: string, format?: string, cursor?: string, since?: string, kind?: string, text?: string, runId?: string, supersedes?: string, decisionId?: string, questionId?: string, eventId?: string, noTranscript?: boolean, wake?: boolean, detach?: boolean, interval?: string, once?: boolean, allowMain?: boolean, force?: boolean, path?: string, replace?: string, phase?: string}} CliValues */
|
|
97
|
+
/** @typedef {{cwd?: string, goal?: string, contract?: string[], landBranch?: string, tool?: string, sessionId?: string, transcript?: string, format?: string, cursor?: string, since?: string, kind?: string, text?: string, runId?: string, supersedes?: string, decisionId?: string, questionId?: string, eventId?: string, noTranscript?: boolean, wake?: boolean, detach?: boolean, interval?: string, once?: boolean, allowMain?: boolean, refreshController?: boolean, force?: boolean, path?: string, replace?: string, phase?: string}} CliValues */
|
|
98
98
|
/** @typedef {import("../campaign/index.mjs").Campaign} Campaign */
|
|
99
99
|
|
|
100
100
|
/**
|
|
@@ -398,6 +398,7 @@ async function supervise(campaignId, values) {
|
|
|
398
398
|
const outcome = await driveCampaignChain(path, {
|
|
399
399
|
repo: cwd,
|
|
400
400
|
allowMain: values.allowMain === true,
|
|
401
|
+
refreshController: values.refreshController === true,
|
|
401
402
|
emit: (line) => process.stdout.write(`${line}\n`),
|
|
402
403
|
launch: async (contractPath, { baseRef, runDir }) => {
|
|
403
404
|
const child = detachSelf("run", contractPath, baseRef ? ["--base-ref", baseRef] : []);
|
package/src/engine/dispatch.mjs
CHANGED
|
@@ -50,7 +50,7 @@ import { transition, writeNode } from "./state.mjs";
|
|
|
50
50
|
* `dispatched`: a judge is running (or failed to start and the node is already
|
|
51
51
|
* marked failed).
|
|
52
52
|
*
|
|
53
|
-
* @typedef {{kind: "rejected", verdict: JudgeVerdict}|{kind: "settle", gate: JudgeVerdict}|{kind: "dispatched"}} JudgeRound
|
|
53
|
+
* @typedef {{kind: "rejected", verdict: JudgeVerdict}|{kind: "settle", gate: JudgeVerdict|null}|{kind: "dispatched"}} JudgeRound
|
|
54
54
|
*/
|
|
55
55
|
/** @typedef {import("./prompts.mjs").JudgeVerdict} JudgeVerdict */
|
|
56
56
|
|
|
@@ -439,6 +439,28 @@ export function startResultMaterialization(contract, node, state, runDir, runnin
|
|
|
439
439
|
transition(runDir, state, "failed", { phase: "worker", error: { code: "result_materialization_failed", message: errorMessage(error) } }, lock);
|
|
440
440
|
}
|
|
441
441
|
}
|
|
442
|
+
/**
|
|
443
|
+
* The mechanical half of the gate, for a node whose gate is disabled: its
|
|
444
|
+
* Definition of Done command and path proofs still run, and no judge is
|
|
445
|
+
* asked. Measured 2026-09-23 on evidence-you-can-recompute: every node carried
|
|
446
|
+
* `gate: false`, and not one of its declared proofs ran.
|
|
447
|
+
*
|
|
448
|
+
* @param {ValidatedContract} contract
|
|
449
|
+
* @param {ValidatedNode} node
|
|
450
|
+
* @param {NodeSnapshot} state
|
|
451
|
+
* @returns {Promise<JudgeRound>}
|
|
452
|
+
*/
|
|
453
|
+
export async function startMechanicalGate(contract, node, state) {
|
|
454
|
+
const { verdict, results } = await deterministicGate(
|
|
455
|
+
node,
|
|
456
|
+
attemptWorkspace(state) ?? contract.cwd,
|
|
457
|
+
false,
|
|
458
|
+
gateProofTimeoutMs(node, contract),
|
|
459
|
+
/** @type {import("../contract/index.mjs").VerificationState|null} */ (state.verification),
|
|
460
|
+
);
|
|
461
|
+
if (verdict.verdict === "fail") return { kind: "rejected", verdict };
|
|
462
|
+
return { kind: "settle", gate: results.length ? verdict : null };
|
|
463
|
+
}
|
|
442
464
|
/**
|
|
443
465
|
* Gate a completed worker: mechanical proofs gate first, the judge arbitrates
|
|
444
466
|
* only judgment items and is skipped when the review mode is `none` or no
|
package/src/engine/lifecycle.mjs
CHANGED
|
@@ -52,7 +52,7 @@ import {
|
|
|
52
52
|
workerResultPath,
|
|
53
53
|
} from "./result-file.mjs";
|
|
54
54
|
import { canReuseResultEvidence, checkResultMaterializationScope, checkWorkerScope, recordScopeFinding, sourceWorkerRuntime } from "./scope.mjs";
|
|
55
|
-
import { startJudge, startResultMaterialization } from "./dispatch.mjs";
|
|
55
|
+
import { startJudge, startMechanicalGate, startResultMaterialization } from "./dispatch.mjs";
|
|
56
56
|
import { raiseNodeAttention, settleDone } from "./settle.mjs";
|
|
57
57
|
import { applyRejection, applyVerificationFailure } from "./settle.mjs";
|
|
58
58
|
import { emitNodeAdvisories } from "./notify-queue.mjs";
|
|
@@ -587,11 +587,10 @@ export async function finalizeClosedJobs(contract, runDir, states, closed, lock,
|
|
|
587
587
|
continue;
|
|
588
588
|
}
|
|
589
589
|
if (job.scopeViolation) recordScopeFinding(runDir, state, lock);
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
else await settleDone(contract, job.node, state, runDir, lock, states, campaignPath, { phase: "complete", result: workerResult });
|
|
590
|
+
const round = job.node.gate.enabled
|
|
591
|
+
? await startJudge(contract, job.node, state, runDir, running, workerResult, lock, states, campaignPath)
|
|
592
|
+
: await startMechanicalGate(contract, job.node, state);
|
|
593
|
+
await applyJudgeRound(round, contract, job.node, state, runDir, running, lock, states, campaignPath, workerResult);
|
|
595
594
|
continue;
|
|
596
595
|
}
|
|
597
596
|
}
|
package/src/plan/proof-run.mjs
CHANGED
|
@@ -65,18 +65,60 @@ export const MEASURE_SIDE_EFFECT_ENV_KEYS = [
|
|
|
65
65
|
* @returns {{output: string, exitCode: number|null, truncated: boolean}}
|
|
66
66
|
*/
|
|
67
67
|
export function runShellCapture(cwd, command, probes = {}) {
|
|
68
|
+
const { output, exitCode, truncated } = runShellFull(cwd, command, probes);
|
|
69
|
+
const bytes = Buffer.from(output, "utf8");
|
|
70
|
+
return {
|
|
71
|
+
output: truncated ? bytes.subarray(0, MEASURE_OUTPUT_CAP_BYTES).toString("utf8") : output,
|
|
72
|
+
exitCode,
|
|
73
|
+
truncated,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The shell run behind `runShellCapture`, returning the whole output: a
|
|
79
|
+
* pinned-test check has to see every test the runner reported, and the
|
|
80
|
+
* matching line can sit far past the 4 KiB a measurement keeps.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} cwd
|
|
83
|
+
* @param {string} command
|
|
84
|
+
* @param {MeasureProbes} [probes]
|
|
85
|
+
* @returns {{output: string, exitCode: number|null, truncated: boolean}}
|
|
86
|
+
*/
|
|
87
|
+
function runShellFull(cwd, command, probes = {}) {
|
|
68
88
|
const run = probes.run ?? spawnSync;
|
|
69
89
|
const env = { ...process.env };
|
|
70
90
|
for (const key of MEASURE_SIDE_EFFECT_ENV_KEYS) delete env[key];
|
|
91
|
+
// A nested `node --test` that inherits NODE_TEST_CONTEXT stays a runner
|
|
92
|
+
// child and prints no result at all (measured 2026-09-21, AGENTS.md), so a
|
|
93
|
+
// proof run from inside a test runner would have nothing to show.
|
|
94
|
+
delete env.NODE_TEST_CONTEXT;
|
|
71
95
|
const result = run(command, { shell: true, cwd, timeout: MEASURE_TIMEOUT_MS, encoding: "utf8", env });
|
|
72
96
|
const combined = `${result.stdout ?? ""}${result.stderr ?? ""}`;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
97
|
+
return { output: combined, exitCode: result.status, truncated: Buffer.byteLength(combined, "utf8") > MEASURE_OUTPUT_CAP_BYTES };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** `--test-name-pattern` in a shell command, quoted or bare, `=` or space. */
|
|
101
|
+
const NAME_PATTERN_FLAG = /--test-name-pattern(?:=|\s+)(?:"([^"]*)"|'([^']*)'|(\S+))/u;
|
|
102
|
+
/** A passing test as the spec reporter (`✔ name (1ms)`) or TAP (`ok 1 - name`) prints it. */
|
|
103
|
+
const PASSING_TEST_LINE = /^\s*(?:\u2714\s+|ok \d+ - )(.+?)(?:\s+\(\d[\d.]*m?s\))?\s*$/gmu;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Whether a `node --test --test-name-pattern=<p>` proof ran a test named by
|
|
107
|
+
* its pattern. Node exits 0 when the pattern matches nothing, printing only
|
|
108
|
+
* the file, so the exit code alone cannot tell a proof from its absence.
|
|
109
|
+
* Returns null when the command carries no pattern.
|
|
110
|
+
*
|
|
111
|
+
* @param {string} command
|
|
112
|
+
* @param {string} output
|
|
113
|
+
* @returns {boolean|null}
|
|
114
|
+
*/
|
|
115
|
+
function patternMatchedATest(command, output) {
|
|
116
|
+
if (!/\bnode\b[^|;&]*--test\b/u.test(command)) return null;
|
|
117
|
+
const flag = NAME_PATTERN_FLAG.exec(command);
|
|
118
|
+
if (!flag) return null;
|
|
119
|
+
const pattern = new RegExp(flag[1] ?? flag[2] ?? flag[3], "u");
|
|
120
|
+
const plain = output.replace(/\u001b\[[0-9;]*m/gu, "");
|
|
121
|
+
return [...plain.matchAll(PASSING_TEST_LINE)].some((line) => pattern.test(line[1]) && !/\.m?[jt]s$/u.test(line[1].trim()));
|
|
80
122
|
}
|
|
81
123
|
|
|
82
124
|
/**
|
|
@@ -104,11 +146,12 @@ export function proveRequirements(cwd, requirements, probes = {}) {
|
|
|
104
146
|
const proof = requirement.proof;
|
|
105
147
|
if (!proof?.ref) continue;
|
|
106
148
|
if (proof.kind === "command") {
|
|
107
|
-
const { output, exitCode } =
|
|
108
|
-
const
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
149
|
+
const { output, exitCode } = runShellFull(cwd, proof.ref, probes);
|
|
150
|
+
const matched = exitCode === 0 ? patternMatchedATest(proof.ref, output) : null;
|
|
151
|
+
const detail = exitCode !== 0
|
|
152
|
+
? `exit ${exitCode ?? "no exit code (killed or never started)"}${output.trim() ? `: ${output.trim().slice(0, PROOF_DETAIL_CAP)}` : ""}`
|
|
153
|
+
: matched === false ? "exit 0, but its --test-name-pattern matched no test: the proof ran nothing" : "exit 0";
|
|
154
|
+
results.push({ requirementId: requirement.id, kind: "command", ref: proof.ref, pass: exitCode === 0 && matched !== false, detail });
|
|
112
155
|
continue;
|
|
113
156
|
}
|
|
114
157
|
if (proof.kind === "path") {
|
package/src/repo/worktree.mjs
CHANGED
|
@@ -384,7 +384,10 @@ export function sealAttempt({ repo, path, baseSha, runId, nodeId, attempt, exclu
|
|
|
384
384
|
// schedule it chose. The identity and signing overrides above are the
|
|
385
385
|
// same argument: this commit answers to the factory, not to the repo's
|
|
386
386
|
// conventions for human commits.
|
|
387
|
-
|
|
387
|
+
// Conventional, so a campaign branch passes a PR's commitlint check
|
|
388
|
+
// (measured 2026-09-23: every `faberun <run> <node> attempt N` seal was
|
|
389
|
+
// refused); the run id moves to the body to keep the header short.
|
|
390
|
+
"commit", "--no-verify", "-q", "-m", `chore(faberun): seal ${nodeId} attempt ${attempt}`, "-m", `run ${runId}`,
|
|
388
391
|
]);
|
|
389
392
|
}
|
|
390
393
|
const sha = gitHead(path);
|
package/src/run/lock.mjs
CHANGED
|
@@ -17,7 +17,7 @@ import { closeSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, rena
|
|
|
17
17
|
import { hostname } from "node:os";
|
|
18
18
|
import { join } from "node:path";
|
|
19
19
|
import { fsyncDirectory } from "./store.mjs";
|
|
20
|
-
import { errorCode } from "../util.mjs";
|
|
20
|
+
import { errorCode, sleepSync } from "../util.mjs";
|
|
21
21
|
|
|
22
22
|
const LOCK_FILE = "controller.lock";
|
|
23
23
|
const TAKEOVER_ATTEMPTS = 20;
|
|
@@ -84,7 +84,7 @@ export function processStartToken(pid) {
|
|
|
84
84
|
// and report nothing for a pid that is already alive. One short retry
|
|
85
85
|
// closes that window; a still-empty answer stays null.
|
|
86
86
|
if (!pidAlive(pid)) return null;
|
|
87
|
-
|
|
87
|
+
sleepSync(20);
|
|
88
88
|
const retried = psStartTime(pid);
|
|
89
89
|
return retried.length > 0 ? retried : null;
|
|
90
90
|
}
|
|
@@ -106,16 +106,6 @@ function psStartTime(pid) {
|
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
/**
|
|
110
|
-
* Block without a timer so the synchronous darwin retry above can wait out the
|
|
111
|
-
* spawn race. The duration is tiny and bounded, so blocking the loop is safe.
|
|
112
|
-
*
|
|
113
|
-
* @param {number} milliseconds
|
|
114
|
-
*/
|
|
115
|
-
function sleepMs(milliseconds) {
|
|
116
|
-
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
|
|
117
|
-
}
|
|
118
|
-
|
|
119
109
|
/** @param {number|null|undefined} pid @returns {boolean} */
|
|
120
110
|
export function pidAlive(pid) {
|
|
121
111
|
if (!Number.isInteger(pid) || /** @type {number} */ (pid) <= 0) return false;
|
package/src/run/store.mjs
CHANGED
|
@@ -14,9 +14,19 @@ import {
|
|
|
14
14
|
} from "node:fs";
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
16
16
|
import { dirname, join } from "node:path";
|
|
17
|
-
import { errorCode } from "../util.mjs";
|
|
17
|
+
import { errorCode, sleepSync } from "../util.mjs";
|
|
18
18
|
|
|
19
19
|
const BOOTSTRAP_FILE = "bootstrap.json";
|
|
20
|
+
// Windows refuses to replace a file another process holds open: MoveFileEx
|
|
21
|
+
// answers EPERM (or EACCES, EBUSY) while a reader, an indexer or a virus
|
|
22
|
+
// scanner has the destination, where a POSIX rename replaces it regardless.
|
|
23
|
+
// Measured 2026-09-23 on Windows 11 with node 24: one process polling a file
|
|
24
|
+
// with readFileSync failed 882 of 2190 atomic writes onto it, and on CI that
|
|
25
|
+
// killed controllers mid-run (a heartbeat write threw out of driveRun). The
|
|
26
|
+
// retry and its bounds are graceful-fs's: back off 10 ms more per attempt up to
|
|
27
|
+
// 100 ms, and give up after 60 s.
|
|
28
|
+
const WINDOWS_RENAME_BUSY = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
29
|
+
const RENAME_RETRY_BUDGET_MS = 60_000;
|
|
20
30
|
const JSONL_RECOVERY_TAIL_BYTES = 64 * 1024;
|
|
21
31
|
|
|
22
32
|
/**
|
|
@@ -51,7 +61,7 @@ export function writeTextAtomic(path, text) {
|
|
|
51
61
|
} finally {
|
|
52
62
|
closeSync(fd);
|
|
53
63
|
}
|
|
54
|
-
|
|
64
|
+
renameReplacing(temporary, path);
|
|
55
65
|
fsyncDirectory(dirname(path));
|
|
56
66
|
committed = true;
|
|
57
67
|
} catch (error) {
|
|
@@ -68,6 +78,24 @@ export function writeTextAtomic(path, text) {
|
|
|
68
78
|
}
|
|
69
79
|
}
|
|
70
80
|
|
|
81
|
+
/**
|
|
82
|
+
* @param {string} from
|
|
83
|
+
* @param {string} to
|
|
84
|
+
*/
|
|
85
|
+
function renameReplacing(from, to) {
|
|
86
|
+
const deadline = Date.now() + RENAME_RETRY_BUDGET_MS;
|
|
87
|
+
for (let backoff = 0; ; backoff = Math.min(backoff + 10, 100)) {
|
|
88
|
+
try {
|
|
89
|
+
renameSync(from, to);
|
|
90
|
+
return;
|
|
91
|
+
} catch (error) {
|
|
92
|
+
const busy = process.platform === "win32" && WINDOWS_RENAME_BUSY.has(errorCode(error) ?? "");
|
|
93
|
+
if (!busy || Date.now() >= deadline) throw error;
|
|
94
|
+
sleepSync(backoff);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
71
99
|
/**
|
|
72
100
|
* @param {string} path
|
|
73
101
|
* @param {unknown} value
|
package/src/util.mjs
CHANGED
|
@@ -275,3 +275,13 @@ export function shellWords(text) {
|
|
|
275
275
|
if (current !== null) words.push(current);
|
|
276
276
|
return words;
|
|
277
277
|
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Block the thread without a timer, for a synchronous path that has to wait
|
|
281
|
+
* out a short race. Callers keep the duration tiny and bounded.
|
|
282
|
+
*
|
|
283
|
+
* @param {number} milliseconds
|
|
284
|
+
*/
|
|
285
|
+
export function sleepSync(milliseconds) {
|
|
286
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
|
|
287
|
+
}
|