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/src/recovery.ts
CHANGED
|
@@ -85,6 +85,15 @@ export interface BootScanSummary {
|
|
|
85
85
|
flipRetired: number;
|
|
86
86
|
/** Issue #546: flips decided but whose durable write did NOT land (#304 rule). */
|
|
87
87
|
flipFailures: number;
|
|
88
|
+
/**
|
|
89
|
+
* Issue #554: the CORRUPT subset of `flipFailures` — the record was present
|
|
90
|
+
* and its bytes were read, but `JSON.parse` rejected them. An ADDITIONAL
|
|
91
|
+
* count, never a replacement: `flipFailures` keeps its meaning (a failed
|
|
92
|
+
* settlement) so #546's H2c and every other marker case stay valid. The
|
|
93
|
+
* operator's distinction is "repair the file" (corrupt) vs "fix permissions"
|
|
94
|
+
* (unreadable, the rest of `flipFailures`).
|
|
95
|
+
*/
|
|
96
|
+
flipCorrupt: number;
|
|
88
97
|
}
|
|
89
98
|
|
|
90
99
|
/** The all-zero summary (a skipped scan / an empty registry). */
|
|
@@ -103,6 +112,7 @@ export function emptyBootScanSummary(): BootScanSummary {
|
|
|
103
112
|
flipRepaired: 0,
|
|
104
113
|
flipRetired: 0,
|
|
105
114
|
flipFailures: 0,
|
|
115
|
+
flipCorrupt: 0,
|
|
106
116
|
};
|
|
107
117
|
}
|
|
108
118
|
|
|
@@ -330,8 +340,18 @@ export type RecordFlipOutcome = "repaired" | "retired" | false;
|
|
|
330
340
|
export interface FreshAgentRecord {
|
|
331
341
|
record: PersistedAgentLike | null;
|
|
332
342
|
exists: boolean;
|
|
343
|
+
/**
|
|
344
|
+
* Issue #554: WHY there is no record when `exists` is true — `"corrupt"`
|
|
345
|
+
* (the file read, but JSON.parse rejected it) vs `"unreadable"` (stat/read
|
|
346
|
+
* failed). Optional so a caller that only knows the tri-state (a test seam)
|
|
347
|
+
* stays valid; the boot ledger counts the corrupt subset by name.
|
|
348
|
+
*/
|
|
349
|
+
reason?: AgentRecordFailureReason;
|
|
333
350
|
}
|
|
334
351
|
|
|
352
|
+
/** Issue #554: the two named record-read failures. */
|
|
353
|
+
export type AgentRecordFailureReason = "corrupt" | "unreadable";
|
|
354
|
+
|
|
335
355
|
export interface RegistryScanOptions {
|
|
336
356
|
deps: RecoveryDeps;
|
|
337
357
|
/**
|
|
@@ -468,6 +488,9 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
468
488
|
let flipRepaired = 0;
|
|
469
489
|
let flipRetired = 0;
|
|
470
490
|
let flipFailures = 0;
|
|
491
|
+
// Issue #554: the corrupt SUBSET of the failures above — counted beside it,
|
|
492
|
+
// never instead of it.
|
|
493
|
+
let flipCorrupt = 0;
|
|
471
494
|
for (const entry of addressable) {
|
|
472
495
|
const isBackground = entry.kind === "background";
|
|
473
496
|
// Only a background entry has an agent record to enrich from (and to drop
|
|
@@ -508,9 +531,14 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
508
531
|
// tell whether it is still `running`. The marker is KEPT and the
|
|
509
532
|
// settlement is counted failed (never silently dropped).
|
|
510
533
|
flipFailures++;
|
|
534
|
+
// Issue #554: name the corrupt subset — the record read fine but
|
|
535
|
+
// its JSON did not parse. The decision and the kept marker are
|
|
536
|
+
// unchanged; only the ledger gains the finer distinction.
|
|
537
|
+
if (fresh.reason === "corrupt") flipCorrupt++;
|
|
511
538
|
options.log?.warn("Recovery: could not read the agent record for a record-flip marker — the marker is kept", {
|
|
512
539
|
id: entry.id,
|
|
513
540
|
kind: entry.kind,
|
|
541
|
+
...(fresh.reason ? { reason: fresh.reason } : {}),
|
|
514
542
|
});
|
|
515
543
|
continue;
|
|
516
544
|
}
|
|
@@ -657,6 +685,7 @@ export async function recoverInflightRuns(options: RegistryScanOptions): Promise
|
|
|
657
685
|
summary.flipRepaired = flipRepaired;
|
|
658
686
|
summary.flipRetired = flipRetired;
|
|
659
687
|
summary.flipFailures = flipFailures;
|
|
688
|
+
summary.flipCorrupt = flipCorrupt;
|
|
660
689
|
return summary;
|
|
661
690
|
}
|
|
662
691
|
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
// Purpose: The durable "retry armed" marker for the background transport auto-retry (issue #616).
|
|
2
|
+
/**
|
|
3
|
+
* Issue #616 (Q3) — the ARMED-RETRY marker.
|
|
4
|
+
*
|
|
5
|
+
* The background transport auto-retry has an unaddressable window: the retry
|
|
6
|
+
* attempt's id is minted inside `spawnBackgroundSession` and its agent record +
|
|
7
|
+
* registry entry only land several statements later. Between the two, nothing
|
|
8
|
+
* durable says the retry exists, so a `stop_subagent` aimed at the dispatch
|
|
9
|
+
* finds a dead attempt 1 and truthfully-but-uselessly reports "stopped" while
|
|
10
|
+
* the retry is being started.
|
|
11
|
+
*
|
|
12
|
+
* This module closes that window with a marker that is an **intent, not a run**:
|
|
13
|
+
*
|
|
14
|
+
* - it is written by `scheduleTransportRetry` BEFORE the spawn
|
|
15
|
+
* (`armRetry`), naming the SOURCE run it replaces and the attempt it will
|
|
16
|
+
* become;
|
|
17
|
+
* - a stop of that dispatch sets `cancelRequested` (`cancelArmedRetry`);
|
|
18
|
+
* - the spawn honours it at its pre-prompt gate
|
|
19
|
+
* (`isRetryCancelRequested` → settle `stopped`, never prompt) and clears it
|
|
20
|
+
* once the retry is durable (`clearArmedRetry`).
|
|
21
|
+
*
|
|
22
|
+
* WHY NOT A FIELD ON THE EXISTING REGISTRY ENTRY: the retry's entry does not
|
|
23
|
+
* exist yet inside the window — that IS the window. The marker therefore hangs
|
|
24
|
+
* off the one id that does exist, the source run.
|
|
25
|
+
*
|
|
26
|
+
* WHY A SUBDIRECTORY (`.pi/run-registry/armed/`): every run-shaped reader —
|
|
27
|
+
* `listInflightRuns` (and therefore the boot scan), run history, the monitor —
|
|
28
|
+
* enumerates `*.json` files directly in the registry directory. A nested
|
|
29
|
+
* directory is invisible to all of them by construction, which is what keeps an
|
|
30
|
+
* INTENT from rendering as a RUN ROW. (`src/__tests__/stop-subagent-lineage.test.ts`
|
|
31
|
+
* pins that: arming produces no registry entry and no run record.)
|
|
32
|
+
*
|
|
33
|
+
* Writes are atomic (temp + rename) and owner-only (0o600), mirroring the
|
|
34
|
+
* registry's own discipline. Every reader is total: a missing, unreadable or
|
|
35
|
+
* malformed marker reads as "nothing armed" and never throws — the failure mode
|
|
36
|
+
* is the pre-#616 window, not a broken stop.
|
|
37
|
+
*
|
|
38
|
+
* THE AGE RULE (review 624 r2, B1): **age may reclaim an INTENT, never a
|
|
39
|
+
* CANCEL.** An UNCLAIMED marker past `ARMED_RETRY_STALE_MS` is crash residue and
|
|
40
|
+
* is reclaimed on read (and by the boot sweep); a marker whose
|
|
41
|
+
* `cancelRequested === true` is NEVER stale and is never unlinked by age, in any
|
|
42
|
+
* reader. The stretch between the arm and the pre-prompt gate is NOT bounded —
|
|
43
|
+
* the spawn waits in the process-wide spawn queue, and a `gitMode: 'branch'`
|
|
44
|
+
* retry waits on another run's repository lock, bound only by that run's
|
|
45
|
+
* lifetime — so a cancel can still have its gate coming arbitrarily far away.
|
|
46
|
+
* Reclaiming it on age would silently lose a live stop, which is the failure this
|
|
47
|
+
* issue exists to prevent.
|
|
48
|
+
*
|
|
49
|
+
* THE ACCEPTED RESIDUAL (stated, not papered over): a cancel whose spawn never
|
|
50
|
+
* materialises — the process died after the cancel write, before the gate — stays
|
|
51
|
+
* on disk forever, and every later stop of that dispatch keeps the "not claimed
|
|
52
|
+
* quiescent" disclosure. A permanent false NOT-QUIESCENT is acceptable; a false
|
|
53
|
+
* QUIESCENT is the bug this issue exists for.
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
import * as fs from 'node:fs';
|
|
57
|
+
import * as path from 'node:path';
|
|
58
|
+
|
|
59
|
+
import { writeFileAtomicSync } from './atomic-write';
|
|
60
|
+
import { registryDir } from './run-registry';
|
|
61
|
+
import { assertSafeAgentId } from './sanitize';
|
|
62
|
+
import { ensureOwnerOnlyDir } from './store-permissions';
|
|
63
|
+
|
|
64
|
+
/** The armed retry's cause. Only the automatic transport retry is ever armed. */
|
|
65
|
+
export type ArmedRetryCause = 'transport';
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Issue #616 / review 624 (B1) — the RE-ARM BOUND.
|
|
69
|
+
*
|
|
70
|
+
* The ONE thing this bound decides is whether a SECOND arm for the same source
|
|
71
|
+
* may inherit a cancel from the previous one. Inside it, a re-arm PRESERVES the
|
|
72
|
+
* cancel (a second `scheduleTransportRetry` must not un-cancel a stop that
|
|
73
|
+
* already reached the dispatch). Beyond it the previous arm describes a spawn
|
|
74
|
+
* that never made it (the process died between arm and gate), so a cancel on it
|
|
75
|
+
* belongs to a spawn that is gone — preserving it would let a phantom kill the
|
|
76
|
+
* retry this arm is about to start.
|
|
77
|
+
*
|
|
78
|
+
* It is NOT a staleness bound: no reader reclaims a marker on this age, and age
|
|
79
|
+
* never reclaims a cancel at all (see `ARMED_RETRY_STALE_MS`).
|
|
80
|
+
*/
|
|
81
|
+
export const ARMED_RETRY_SPAWN_BOUND_MS = 120_000;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Issue #616 / review 624 (B1) — the UNCLAIMED-MARKER STALE BOUND.
|
|
85
|
+
*
|
|
86
|
+
* Nothing clears a marker when the process dies between the arm write and the
|
|
87
|
+
* spawn, and no run-shaped reader enumerates `armed/` (that is what keeps an
|
|
88
|
+
* intent from rendering as a run row), so without an age rule a phantom marker
|
|
89
|
+
* makes every later stop of that dispatch print "Cancelled transport retry …"
|
|
90
|
+
* for a retry that will never exist, and suppress the universal claim forever.
|
|
91
|
+
*
|
|
92
|
+
* AGE RECLAIMS AN INTENT, NEVER A CANCEL. This bound applies ONLY to a marker
|
|
93
|
+
* with no `cancelRequested` (see the module header). A CANCELLED marker is never
|
|
94
|
+
* stale at any age — in the gate, in the stop's cancel, and in the boot sweep —
|
|
95
|
+
* because its gate can still be an unbounded wait away.
|
|
96
|
+
*
|
|
97
|
+
* THE ACCEPTED RESIDUAL: a cancel whose spawn never materialises stays on disk
|
|
98
|
+
* indefinitely and keeps its dispatch's "not claimed quiescent" disclosure. The
|
|
99
|
+
* safe direction is deliberate: a false not-quiescent is survivable, a false
|
|
100
|
+
* quiescent is not.
|
|
101
|
+
*/
|
|
102
|
+
export const ARMED_RETRY_STALE_MS = 600_000;
|
|
103
|
+
|
|
104
|
+
/** One durable "a transport retry is being started for this run" intent. */
|
|
105
|
+
export interface ArmedRetry {
|
|
106
|
+
/** The SOURCE run id — the attempt a stop of the dispatch resolves to. */
|
|
107
|
+
parentId: string;
|
|
108
|
+
/** The attempt number the retry will carry (`sourceAttempt + 1`). */
|
|
109
|
+
attempt: number;
|
|
110
|
+
cause: ArmedRetryCause;
|
|
111
|
+
/** ISO stamp of the arm write (diagnostics and ordering). */
|
|
112
|
+
armedAt: string;
|
|
113
|
+
/** Set by a stop that reached the dispatch while the retry was unspawned. */
|
|
114
|
+
cancelRequested?: boolean;
|
|
115
|
+
/** ISO stamp of that cancel. */
|
|
116
|
+
cancelRequestedAt?: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The marker subdirectory, resolved against the CURRENT registry dir per call. */
|
|
120
|
+
function armedDir(): string {
|
|
121
|
+
return path.join(registryDir(), 'armed');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** `<registry>/armed/<parentId>.json`, or `null` for an unusable id. */
|
|
125
|
+
function armedPath(parentId: string): string | null {
|
|
126
|
+
try {
|
|
127
|
+
assertSafeAgentId(parentId);
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
return path.join(armedDir(), `${parentId}.json`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function isArmedRetry(value: unknown): value is ArmedRetry {
|
|
135
|
+
if (!value || typeof value !== 'object') return false;
|
|
136
|
+
const v = value as Record<string, unknown>;
|
|
137
|
+
if (typeof v.parentId !== 'string' || v.parentId === '') return false;
|
|
138
|
+
if (typeof v.attempt !== 'number' || !Number.isFinite(v.attempt) || v.attempt < 1) return false;
|
|
139
|
+
if (v.cause !== 'transport') return false;
|
|
140
|
+
if (typeof v.armedAt !== 'string' || v.armedAt === '') return false;
|
|
141
|
+
if (v.cancelRequested !== undefined && typeof v.cancelRequested !== 'boolean') return false;
|
|
142
|
+
if (v.cancelRequestedAt !== undefined && typeof v.cancelRequestedAt !== 'string') return false;
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function writeArmed(retry: ArmedRetry): boolean {
|
|
147
|
+
const file = armedPath(retry.parentId);
|
|
148
|
+
if (!file) return false;
|
|
149
|
+
try {
|
|
150
|
+
ensureOwnerOnlyDir(armedDir());
|
|
151
|
+
writeFileAtomicSync(file, JSON.stringify(retry, null, 2));
|
|
152
|
+
return true;
|
|
153
|
+
} catch {
|
|
154
|
+
// Best-effort by contract: a marker that cannot be written leaves the
|
|
155
|
+
// pre-#616 window, which is strictly better than refusing the retry.
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** The marker's age in ms, or `null` when its stamp cannot be read. */
|
|
161
|
+
function armedAgeMs(retry: ArmedRetry): number | null {
|
|
162
|
+
const armedAt = Date.parse(retry.armedAt);
|
|
163
|
+
if (!Number.isFinite(armedAt)) return null;
|
|
164
|
+
return Date.now() - armedAt;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Is this marker an unclaimed intent old enough to be crash residue?
|
|
169
|
+
*
|
|
170
|
+
* RULE (1), review 624 r2: a CANCEL is never stale — its spawn's gate can still
|
|
171
|
+
* be waiting behind the spawn queue or another run's repository lock, so an age
|
|
172
|
+
* bound would silently drop a live stop. Only an UNCLAIMED marker is judged, and
|
|
173
|
+
* only by age.
|
|
174
|
+
*
|
|
175
|
+
* TOTAL and CHEAP: one parse of a stamp already in memory. An unjudgeable stamp
|
|
176
|
+
* (a rolled-back clock, a corrupt `armedAt`) is NOT stale — the conservative
|
|
177
|
+
* side is to honour an intent we cannot date (review 624, N-r2-4).
|
|
178
|
+
*/
|
|
179
|
+
function isStaleArmedRetry(retry: ArmedRetry): boolean {
|
|
180
|
+
if (retry.cancelRequested === true) return false;
|
|
181
|
+
const age = armedAgeMs(retry);
|
|
182
|
+
if (age === null) return false;
|
|
183
|
+
return age > ARMED_RETRY_STALE_MS;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Unlink a marker file. Best-effort: a failed unlink leaves it readable. */
|
|
187
|
+
function reclaimArmed(file: string): boolean {
|
|
188
|
+
try {
|
|
189
|
+
fs.unlinkSync(file);
|
|
190
|
+
return true;
|
|
191
|
+
} catch {
|
|
192
|
+
// ENOENT (already gone) and EACCES (cannot reclaim) both leave a marker that
|
|
193
|
+
// the next read judges stale again — no state is corrupted by failing here.
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Read one marker. Total: absent/unreadable/malformed all read as `null`. */
|
|
199
|
+
export function readArmedRetry(parentId: string): ArmedRetry | null {
|
|
200
|
+
const file = armedPath(parentId);
|
|
201
|
+
if (!file) return null;
|
|
202
|
+
let parsed: unknown;
|
|
203
|
+
try {
|
|
204
|
+
parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
205
|
+
} catch {
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
208
|
+
if (!isArmedRetry(parsed)) return null;
|
|
209
|
+
// The id in the FILE must be the id we asked about: a mismatched marker is
|
|
210
|
+
// not this run's intent.
|
|
211
|
+
if (parsed.parentId !== parentId) return null;
|
|
212
|
+
// Review 624 (B1): reclaim on read. A stale marker must not be honoured by
|
|
213
|
+
// ANY reader — the gate, the cancel and the stop report all come through here.
|
|
214
|
+
// A cancel is never stale (rule 1), so this can only drop an unclaimed intent.
|
|
215
|
+
if (isStaleArmedRetry(parsed)) {
|
|
216
|
+
reclaimArmed(file);
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
return parsed;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Arm `attempt` for `parentId`. Idempotent WITHIN THE RE-ARM BOUND: re-arming an
|
|
224
|
+
* already-armed retry refreshes the stamp but PRESERVES a cancel that is already
|
|
225
|
+
* requested (a second arming must not un-cancel a stop that already reached it).
|
|
226
|
+
*
|
|
227
|
+
* BEYOND the re-arm bound the previous marker cannot be about this spawn: it
|
|
228
|
+
* outlived an arm whose spawn never reached the gate (the process died), so a
|
|
229
|
+
* cancel on it describes a spawn that is gone. Preserving it would let a phantom
|
|
230
|
+
* kill THIS retry at the gate, so the arm starts fresh instead (review 624, B1).
|
|
231
|
+
*
|
|
232
|
+
* An age that CANNOT be judged is IN-WINDOW (review 624, N-r2-4): honour the
|
|
233
|
+
* cancel rather than discard one that every other reader would still honour.
|
|
234
|
+
*/
|
|
235
|
+
export function armRetry(input: {
|
|
236
|
+
parentId: string;
|
|
237
|
+
attempt: number;
|
|
238
|
+
armedAt: string;
|
|
239
|
+
}): boolean {
|
|
240
|
+
const existing = readArmedRetry(input.parentId);
|
|
241
|
+
const age = existing ? armedAgeMs(existing) : null;
|
|
242
|
+
const inSpawnWindow = age === null || age <= ARMED_RETRY_SPAWN_BOUND_MS;
|
|
243
|
+
if (existing && existing.attempt === input.attempt && inSpawnWindow) {
|
|
244
|
+
return writeArmed({ ...existing, armedAt: input.armedAt });
|
|
245
|
+
}
|
|
246
|
+
return writeArmed({
|
|
247
|
+
parentId: input.parentId,
|
|
248
|
+
attempt: input.attempt,
|
|
249
|
+
cause: 'transport',
|
|
250
|
+
armedAt: input.armedAt,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* What a stop's cancel attempt did. Three outcomes, not two, because the caller
|
|
256
|
+
* must distinguish "the retry has not spawned yet" (`cancelled`) from "the
|
|
257
|
+
* marker was already gone because the retry became durable" (`gone` — worth ONE
|
|
258
|
+
* lineage re-read, since the retry is now a normal record) from "the marker is
|
|
259
|
+
* there and could not be written" (`failed` — the retry may still prompt, which
|
|
260
|
+
* is an error the caller must report).
|
|
261
|
+
*/
|
|
262
|
+
export type CancelOutcome = 'cancelled' | 'gone' | 'failed';
|
|
263
|
+
|
|
264
|
+
/** Request the cancel on an armed retry. Never throws. */
|
|
265
|
+
export function cancelArmedRetry(parentId: string, attempt: number): CancelOutcome {
|
|
266
|
+
// Reclaim-on-read applies here too (B1): an unclaimed marker past the stale
|
|
267
|
+
// bound is `gone` for every attempt, and is unlinked rather than left to
|
|
268
|
+
// mislead the next reader. A CANCEL is never stale (rule 1).
|
|
269
|
+
const existing = readArmedRetry(parentId);
|
|
270
|
+
// A marker for a DIFFERENT attempt is not this retry's intent: treat it as
|
|
271
|
+
// gone for this attempt (the gate compares attempts too, so no cancel leaks).
|
|
272
|
+
if (!existing || existing.attempt !== attempt) return 'gone';
|
|
273
|
+
const cancelled: ArmedRetry = {
|
|
274
|
+
...existing,
|
|
275
|
+
cancelRequested: true,
|
|
276
|
+
cancelRequestedAt: new Date().toISOString(),
|
|
277
|
+
};
|
|
278
|
+
return writeArmed(cancelled) ? 'cancelled' : 'failed';
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* The PRE-PROMPT gate (issue #616's Q3 seam): has a stop cancelled the retry
|
|
283
|
+
* that is about to prompt? Total — an unreadable marker answers `false`, which
|
|
284
|
+
* degrades to the pre-#616 behaviour rather than blocking a legitimate retry.
|
|
285
|
+
*/
|
|
286
|
+
export function isRetryCancelRequested(parentId: string, attempt: number): boolean {
|
|
287
|
+
const armed = readArmedRetry(parentId);
|
|
288
|
+
return !!armed && armed.attempt === attempt && armed.cancelRequested === true;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Drop the marker for `parentId` when it names `attempt`. True when none is left. */
|
|
292
|
+
export function clearArmedRetry(parentId: string, attempt?: number): boolean {
|
|
293
|
+
const file = armedPath(parentId);
|
|
294
|
+
if (!file) return true;
|
|
295
|
+
const existing = readArmedRetry(parentId);
|
|
296
|
+
if (existing && attempt !== undefined && existing.attempt !== attempt) return false;
|
|
297
|
+
try {
|
|
298
|
+
fs.unlinkSync(file);
|
|
299
|
+
return true;
|
|
300
|
+
} catch (err) {
|
|
301
|
+
// Only ENOENT proves the desired end state (the same rule
|
|
302
|
+
// `clearInflightRun` follows).
|
|
303
|
+
return (err as NodeJS.ErrnoException).code === 'ENOENT';
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Is this file NOT a marker for the name it sits under? Total, and never throws.
|
|
309
|
+
*
|
|
310
|
+
* A file that cannot be parsed, does not have the marker shape, or names a
|
|
311
|
+
* different `parentId` can never be returned by `readArmedRetry(fileParentId)`:
|
|
312
|
+
* the path is derived from the id and the read additionally requires the parsed
|
|
313
|
+
* id to match. An UNREADABLE file (EACCES, a race with the unlink) is NOT orphan
|
|
314
|
+
* evidence — the sweep leaves what it cannot judge to the next boot.
|
|
315
|
+
*/
|
|
316
|
+
function isOrphanMarkerFile(fileParentId: string, file: string): boolean {
|
|
317
|
+
let text: string;
|
|
318
|
+
try {
|
|
319
|
+
text = fs.readFileSync(file, 'utf-8');
|
|
320
|
+
} catch {
|
|
321
|
+
return false;
|
|
322
|
+
}
|
|
323
|
+
let parsed: unknown;
|
|
324
|
+
try {
|
|
325
|
+
parsed = JSON.parse(text);
|
|
326
|
+
} catch {
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
return !isArmedRetry(parsed) || parsed.parentId !== fileParentId;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Issue #616 / review 624 (B1) — the BOOT SWEEP.
|
|
334
|
+
*
|
|
335
|
+
* Nothing outside a marker's own lifecycle clears it, so a process death between
|
|
336
|
+
* the arm write and the spawn leaves a file that every later stop of that
|
|
337
|
+
* dispatch would read as an armed retry. The readers already reclaim what they
|
|
338
|
+
* touch; this reclaims what no reader will touch for a while, so a stale intent
|
|
339
|
+
* does not sit on disk until the dispatch is stopped again.
|
|
340
|
+
*
|
|
341
|
+
* Cheap by construction: one `readdir` of a directory that holds at most one
|
|
342
|
+
* marker per in-flight retry, and the same total read every other caller uses.
|
|
343
|
+
*
|
|
344
|
+
* TWO KINDS OF RESIDUE (review 624 r2, N-r2-2):
|
|
345
|
+
*
|
|
346
|
+
* - a MARKER whose own read judges it stale — reclaimed by the read itself;
|
|
347
|
+
* - a FILE that is not a marker for the name it sits under (its `parentId`
|
|
348
|
+
* names another run, or it does not parse into a marker at all). Every
|
|
349
|
+
* reader is keyed by `parentId` and rejects the mismatch, so nothing can
|
|
350
|
+
* ever consume it — it is rubbish that would otherwise be re-scanned on
|
|
351
|
+
* every boot. Unlinking it drops no cancel any reader could honour.
|
|
352
|
+
*
|
|
353
|
+
* RULE (1) IS OBEYED: a well-formed, correctly-named marker with
|
|
354
|
+
* `cancelRequested === true` is never reclaimed here at any age — its gate may
|
|
355
|
+
* still be an unbounded wait away (see the module header).
|
|
356
|
+
*/
|
|
357
|
+
export function sweepStaleArmedRetries(): {
|
|
358
|
+
scanned: number;
|
|
359
|
+
reclaimed: number;
|
|
360
|
+
} {
|
|
361
|
+
let files: string[];
|
|
362
|
+
try {
|
|
363
|
+
files = fs.readdirSync(armedDir());
|
|
364
|
+
} catch {
|
|
365
|
+
return { scanned: 0, reclaimed: 0 };
|
|
366
|
+
}
|
|
367
|
+
let scanned = 0;
|
|
368
|
+
let reclaimed = 0;
|
|
369
|
+
for (const file of files) {
|
|
370
|
+
if (!file.endsWith('.json')) continue;
|
|
371
|
+
const parentId = file.slice(0, -'.json'.length);
|
|
372
|
+
const full = path.join(armedDir(), file);
|
|
373
|
+
scanned += 1;
|
|
374
|
+
if (isOrphanMarkerFile(parentId, full)) {
|
|
375
|
+
if (reclaimArmed(full)) reclaimed += 1;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
if (readArmedRetry(parentId) === null && !fs.existsSync(full)) {
|
|
379
|
+
reclaimed += 1;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return { scanned, reclaimed };
|
|
383
|
+
}
|
package/src/run-registry.ts
CHANGED
|
@@ -32,7 +32,15 @@
|
|
|
32
32
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
33
33
|
import * as fs from "node:fs";
|
|
34
34
|
import * as path from "node:path";
|
|
35
|
-
import {
|
|
35
|
+
import {
|
|
36
|
+
CUSTOM_ENTRY_TYPES,
|
|
37
|
+
RECOVERY_MODES,
|
|
38
|
+
RETRY_CAUSES,
|
|
39
|
+
type ProcessOwner,
|
|
40
|
+
type RecoveryMode,
|
|
41
|
+
type RetryCause,
|
|
42
|
+
type SubagentRun,
|
|
43
|
+
} from "./types";
|
|
36
44
|
import { assertSafeAgentId } from "./sanitize";
|
|
37
45
|
import { ensureOwnerOnlyDir } from "./store-permissions";
|
|
38
46
|
|
|
@@ -72,6 +80,13 @@ export interface InflightRun {
|
|
|
72
80
|
id: string;
|
|
73
81
|
dispatchId?: string;
|
|
74
82
|
attempt?: number;
|
|
83
|
+
/**
|
|
84
|
+
* Issue #616: why this attempt exists (`transport` auto-retry vs a manual
|
|
85
|
+
* `retryRunId` retry). Mirrored from the run record so a stop that must
|
|
86
|
+
* resolve a retry from the registry alone (no agent record yet) can still
|
|
87
|
+
* scope itself. Absent = unknown, never `transport`.
|
|
88
|
+
*/
|
|
89
|
+
retryCause?: RetryCause;
|
|
75
90
|
kind: InflightRunKind;
|
|
76
91
|
owner?: ProcessOwner;
|
|
77
92
|
childMarker?: string;
|
|
@@ -114,6 +129,7 @@ export interface InflightRunInput {
|
|
|
114
129
|
id: string;
|
|
115
130
|
dispatchId?: string;
|
|
116
131
|
attempt?: number;
|
|
132
|
+
retryCause?: RetryCause;
|
|
117
133
|
kind: InflightRunKind;
|
|
118
134
|
owner?: ProcessOwner;
|
|
119
135
|
childMarker?: string;
|
|
@@ -218,6 +234,13 @@ function normalizeEnrichment(value: InflightRun, raw: Record<string, unknown>):
|
|
|
218
234
|
} else {
|
|
219
235
|
delete entry.originalParams;
|
|
220
236
|
}
|
|
237
|
+
// Issue #616: same lenient rule — a cause we cannot trust is DROPPED (absent ⇒
|
|
238
|
+
// unknown ⇒ never auto-stopped), never coerced to the stop-scoped value.
|
|
239
|
+
if (typeof raw.retryCause === "string" && (RETRY_CAUSES as readonly string[]).includes(raw.retryCause)) {
|
|
240
|
+
entry.retryCause = raw.retryCause as RetryCause;
|
|
241
|
+
} else {
|
|
242
|
+
delete entry.retryCause;
|
|
243
|
+
}
|
|
221
244
|
// Issue #447: keep the tri-state intact and treat anything else as LEGACY
|
|
222
245
|
// (absent) rather than inventing a fourth state. A mistyped marker must
|
|
223
246
|
// never downgrade a real run into the never-started class.
|
|
@@ -267,6 +290,7 @@ function mergeInput(base: InflightRun, input: InflightRunInput): InflightRun {
|
|
|
267
290
|
const next: InflightRun = { ...base, id: input.id, kind: input.kind };
|
|
268
291
|
if (input.dispatchId !== undefined) next.dispatchId = input.dispatchId;
|
|
269
292
|
if (input.attempt !== undefined) next.attempt = input.attempt;
|
|
293
|
+
if (input.retryCause !== undefined) next.retryCause = input.retryCause;
|
|
270
294
|
if (input.recoveryPosture !== undefined) next.recoveryPosture = input.recoveryPosture;
|
|
271
295
|
if (input.owner !== undefined) next.owner = input.owner;
|
|
272
296
|
if (input.childMarker !== undefined) next.childMarker = input.childMarker;
|
|
@@ -425,6 +449,7 @@ function toRegistryInput(run: SubagentRun, kind: InflightRunKind): InflightRunIn
|
|
|
425
449
|
id: run.id,
|
|
426
450
|
dispatchId: run.dispatchId,
|
|
427
451
|
attempt: run.attempt,
|
|
452
|
+
retryCause: run.retryCause,
|
|
428
453
|
kind,
|
|
429
454
|
recoveryPosture: run.recoveryPosture,
|
|
430
455
|
owner: run.owner,
|