brl-subagent 2.9.1 → 2.9.2
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/AGENT.md +3 -0
- package/README.md +11 -5
- package/package.json +7 -6
- package/src/agent-tools.ts +178 -19
- package/src/atomic-write.ts +101 -0
- package/src/background-guard.ts +295 -0
- package/src/background-pipeline.ts +19 -1
- package/src/boot-recovery.ts +16 -0
- package/src/brief.ts +228 -0
- package/src/delegate-handler.ts +39 -6
- package/src/dispatch-header.ts +230 -0
- package/src/index.ts +26 -0
- package/src/notify-completion.ts +81 -12
- package/src/params.ts +9 -1
- package/src/project-flags.ts +39 -2
- package/src/recovery-engine.ts +16 -2
- package/src/recovery.ts +29 -0
- package/src/retry-armed.ts +383 -0
- package/src/run-registry.ts +26 -1
- package/src/session-manager.ts +410 -38
- package/src/stop-lineage.ts +280 -0
- package/src/templates.ts +97 -1
- package/src/terminal-notifier.ts +69 -3
- package/src/types.ts +94 -0
- package/src/validate.ts +57 -0
- package/templates/analyze-data.md +1 -0
- package/templates/code-review.md +1 -0
- package/templates/debug-issue.md +1 -0
- package/templates/implement-feature.md +1 -0
- package/templates/prototype.md +1 -0
- package/templates/refactor.md +1 -0
- package/templates/security-audit.md +1 -0
- package/templates/write-docs.md +1 -0
- package/templates/write-tests.md +1 -0
package/AGENT.md
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
> nothing for users (a package directory is not in pi's context-file lookup
|
|
9
9
|
> chain) while adding its full contents to every session run inside this repo.
|
|
10
10
|
|
|
11
|
+
> **Vocabulary:** *dispatch*, *spawn*, *run* and *subagent* — and the one banned synonym — are stated in
|
|
12
|
+
> [`.development/VOCABULARY.md`](.development/VOCABULARY.md) and enforced by `scripts/check-vocabulary.mjs`.
|
|
13
|
+
|
|
11
14
|
This file is the authoritative reference for how the brl-subagent extension behaves
|
|
12
15
|
and how you (the conductor) should judge a delegation. Read it when planning
|
|
13
16
|
delegation-heavy work.
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
> Multi-agent orchestration for [pi](https://github.com/earendil-works/pi) — chain, parallel, and dependency-graph delegation to isolated subagents with per-step model routing, preset-driven tool scoping, thinking-level control, and background execution with live monitoring, real abort, and per-agent timeouts.
|
|
4
4
|
|
|
5
|
-
**Version:** 2.9.
|
|
5
|
+
**Version:** 2.9.2 · **Author:** Azmeen Afandi / [Beeroo Labs](https://beeroolabs.com) · **License:** MIT
|
|
6
6
|
|
|
7
7
|
---
|
|
8
8
|
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
- **True background execution** — live monitor, real abort (`stop_subagent`), per-agent timeouts, and a 30-minute default deadline for runs that don't set one. Nothing orphans; nothing leaks.
|
|
15
15
|
- **Preset-driven tool scoping** — every subagent runs with exactly the tools its job needs, restricted by preset or per-call `tools`/`excludeTools`, with auto-route that picks the right preset when you don't.
|
|
16
16
|
- **Templates with slots** — saved, file-backed task templates with `${param}` placeholders for workflows you run again and again.
|
|
17
|
-
- **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a
|
|
17
|
+
- **Safety by default** — task-fence injection protection, sanitized error paths, owner-only persistence (`0o700` stores, `0o600` files; the directory mode is repaired on every write and is the confidentiality boundary), and a 3700+ test suite pinning every contract against the real pi SDK.
|
|
18
18
|
|
|
19
19
|
---
|
|
20
20
|
|
|
@@ -158,13 +158,19 @@ Alongside `delegate_task`, the extension registers three companion tools for bac
|
|
|
158
158
|
|
|
159
159
|
### `stop_subagent`
|
|
160
160
|
|
|
161
|
-
Stops
|
|
161
|
+
Stops the background work of a **dispatch** — a real abort of the live session, not just a status flip.
|
|
162
162
|
|
|
163
163
|
| Parameter | Type | Description |
|
|
164
164
|
|---|---|---|
|
|
165
|
-
| `agent_id` | string | Agent ID of the
|
|
165
|
+
| `agent_id` | string | Agent ID of the background dispatch to stop (full id or a unique 8-character prefix) |
|
|
166
166
|
|
|
167
|
-
**What it does:**
|
|
167
|
+
**What it does:** resolves the id, expands it to the whole dispatch (the retries that continue the same work), and aborts every attempt of it that is still running — yours first, then its automatic transport retries in attempt order. It aborts the live session where one exists (the pending `prompt()` resolves with `stopReason: "aborted"` rather than hanging); an attempt whose record is on disk but has no live session behind it is settled by its status alone. Partial work from a `gitMode: 'branch'` run is captured before the work branch is discarded.
|
|
168
|
+
|
|
169
|
+
**Scope is `transport` only.** A background run that dies on a transport-class error is re-dispatched once automatically, as a different agent id under the same label — so stopping the id you were handed must also stop that retry. A retry you started yourself (`retryRunId`) is **not** stopped by a stop aimed at another attempt, because you deliberately started it; pass its own id to stop it. An attempt whose record does not say why it exists is *unknown*, and unknown is never stopped this way — it is reported instead.
|
|
170
|
+
|
|
171
|
+
**The report is built from the records, not from the tool's return value.** An attempt is reported as `Stopped` only after its record is re-read and is terminal; anything that could not be verified is an error. A line always carries the id, the attempt number and the cause. The call does **not** print a claim that the dispatch is quiet when that cannot be known: an armed-but-unspawned retry, an unknown cause, a live out-of-scope retry, or a truncated lineage scan (a run older than 7 days, or a store scan that hit its record cap) each get their own disclosure line.
|
|
172
|
+
|
|
173
|
+
Returns an error if the agent is not found and refuses an ambiguous id prefix (stopping nothing). An already-terminal dispatch with nothing running and nothing armed is a no-op success — the call stays idempotent. Use it to halt a background dispatch that is no longer needed.
|
|
168
174
|
|
|
169
175
|
---
|
|
170
176
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brl-subagent",
|
|
3
|
-
"version": "2.9.
|
|
3
|
+
"version": "2.9.2",
|
|
4
4
|
"description": "Subagent delegation for pi — blocking or background runs, chain/parallel/graph modes, presets and task templates, live monitor, and dispatch capability guards.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
]
|
|
26
26
|
},
|
|
27
27
|
"brl-subagent": {
|
|
28
|
-
"processChecks": true
|
|
28
|
+
"processChecks": true,
|
|
29
|
+
"backgroundGuard": "worktree-guard"
|
|
29
30
|
},
|
|
30
31
|
"scripts": {
|
|
31
32
|
"typecheck": "tsc --noEmit",
|
|
@@ -41,10 +42,10 @@
|
|
|
41
42
|
"typebox": "*"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
|
-
"@earendil-works/pi-agent-core": "^1.
|
|
45
|
-
"@earendil-works/pi-ai": "^1.
|
|
46
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
47
|
-
"@earendil-works/pi-tui": "^1.
|
|
45
|
+
"@earendil-works/pi-agent-core": "^1.7.0",
|
|
46
|
+
"@earendil-works/pi-ai": "^1.7.0",
|
|
47
|
+
"@earendil-works/pi-coding-agent": "^1.7.0",
|
|
48
|
+
"@earendil-works/pi-tui": "^1.7.0",
|
|
48
49
|
"jiti": "^2.7.0",
|
|
49
50
|
"typebox": "1.3.27",
|
|
50
51
|
"typescript": "7.0.2",
|
package/src/agent-tools.ts
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* needs one call site fewer than rewriting the schemas into named consts.
|
|
30
30
|
*/
|
|
31
31
|
|
|
32
|
+
import type { StoppedAttempt } from "./stop-lineage";
|
|
32
33
|
import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
33
34
|
import { Type, type TSchema } from "typebox";
|
|
34
35
|
import { formatBudgetLine, normalizeCompletionStatus } from "./notify-completion";
|
|
@@ -284,9 +285,12 @@ export function createAgentTools(): ToolDefinition<any, any, any>[] {
|
|
|
284
285
|
name: "stop_subagent",
|
|
285
286
|
label: "Stop Subagent",
|
|
286
287
|
description: [
|
|
287
|
-
"Stop a
|
|
288
|
-
"
|
|
289
|
-
"
|
|
288
|
+
"Stop a background agent by aborting its session.",
|
|
289
|
+
"A stop is DISPATCH-scoped: it stops the agent you name AND every automatic transport retry of the same dispatch that is still running, because a retried run continues the same work under a different id.",
|
|
290
|
+
"A manual retry (one you started yourself) is never stopped by a stop aimed at another attempt — pass its own id to stop it.",
|
|
291
|
+
"Accepts a full agent id or a unique 8-character id prefix; an ambiguous prefix stops nothing.",
|
|
292
|
+
"The report names every attempt it acted on (id, attempt, cause) and discloses anything left running, an armed retry, or a truncated lineage scan.",
|
|
293
|
+
"An already-terminal dispatch is a no-op success.",
|
|
290
294
|
].join(" "),
|
|
291
295
|
parameters: Type.Object({
|
|
292
296
|
agent_id: Type.String({
|
|
@@ -294,25 +298,12 @@ export function createAgentTools(): ToolDefinition<any, any, any>[] {
|
|
|
294
298
|
}),
|
|
295
299
|
}),
|
|
296
300
|
execute: async (toolCallId, params, _signal, _onUpdate, ctx) => {
|
|
297
|
-
const { stopAgent } = await import('./session-manager');
|
|
298
|
-
|
|
299
301
|
try {
|
|
300
|
-
const
|
|
301
|
-
|
|
302
|
-
if (!agent) {
|
|
303
|
-
return {
|
|
304
|
-
content: [{ type: "text" as const, text: `Agent ${params.agent_id} not found` }],
|
|
305
|
-
details: undefined,
|
|
306
|
-
isError: true,
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
|
|
302
|
+
const report = await runDispatchStop(params.agent_id, ctx);
|
|
310
303
|
return {
|
|
311
|
-
content: [{
|
|
312
|
-
type: "text" as const,
|
|
313
|
-
text: `Stopped agent ${params.agent_id} (${agent.description}).`,
|
|
314
|
-
}],
|
|
304
|
+
content: [{ type: "text" as const, text: report.text }],
|
|
315
305
|
details: undefined,
|
|
306
|
+
...(report.isError ? { isError: true } : {}),
|
|
316
307
|
};
|
|
317
308
|
} catch (err) {
|
|
318
309
|
// F7 (issue #65): sanitize BEFORE the message reaches the main
|
|
@@ -330,3 +321,171 @@ export function createAgentTools(): ToolDefinition<any, any, any>[] {
|
|
|
330
321
|
});
|
|
331
322
|
return [getSubagentResultTool, steerSubagentTool, stopSubagentTool];
|
|
332
323
|
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Issue #616 — the stop contract, as one function: **resolve → plan → cancel an
|
|
327
|
+
* armed retry → stop each live attempt → verify from the records → report**.
|
|
328
|
+
*
|
|
329
|
+
* Separated from the tool definition so the tool stays the adapter it is for the
|
|
330
|
+
* other two lifecycle tools, and every step below is greppable by name.
|
|
331
|
+
*
|
|
332
|
+
* SCOPE (the brief's Contract): the requested id — always — plus every attempt of
|
|
333
|
+
* the same dispatch whose recorded `retryCause` is `transport`. A `manual` retry
|
|
334
|
+
* is disclosed residue, never stopped by scope; an attempt whose cause is ABSENT
|
|
335
|
+
* is unknown and equally untouched. Naming a manual retry's own id DOES stop it
|
|
336
|
+
* (it is the requested id, and `retryCause` is a filter, not an immunity).
|
|
337
|
+
*
|
|
338
|
+
* Never prints a universal claim over a partial answer: an armed retry, an
|
|
339
|
+
* unknown cause, or a truncated lineage scan each get their own disclosure line
|
|
340
|
+
* instead, and the claim itself is suppressed.
|
|
341
|
+
*/
|
|
342
|
+
async function runDispatchStop(
|
|
343
|
+
rawId: string,
|
|
344
|
+
ctx: { cwd?: string } | undefined,
|
|
345
|
+
): Promise<{ text: string; isError: boolean }> {
|
|
346
|
+
const {
|
|
347
|
+
getAgent,
|
|
348
|
+
resolveAgentId,
|
|
349
|
+
findRetryLineage,
|
|
350
|
+
readAgentRecordFromDisk,
|
|
351
|
+
stopAgent,
|
|
352
|
+
} = await import('./session-manager');
|
|
353
|
+
const { planDispatchStop, formatStopReport } = await import('./stop-lineage');
|
|
354
|
+
const { readArmedRetry, cancelArmedRetry } = await import('./retry-armed');
|
|
355
|
+
const { isTerminalAgentStatusValue } = await import('./types');
|
|
356
|
+
|
|
357
|
+
// The notices render the first 8 hex characters of an id, and labels are
|
|
358
|
+
// shared across attempts (that IS #616) — so resolve a prefix exactly as
|
|
359
|
+
// `get_subagent_result` does, and fail closed on ambiguity: a guess here could
|
|
360
|
+
// stop the wrong dispatch.
|
|
361
|
+
const resolution = resolveAgentId(rawId);
|
|
362
|
+
if (resolution.kind === 'ambiguous') {
|
|
363
|
+
return {
|
|
364
|
+
text: `Agent id prefix "${rawId}" is ambiguous — matches: ${resolution.matches.join(', ')}. Nothing was stopped.`,
|
|
365
|
+
isError: true,
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
if (resolution.kind === 'unresolved') return { text: `Agent ${rawId} not found`, isError: true };
|
|
369
|
+
const agentId = resolution.id;
|
|
370
|
+
|
|
371
|
+
// The record read is deliberately NOT windowed: the stop must act on a run
|
|
372
|
+
// that exists, not on what the (bounded) lineage scan could see.
|
|
373
|
+
const agent = getAgent(agentId);
|
|
374
|
+
if (!agent) return { text: `Agent ${rawId} not found`, isError: true };
|
|
375
|
+
|
|
376
|
+
// Review 624 (B1): a marker is STALE when it is an UNCLAIMED intent too old
|
|
377
|
+
// to be about a spawn still on its way. The rule lives in `retry-armed` so
|
|
378
|
+
// every reader — this cancel, the gate, the boot sweep — makes the SAME
|
|
379
|
+
// judgement (review 624 r2: the terminal-parent accelerator is gone; a
|
|
380
|
+
// parent's terminality proves nothing about whether this dispatch's spawn is
|
|
381
|
+
// still queued behind another run). A stale marker is reclaimed by the read,
|
|
382
|
+
// so it never produces a cancel line and never suppresses the claim — which is
|
|
383
|
+
// exactly what a marker left by a process that died between the arm write and
|
|
384
|
+
// the spawn used to do, forever. A CANCELLED marker is never stale at any age.
|
|
385
|
+
const armedFor = (family: Array<{ id: string }>) => {
|
|
386
|
+
const ids = new Set<string>([agentId, ...family.map((record) => record.id)]);
|
|
387
|
+
return [...ids]
|
|
388
|
+
.map((id) => readArmedRetry(id))
|
|
389
|
+
.filter((marker): marker is NonNullable<typeof marker> => marker !== null);
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// Plan 1 — computed BEFORE any cancel, so the armed markers are still there.
|
|
393
|
+
const firstLineage = findRetryLineage(agentId, agent);
|
|
394
|
+
let plan = planDispatchStop({
|
|
395
|
+
targetId: agentId,
|
|
396
|
+
lineage: firstLineage,
|
|
397
|
+
armed: armedFor(firstLineage.family),
|
|
398
|
+
nowMs: Date.now(),
|
|
399
|
+
});
|
|
400
|
+
|
|
401
|
+
const cancels: Array<{
|
|
402
|
+
armed: (typeof plan.armed)[number];
|
|
403
|
+
outcome: Awaited<ReturnType<typeof cancelArmedRetry>>;
|
|
404
|
+
}> = [];
|
|
405
|
+
for (const marker of plan.armed) {
|
|
406
|
+
cancels.push({
|
|
407
|
+
armed: marker,
|
|
408
|
+
outcome: cancelArmedRetry(marker.parentId, marker.attempt),
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// A cancel that found NO marker means the retry became durable between the read
|
|
413
|
+
// and the cancel: the spawn's pre-prompt gate cleared the marker, so the retry
|
|
414
|
+
// now HAS a record. Re-read the lineage ONCE and stop it like any other live
|
|
415
|
+
// attempt rather than reporting an armed retry that no longer exists.
|
|
416
|
+
if (cancels.some((cancel) => cancel.outcome === 'gone')) {
|
|
417
|
+
const reLineage = findRetryLineage(agentId, agent);
|
|
418
|
+
plan = planDispatchStop({
|
|
419
|
+
targetId: agentId,
|
|
420
|
+
lineage: reLineage,
|
|
421
|
+
armed: armedFor(reLineage.family),
|
|
422
|
+
nowMs: Date.now(),
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const stopped: StoppedAttempt[] = [];
|
|
427
|
+
for (const record of plan.live) {
|
|
428
|
+
let thrown: string | undefined;
|
|
429
|
+
try {
|
|
430
|
+
// SEQUENTIAL, one contained try per attempt: a throw must not hide the
|
|
431
|
+
// next run's stop, nor the evidence the report is built from.
|
|
432
|
+
await stopAgent(record.id);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
thrown = sanitizeErrorMessage(err instanceof Error ? err.message : String(err), ctx?.cwd);
|
|
435
|
+
}
|
|
436
|
+
// THE VERDICT IS THE STORE'S, not the primitive's return value: `stopAgent`
|
|
437
|
+
// returns a terminal record UNCHANGED, so "already dead" and "just stopped"
|
|
438
|
+
// are the same answer — the record is what can tell them apart.
|
|
439
|
+
const after = readAgentRecordFromDisk(record.id);
|
|
440
|
+
const status = after.record?.status;
|
|
441
|
+
const verified = status !== undefined && isTerminalAgentStatusValue(status);
|
|
442
|
+
const storeState = after.record
|
|
443
|
+
? `status ${after.record.status}`
|
|
444
|
+
: after.exists
|
|
445
|
+
? `record ${after.reason ?? 'unreadable'}`
|
|
446
|
+
: 'no record';
|
|
447
|
+
stopped.push({
|
|
448
|
+
record,
|
|
449
|
+
description: after.record?.description ?? getAgent(record.id)?.description,
|
|
450
|
+
verifiedStatus: verified ? (status as NonNullable<typeof status>) : null,
|
|
451
|
+
unverifiedState: verified
|
|
452
|
+
? undefined
|
|
453
|
+
: thrown
|
|
454
|
+
? `${storeState}; stopAgent threw: ${thrown}`
|
|
455
|
+
: storeState,
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// Review 624 (F5): the markers were read BEFORE the stops above. An `armRetry`
|
|
460
|
+
// that lands between that read and this line would otherwise let the report
|
|
461
|
+
// claim quiescence over a retry that is about to prompt. Re-read ONCE, fold
|
|
462
|
+
// every marker not already accounted for in as a cancel, and let
|
|
463
|
+
// `formatStopReport`'s own rule suppress the claim. A `gone` outcome (the retry
|
|
464
|
+
// became durable inside that interval) prints no line but still withholds the
|
|
465
|
+
// claim: the attempt was not in the plan, so the plan cannot vouch for it.
|
|
466
|
+
// Review 624 r2 (N-r2-3): the dedup key is the MARKER's identity, not its
|
|
467
|
+
// parent. A `gone` outcome plus a re-plan can leave a marker for the same
|
|
468
|
+
// source at a NEW attempt (a second scheduleTransportRetry): keying on
|
|
469
|
+
// `parentId` alone would skip it and let the universal claim print over a
|
|
470
|
+
// retry that is about to prompt.
|
|
471
|
+
const armedKey = (marker: { parentId: string; attempt: number }): string =>
|
|
472
|
+
`${marker.parentId}:${marker.attempt}`;
|
|
473
|
+
const plannedArmed = new Set(cancels.map((cancel) => armedKey(cancel.armed)));
|
|
474
|
+
const planRecords = [
|
|
475
|
+
...(plan.target ? [plan.target] : []),
|
|
476
|
+
...plan.live,
|
|
477
|
+
...plan.terminalFamily,
|
|
478
|
+
...plan.outOfScopeLive,
|
|
479
|
+
...plan.unknownCauseLive,
|
|
480
|
+
];
|
|
481
|
+
for (const marker of armedFor(planRecords)) {
|
|
482
|
+
if (plannedArmed.has(armedKey(marker))) continue;
|
|
483
|
+
cancels.push({
|
|
484
|
+
armed: marker,
|
|
485
|
+
outcome: cancelArmedRetry(marker.parentId, marker.attempt),
|
|
486
|
+
});
|
|
487
|
+
plannedArmed.add(armedKey(marker));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
return formatStopReport({ plan, stopped, cancels });
|
|
491
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Purpose: A same-directory temp+rename writer for the agent record — a reader never sees a torn JSON file.
|
|
2
|
+
/**
|
|
3
|
+
* Issue #554 — process-kill atomicity for the agent store's one record writer.
|
|
4
|
+
*
|
|
5
|
+
* `persistAgent` used to `writeFileSync(filePath, json)`: Node truncates the
|
|
6
|
+
* destination and then writes, so a SIGKILL between those two steps leaves a
|
|
7
|
+
* half-written record — unparseable, and indistinguishable from a permissions
|
|
8
|
+
* fault to every reader. The fix is the standard one: write the whole text to a
|
|
9
|
+
* temp file in the SAME directory, `fsync` it best-effort, then `rename` it over
|
|
10
|
+
* the destination. On POSIX a rename is atomic, so a reader sees either the old
|
|
11
|
+
* file or the new one — never a torn one.
|
|
12
|
+
*
|
|
13
|
+
* WHAT THIS DOES NOT CLAIM (issue #554 §2): the guarantee is process-kill
|
|
14
|
+
* atomicity, not power-loss durability. The temp file is fsynced best-effort
|
|
15
|
+
* (a failure is swallowed — some filesystems/files reject it and a record write
|
|
16
|
+
* must not fail for that), and the DIRECTORY is deliberately not fsynced. Nor is
|
|
17
|
+
* this writer isolation: two writers can still interleave, and the last rename
|
|
18
|
+
* wins. Atomicity is a reader-facing invariant, not a last-writer-wins one.
|
|
19
|
+
*
|
|
20
|
+
* The temp's mode travels through the rename (the destination's inode changes);
|
|
21
|
+
* callers get a `0o600` record on every successful write, which is the mode
|
|
22
|
+
* `persistAgent` has always asked for.
|
|
23
|
+
*/
|
|
24
|
+
import { closeSync, fsyncSync, openSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
25
|
+
import { randomBytes } from 'node:crypto';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The filesystem surface this writer uses. Production passes nothing (the real
|
|
29
|
+
* `node:fs` is the default); `options.fs` exists ONLY as a fault-injection seam
|
|
30
|
+
* for tests — there is no production caller that supplies it.
|
|
31
|
+
*/
|
|
32
|
+
export interface AtomicFs {
|
|
33
|
+
openSync(path: string, flags: string, mode?: number): number;
|
|
34
|
+
writeFileSync(fd: number, data: string): void;
|
|
35
|
+
fsyncSync(fd: number): void;
|
|
36
|
+
closeSync(fd: number): void;
|
|
37
|
+
renameSync(from: string, to: string): void;
|
|
38
|
+
unlinkSync(path: string): void;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const nodeFs: AtomicFs = { openSync, writeFileSync, fsyncSync, closeSync, renameSync, unlinkSync };
|
|
42
|
+
|
|
43
|
+
/** Default mode for the temp (and therefore the destination) file. */
|
|
44
|
+
const DEFAULT_MODE = 0o600;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Write `text` to `file` atomically with respect to a process kill.
|
|
48
|
+
*
|
|
49
|
+
* The temp is `${file}.${pid}.${8 random bytes}.tmp` in the destination's own
|
|
50
|
+
* directory, so the rename never crosses a filesystem boundary. `mode` is
|
|
51
|
+
* applied when the temp is CREATED (the old file's mode is not consulted).
|
|
52
|
+
*
|
|
53
|
+
* On any failure the temp is unlinked best-effort — its own error is swallowed
|
|
54
|
+
* so it can never mask the original — and the original error is rethrown. A
|
|
55
|
+
* failing `closeSync` is swallowed the same way when a write error is already in
|
|
56
|
+
* flight, and surfaces only when it is the ONLY failure, so a double fault still
|
|
57
|
+
* reports the primary one.
|
|
58
|
+
*/
|
|
59
|
+
export function writeFileAtomicSync(
|
|
60
|
+
file: string,
|
|
61
|
+
text: string,
|
|
62
|
+
options?: { mode?: number; fs?: AtomicFs },
|
|
63
|
+
): void {
|
|
64
|
+
const fs = options?.fs ?? nodeFs;
|
|
65
|
+
const mode = options?.mode ?? DEFAULT_MODE;
|
|
66
|
+
const tmp = `${file}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
|
|
67
|
+
try {
|
|
68
|
+
const fd = fs.openSync(tmp, 'wx', mode);
|
|
69
|
+
let writeFailed = false;
|
|
70
|
+
try {
|
|
71
|
+
fs.writeFileSync(fd, text);
|
|
72
|
+
// Best-effort: the guarantee is a complete file after a process kill,
|
|
73
|
+
// not that its bytes survive a power loss.
|
|
74
|
+
try {
|
|
75
|
+
fs.fsyncSync(fd);
|
|
76
|
+
} catch {
|
|
77
|
+
// swallowed on purpose — see the module comment
|
|
78
|
+
}
|
|
79
|
+
} catch (err) {
|
|
80
|
+
writeFailed = true;
|
|
81
|
+
throw err;
|
|
82
|
+
} finally {
|
|
83
|
+
try {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
} catch (closeErr) {
|
|
86
|
+
// A double fault must keep the PRIMARY error: a close failure is only
|
|
87
|
+
// worth reporting when nothing else failed.
|
|
88
|
+
if (!writeFailed) throw closeErr;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
fs.renameSync(tmp, file);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
// Best-effort cleanup whose failure must never mask `err`.
|
|
94
|
+
try {
|
|
95
|
+
fs.unlinkSync(tmp);
|
|
96
|
+
} catch {
|
|
97
|
+
// already gone, or the directory is unwritable — nothing to do
|
|
98
|
+
}
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
}
|