opencode-model-router 2.10.0 → 2.11.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/CHANGELOG.md +306 -0
- package/README.md +3 -2
- package/package.json +8 -1
- package/src/compat/background.ts +5 -0
- package/src/compat/session-lookup.ts +21 -0
- package/src/compat/v2-hooks.ts +256 -88
- package/src/compat/v2-observations.ts +1 -0
- package/src/compat/v2-vocabulary.ts +14 -0
- package/src/executor/create.ts +3 -0
- package/src/executor/git.ts +110 -26
- package/src/executor/integrate/checks.ts +29 -11
- package/src/executor/integrate/queue.ts +95 -13
- package/src/executor/ledger.ts +16 -12
- package/src/executor/lfs-restore.ts +492 -0
- package/src/executor/paths.ts +7 -2
- package/src/executor/recovery.ts +2 -1
- package/src/executor/runtime.ts +1010 -226
- package/src/executor/slots/pool.ts +120 -19
- package/src/executor/slots/provision.ts +111 -23
- package/src/executor/slots/root.ts +81 -0
- package/src/executor/types.ts +28 -2
- package/src/executor/unattended.ts +6 -1
- package/src/executor/verify-trees.ts +507 -0
- package/src/guard/enforce.ts +2 -1
- package/src/guard/fingerprint.ts +9 -0
- package/src/guard/guards.ts +7 -1
- package/src/index.ts +107 -27
- package/src/router/answer-dedup.ts +198 -0
- package/src/router/common-dir.ts +241 -0
- package/src/router/config.ts +71 -12
- package/src/router/diff-handles.ts +322 -0
- package/src/router/diff-summary.ts +318 -0
- package/src/router/git-metadata-guard.ts +144 -7
- package/src/router/git-tools.ts +930 -73
- package/src/router/role-agents.ts +100 -36
- package/src/router/run-summary.ts +253 -0
- package/src/router/run-tools.ts +145 -23
- package/src/router/sessions.ts +14 -1
- package/src/routing/classify/rules.ts +93 -14
- package/src/routing/wire/hint.ts +9 -2
- package/src/v2.ts +3 -1
- package/src/verify/exec.ts +454 -2
- package/src/verify/plan-task.ts +86 -26
- package/src/verify/runner.ts +14 -6
- package/src/verify/tree.ts +5 -1
- package/src/verify/types.ts +44 -0
- package/src/verify/wiring.ts +87 -10
package/src/executor/types.ts
CHANGED
|
@@ -218,6 +218,12 @@ export interface SlotRecord {
|
|
|
218
218
|
manifests: Record<string, string>;
|
|
219
219
|
createdAt: IsoTime;
|
|
220
220
|
updatedAt: IsoTime;
|
|
221
|
+
/**
|
|
222
|
+
* #187: written by the gc on a `retired` marker once its unsaved-work check passed (or the caller saved the slot) and it
|
|
223
|
+
* starts deleting the slot. A gc interrupted there (EBUSY) finishes the removal later without that check, which a
|
|
224
|
+
* half-deleted slot could never pass again. Absent on every other marker (a broken slot retired by the pool included).
|
|
225
|
+
*/
|
|
226
|
+
removing?: true;
|
|
221
227
|
}
|
|
222
228
|
|
|
223
229
|
export type IntegrationStep =
|
|
@@ -1450,11 +1456,20 @@ export interface SlotAcquisition extends SlotLease {
|
|
|
1450
1456
|
readonly verifiedResetBase?: string;
|
|
1451
1457
|
}
|
|
1452
1458
|
|
|
1459
|
+
/** Options of one `SlotPool.acquire`. */
|
|
1460
|
+
export interface SlotAcquireOptions {
|
|
1461
|
+
/**
|
|
1462
|
+
* Recovery-R1-m1 (#190): aborts the claim only while it is still queued (behind earlier claims or its base lookup); it then
|
|
1463
|
+
* rejects with E_PLAN_STATE and leases nothing. A claim that started (claiming, provisioning, reset) runs to its end.
|
|
1464
|
+
*/
|
|
1465
|
+
signal?: AbortSignal;
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1453
1468
|
/** Pool of provisioned git worktrees (2.4). */
|
|
1454
1469
|
export interface SlotPool {
|
|
1455
1470
|
/** Never waits: a reset, provisioned slot leased to `owner`, or E_SLOT_UNAVAILABLE. Concurrent calls are claimed in call order; never double-leases.
|
|
1456
1471
|
* A task that already holds a slot gets the same slot back. err E_SLOT_UNAVAILABLE, E_PROVISION, E_SLOT_BROKEN */
|
|
1457
|
-
acquire(planId: PlanId, owner: string, baseCommit: string): Promise<SlotAcquisition>;
|
|
1472
|
+
acquire(planId: PlanId, owner: string, baseCommit: string, opts?: SlotAcquireOptions): Promise<SlotAcquisition>;
|
|
1458
1473
|
acquireSpecial(planId: PlanId, kind: "integration" | "ci"): Promise<SlotAcquisition>;
|
|
1459
1474
|
/** Checkout detached + clean tracked; re-provision on manifest drift. */
|
|
1460
1475
|
reset(slot: string, commit: string): Promise<void>;
|
|
@@ -1975,6 +1990,11 @@ export interface ProcOpts {
|
|
|
1975
1990
|
/** No shell; a non-zero exit is a result; throws only spawn/ETIMEDOUT/EOUTPUT. Preparation adapters preserve `service`. */
|
|
1976
1991
|
export interface GitRunner {
|
|
1977
1992
|
run(args: readonly string[], o: ProcOpts): Promise<ProcessResult>;
|
|
1993
|
+
/**
|
|
1994
|
+
* #208: restores, in the work tree the global options `prefix` name, the LFS files whose object is in the local LFS store
|
|
1995
|
+
* (the production runner, executor/git.ts `withRepositoryDrivers`). Never throws; a problem is a warning. Absent: no restore.
|
|
1996
|
+
*/
|
|
1997
|
+
restoreLocalLfs?(prefix: readonly string[], cwd: string, o: { timeoutMs: number; signal?: AbortSignal }): Promise<void>;
|
|
1978
1998
|
}
|
|
1979
1999
|
/** Never a shell. `pid`/`hostname`/`isAlive` serve lock staleness (2.2.2.e). */
|
|
1980
2000
|
export interface Spawner {
|
|
@@ -1987,6 +2007,9 @@ export interface FsStat {
|
|
|
1987
2007
|
kind: "file" | "dir" | "symlink" | "junction" | "other";
|
|
1988
2008
|
size: number;
|
|
1989
2009
|
mtimeMs: number;
|
|
2010
|
+
/** POSIX only (#192): the owner's uid and the mode bits; absent on win32 and from ports that do not know them. */
|
|
2011
|
+
uid?: number;
|
|
2012
|
+
mode?: number;
|
|
1990
2013
|
}
|
|
1991
2014
|
/** Errors carry `.code` (ENOENT, EEXIST, EPERM, EBUSY...); the 2 s EPERM/EBUSY retry belongs to the caller. */
|
|
1992
2015
|
export interface FileSystem {
|
|
@@ -1995,11 +2018,14 @@ export interface FileSystem {
|
|
|
1995
2018
|
appendText(p: string, data: string, o: { fsync: boolean }): Promise<void>;
|
|
1996
2019
|
rename(a: string, b: string): Promise<void>;
|
|
1997
2020
|
rm(p: string, o: { recursive: boolean }): Promise<void>;
|
|
1998
|
-
|
|
2021
|
+
/** `o.mode`: the permission bits of the created directories (POSIX; callers pass none on win32). */
|
|
2022
|
+
mkdir(p: string, o?: { mode?: number }): Promise<void>;
|
|
1999
2023
|
readdir(p: string): Promise<string[]>;
|
|
2000
2024
|
lstat(p: string): Promise<FsStat | null>;
|
|
2001
2025
|
realpath(p: string): Promise<string>;
|
|
2002
2026
|
fsyncDir(p: string): Promise<void>;
|
|
2027
|
+
/** POSIX only (#192): set the permission bits of `p` (a private slots root or lock directory). */
|
|
2028
|
+
chmod?(p: string, mode: number): Promise<void>;
|
|
2003
2029
|
}
|
|
2004
2030
|
|
|
2005
2031
|
export interface HostSessionContext {
|
|
@@ -113,10 +113,15 @@ const NOT_COMMIT_FAILED_STATES: readonly TaskState[] =
|
|
|
113
113
|
* with no verdict was followed by a retry, which only `commit-failed` allows (`completed` leaves for `failed` only
|
|
114
114
|
* that way). The latest one counts whenever the task is outside `NOT_COMMIT_FAILED_STATES` (QA-4.2-19): `failed`, or
|
|
115
115
|
* the `ready`/`parked`/`blocked` the retry decision moves it to right after the feed, so the sample outlives the move.
|
|
116
|
+
* QA-4.2-38 (#188): `cancelled` (abort) follows `completed`/`verifying` (no commit failure) or the states above. A
|
|
117
|
+
* succeeded, verdict-less attempt gets a context only in the commit-failed batch (or the park/answer that follows it),
|
|
118
|
+
* so a cancelled task whose latest such attempt has one keeps its commit failure in the breaker window.
|
|
116
119
|
*/
|
|
117
120
|
export function isCommitFailure(t: Readonly<LedgerV1["tasks"][string]>, a: Attempt): boolean {
|
|
118
121
|
if (a.outcome !== "succeeded" || a.verdict !== null) return false;
|
|
119
|
-
|
|
122
|
+
if (a !== t.attempts[t.attempts.length - 1]) return true;
|
|
123
|
+
if (t.state === "cancelled") return a.context !== "";
|
|
124
|
+
return !NOT_COMMIT_FAILED_STATES.includes(t.state);
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
/**
|
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
// #189 R2-pre-2: the process journal of plan-task verifications and the activation sweep of a dead server's trees.
|
|
2
|
+
//
|
|
3
|
+
// A plan-task verification records every root its check seams spawn (verify/exec.ts `onSpawn`/`onExit`/`onSettle`) in one
|
|
4
|
+
// file per attempt, `<executor home>/verify-trees/<planId>/<taskId>#<n>.json`, together with the identity of the server that
|
|
5
|
+
// ran it (pid, token, host name, process start and, on POSIX, its /proc start ticks), the platform and the slot. A server
|
|
6
|
+
// that dies by a signal skips exec.ts's exit hook, so those trees can outlive it and overlap the re-verification of the next
|
|
7
|
+
// activation (its clean, ports, locks). At activation the runtime sweeps the plan's files once: every file whose server is
|
|
8
|
+
// dead (and is not this process) goes to ONE `killRecordedTrees` call, bounded as a whole; a file whose trees are proven
|
|
9
|
+
// gone is removed, any other is reported so the runtime parks the slot's recovered work. A record that fails validation
|
|
10
|
+
// is never acted on.
|
|
11
|
+
import { mkdirSync, readFileSync, realpathSync, renameSync, rmSync, utimesSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { readdir, readFile, rm, stat } from "node:fs/promises";
|
|
13
|
+
import { dirname, join, resolve } from "node:path";
|
|
14
|
+
import { killRecordedTrees, readProcStart, type RecordedRoot, type RecordedTreeGroup, type RecordedTreeKill, type RecordedTreeKillInput } from "../verify/exec";
|
|
15
|
+
import type { ProcessJournal, SpawnedProcess } from "../verify/types";
|
|
16
|
+
import { assertPlanId, VERIFY_TREES_DIRNAME } from "./paths";
|
|
17
|
+
import type { ProcessIdentity } from "./process-identity";
|
|
18
|
+
import { SLOT_NAME_PATTERN } from "./slots/pool";
|
|
19
|
+
import { isTaskId, type PlanId, type TaskId } from "./types";
|
|
20
|
+
|
|
21
|
+
export { VERIFY_TREES_DIRNAME };
|
|
22
|
+
|
|
23
|
+
/** M2: the bound of one whole activation sweep (every journal of the plan). */
|
|
24
|
+
export const VERIFY_TREE_SWEEP_MS = 60_000;
|
|
25
|
+
/**
|
|
26
|
+
* While a journal has roots in flight its server touches the file's mtime this often (the heartbeat). A sweep takes the
|
|
27
|
+
* mtime plus this interval plus JOURNAL_HEARTBEAT_SLACK_MS as the newest time the server was alive: nothing recorded a
|
|
28
|
+
* root past it, so a dead root's child created later may belong to a later owner of the root's pid (reported, never killed).
|
|
29
|
+
*/
|
|
30
|
+
export const JOURNAL_HEARTBEAT_MS = 2000;
|
|
31
|
+
/** How late a heartbeat may land (a busy event loop, coarse file times) before the server counts as gone. */
|
|
32
|
+
export const JOURNAL_HEARTBEAT_SLACK_MS = 3000;
|
|
33
|
+
|
|
34
|
+
/** One journal file. */
|
|
35
|
+
export interface VerifyTreeRecord {
|
|
36
|
+
readonly version: 1;
|
|
37
|
+
/** `process.platform` of the server: a record of another system (same host name, other pid space) is never acted on. */
|
|
38
|
+
readonly platform: string;
|
|
39
|
+
/** The server that ran the verification; `startedAtMs` is its process start, `startTicks` its POSIX /proc start. */
|
|
40
|
+
readonly server: {
|
|
41
|
+
readonly pid: number; readonly token: string; readonly hostname: string; readonly startedAtMs: number; readonly startTicks: number | null;
|
|
42
|
+
};
|
|
43
|
+
/** The server's heartbeat interval (JOURNAL_HEARTBEAT_MS): its mtime is touched this often while roots are in flight. */
|
|
44
|
+
readonly heartbeatMs: number;
|
|
45
|
+
readonly planId: PlanId;
|
|
46
|
+
readonly taskId: TaskId;
|
|
47
|
+
readonly n: number;
|
|
48
|
+
readonly slot: { readonly name: string; readonly path: string };
|
|
49
|
+
/** The roots still running when the file was last written. */
|
|
50
|
+
readonly roots: readonly RecordedRoot[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The trees of one journal file a sweep could not prove gone (or could not look at). */
|
|
54
|
+
export interface AliveVerifyTree {
|
|
55
|
+
/** The slot name; "" when it is not known (a journal that could not be read or was refused, or no journal at all). */
|
|
56
|
+
readonly slot: string;
|
|
57
|
+
/** The attempt's task; null when not even the file name gives it (then every recovered work of the plan waits). */
|
|
58
|
+
readonly taskId: TaskId | null;
|
|
59
|
+
readonly n: number | null;
|
|
60
|
+
readonly serverPid: number | null;
|
|
61
|
+
/** What may still run (the recorded roots when nothing could be checked). */
|
|
62
|
+
readonly pids: readonly number[];
|
|
63
|
+
/**
|
|
64
|
+
* The part of `pids` started where a recorded root's child would be, but after the recorded run could still start
|
|
65
|
+
* processes: maybe the user's own (an editor or a shell opened on the slot). Present only when non-empty.
|
|
66
|
+
*/
|
|
67
|
+
readonly late?: readonly number[];
|
|
68
|
+
readonly reason: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A journal file the sweep refused: never acted on. */
|
|
72
|
+
export interface RefusedVerifyTree {
|
|
73
|
+
readonly file: string;
|
|
74
|
+
readonly reason: string;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface VerifyTreeSweep {
|
|
78
|
+
readonly alive: readonly AliveVerifyTree[];
|
|
79
|
+
/** Processes the sweep ended. */
|
|
80
|
+
readonly killed: readonly number[];
|
|
81
|
+
/** Files of dead servers whose trees were proven gone; each was removed. */
|
|
82
|
+
readonly cleared: number;
|
|
83
|
+
readonly refused: readonly RefusedVerifyTree[];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface VerifyTreeSweepOptions {
|
|
87
|
+
/** L8: the plan's slots directory; a journal's slot must be the pool's path of a slot in it. */
|
|
88
|
+
readonly slotsDir: string;
|
|
89
|
+
/** M2: aborts the sweep (the attachment closing, dispose): what it has not confirmed parks. */
|
|
90
|
+
readonly signal?: AbortSignal;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export interface VerifyTrees {
|
|
94
|
+
/** The journal of attempt `n` of `taskId`, verified in `slot`. Throws on an id that is not a valid path segment. */
|
|
95
|
+
journal(planId: PlanId, taskId: TaskId, n: number, slot: { readonly name: string; readonly path: string }): ProcessJournal;
|
|
96
|
+
/** Sweeps the plan's journal files left by dead servers. Never rejects. */
|
|
97
|
+
sweep(planId: PlanId, opts: VerifyTreeSweepOptions): Promise<VerifyTreeSweep>;
|
|
98
|
+
/** Removes the plan's journal directory (purge). Never rejects. */
|
|
99
|
+
purge(planId: PlanId): Promise<void>;
|
|
100
|
+
/** Stops the heartbeat (the assembly's dispose); the journals stay for the next activation's sweep. */
|
|
101
|
+
dispose?(): void;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface VerifyTreesDeps {
|
|
105
|
+
/** The executor home. */
|
|
106
|
+
home: string;
|
|
107
|
+
self: ProcessIdentity;
|
|
108
|
+
/** This process's start (ms epoch): the newest creation time of a dead root's child. Default: from process.uptime(). */
|
|
109
|
+
selfStartedAtMs?: number;
|
|
110
|
+
/** Same-host pid liveness (the launcher-liveness check, recovery.ts). */
|
|
111
|
+
isAlive(pid: number): boolean;
|
|
112
|
+
/** Test seam; default `killRecordedTrees`. */
|
|
113
|
+
kill?(input: RecordedTreeKillInput): Promise<RecordedTreeKill>;
|
|
114
|
+
log?(level: "info" | "warn" | "error", msg: string, detail?: string): void;
|
|
115
|
+
/** Test seams: the platform recorded and compared, and the POSIX /proc reader. */
|
|
116
|
+
platform?: NodeJS.Platform;
|
|
117
|
+
readProc?(path: string): string;
|
|
118
|
+
/** M2: the bound of one sweep; default VERIFY_TREE_SWEEP_MS. */
|
|
119
|
+
sweepTimeoutMs?: number;
|
|
120
|
+
/** Test seam: the heartbeat interval; default JOURNAL_HEARTBEAT_MS. */
|
|
121
|
+
heartbeatMs?: number;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function errorText(e: unknown): string {
|
|
125
|
+
return e instanceof Error ? e.message : String(e);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function errorCode(e: unknown): string | undefined {
|
|
129
|
+
const code: unknown = typeof e === "object" && e !== null ? (e as { code?: unknown }).code : undefined;
|
|
130
|
+
return typeof code === "string" ? code : undefined;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const isId = (n: unknown): n is number => typeof n === "number" && Number.isSafeInteger(n) && n > 0;
|
|
134
|
+
const isText = (s: unknown): s is string => typeof s === "string" && s !== "";
|
|
135
|
+
const isTime = (n: unknown): n is number => typeof n === "number" && Number.isFinite(n) && n >= 0;
|
|
136
|
+
const isTicks = (n: unknown): n is number | null => n === null || (typeof n === "number" && Number.isSafeInteger(n) && n >= 0);
|
|
137
|
+
|
|
138
|
+
function parseRoot(v: unknown): RecordedRoot | null {
|
|
139
|
+
if (typeof v !== "object" || v === null) return null;
|
|
140
|
+
const r = v as Record<string, unknown>;
|
|
141
|
+
if (!isId(r.pid) || typeof r.startedAtMs !== "number" || !Number.isFinite(r.startedAtMs) || !(r.pgid === null || isId(r.pgid))) return null;
|
|
142
|
+
if (typeof r.command !== "string" || !(r.deadlineMs === null || isTime(r.deadlineMs)) || !(r.exitedAtMs === null || isTime(r.exitedAtMs))) return null;
|
|
143
|
+
if (!isTicks(r.startTicks)) return null;
|
|
144
|
+
return { pid: r.pid, startedAtMs: r.startedAtMs, pgid: r.pgid, command: r.command, deadlineMs: r.deadlineMs, exitedAtMs: r.exitedAtMs, startTicks: r.startTicks };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** The record in `text`, or null when it is not a well-formed journal of `planId` (shape only; see the sweep's checks). */
|
|
148
|
+
export function parseVerifyTreeRecord(text: string, planId: PlanId): VerifyTreeRecord | null {
|
|
149
|
+
let v: unknown;
|
|
150
|
+
try {
|
|
151
|
+
v = JSON.parse(text);
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
if (typeof v !== "object" || v === null) return null;
|
|
156
|
+
const o = v as Record<string, unknown>;
|
|
157
|
+
const server = typeof o.server === "object" && o.server !== null ? (o.server as Record<string, unknown>) : null;
|
|
158
|
+
const slot = typeof o.slot === "object" && o.slot !== null ? (o.slot as Record<string, unknown>) : null;
|
|
159
|
+
if (o.version !== 1 || !isText(o.platform) || server === null || slot === null || o.planId !== planId || !isTaskId(o.taskId) || !isId(o.n)) return null;
|
|
160
|
+
if (typeof o.heartbeatMs !== "number" || !Number.isFinite(o.heartbeatMs) || o.heartbeatMs <= 0) return null;
|
|
161
|
+
if (!isId(server.pid) || !isText(server.token) || typeof server.hostname !== "string" || !isTicks(server.startTicks)) return null;
|
|
162
|
+
if (typeof server.startedAtMs !== "number" || !Number.isFinite(server.startedAtMs)) return null;
|
|
163
|
+
if (!isText(slot.name) || !isText(slot.path) || !Array.isArray(o.roots)) return null;
|
|
164
|
+
const roots: RecordedRoot[] = [];
|
|
165
|
+
for (const raw of o.roots) {
|
|
166
|
+
const root = parseRoot(raw);
|
|
167
|
+
if (root === null) return null;
|
|
168
|
+
roots.push(root);
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
version: 1,
|
|
172
|
+
platform: o.platform,
|
|
173
|
+
server: { pid: server.pid, token: server.token, hostname: server.hostname, startedAtMs: server.startedAtMs, startTicks: server.startTicks },
|
|
174
|
+
heartbeatMs: o.heartbeatMs,
|
|
175
|
+
planId, taskId: o.taskId, n: o.n,
|
|
176
|
+
slot: { name: slot.name, path: slot.path },
|
|
177
|
+
roots,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The attempt a journal file name gives (`<taskId>#<n>.json`), or null. */
|
|
182
|
+
function attemptOfFile(name: string): { taskId: TaskId; n: number } | null {
|
|
183
|
+
const m = /^(.+)#(\d+)\.json$/.exec(name);
|
|
184
|
+
const taskId = m?.[1];
|
|
185
|
+
const n = Number(m?.[2]);
|
|
186
|
+
return taskId !== undefined && isTaskId(taskId) && Number.isSafeInteger(n) && n >= 1 ? { taskId, n } : null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
interface JournalFile {
|
|
190
|
+
readonly header: Omit<VerifyTreeRecord, "roots">;
|
|
191
|
+
readonly roots: Map<string, RecordedRoot>;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function createVerifyTrees(d: VerifyTreesDeps): VerifyTrees {
|
|
195
|
+
const startedAtMs = d.selfStartedAtMs ?? Math.floor(Date.now() - process.uptime() * 1000);
|
|
196
|
+
const kill = d.kill ?? ((input: RecordedTreeKillInput) => killRecordedTrees(input));
|
|
197
|
+
const platform = d.platform ?? process.platform;
|
|
198
|
+
const readProc = d.readProc ?? ((path: string) => readFileSync(path, "utf8"));
|
|
199
|
+
/** L5: POSIX start ticks of `pid` (null on Windows or when /proc cannot tell). */
|
|
200
|
+
const startTicksOf = (pid: number): number | null => (platform === "win32" ? null : readProcStart(readProc, pid)?.ticks ?? null);
|
|
201
|
+
const serverStartTicks = startTicksOf(process.pid);
|
|
202
|
+
/** This process's journals with roots in flight, by file path (several journal objects of one attempt share one entry). */
|
|
203
|
+
const files = new Map<string, JournalFile>();
|
|
204
|
+
/** Paths whose write failure was already logged (once per file). */
|
|
205
|
+
const warned = new Set<string>();
|
|
206
|
+
const log = (level: "info" | "warn" | "error", msg: string, detail?: string): void => {
|
|
207
|
+
try { d.log?.(level, msg, detail); } catch { /* logging never fails a verification or a sweep */ }
|
|
208
|
+
};
|
|
209
|
+
const dirOf = (planId: PlanId): string => join(d.home, VERIFY_TREES_DIRNAME, assertPlanId(planId));
|
|
210
|
+
const heartbeatMs = d.heartbeatMs ?? JOURNAL_HEARTBEAT_MS;
|
|
211
|
+
/** The heartbeat (re-review 1): one unref'd timer touching every journal with roots in flight; none without them. */
|
|
212
|
+
let beat: ReturnType<typeof setInterval> | undefined;
|
|
213
|
+
let disposed = false;
|
|
214
|
+
const beatOnce = (): void => {
|
|
215
|
+
const now = new Date();
|
|
216
|
+
for (const [path, file] of files) {
|
|
217
|
+
if (file.roots.size === 0) continue;
|
|
218
|
+
try {
|
|
219
|
+
utimesSync(path, now, now);
|
|
220
|
+
} catch {
|
|
221
|
+
// Gone or unwritable: the next write of the journal recreates it (and logs a failure).
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
/** Starts the heartbeat while a journal has roots in flight, and stops it once none has (or after dispose). */
|
|
226
|
+
const syncBeat = (): void => {
|
|
227
|
+
const needed = !disposed && [...files.values()].some((f) => f.roots.size > 0);
|
|
228
|
+
if (needed && beat === undefined) {
|
|
229
|
+
beat = setInterval(beatOnce, heartbeatMs);
|
|
230
|
+
beat.unref?.();
|
|
231
|
+
} else if (!needed && beat !== undefined) {
|
|
232
|
+
clearInterval(beat);
|
|
233
|
+
beat = undefined;
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
/** Rewrites (atomically) or removes the file of `path`; the entry goes only once its file did. Never throws. */
|
|
238
|
+
const write = (path: string, file: JournalFile): void => {
|
|
239
|
+
try {
|
|
240
|
+
if (file.roots.size === 0) {
|
|
241
|
+
rmSync(path, { force: true });
|
|
242
|
+
files.delete(path);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
246
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
247
|
+
writeFileSync(tmp, JSON.stringify({ ...file.header, roots: [...file.roots.values()] }));
|
|
248
|
+
renameSync(tmp, path);
|
|
249
|
+
} catch (e) {
|
|
250
|
+
if (warned.has(path)) return;
|
|
251
|
+
warned.add(path);
|
|
252
|
+
log("warn", `the verification process journal ${path} could not be written; a restart cannot end what this verification leaves running`, errorText(e));
|
|
253
|
+
} finally {
|
|
254
|
+
syncBeat();
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
const remove = async (path: string): Promise<void> => {
|
|
259
|
+
try {
|
|
260
|
+
await rm(path, { force: true });
|
|
261
|
+
} catch (e) {
|
|
262
|
+
log("warn", `the verification process journal ${path} could not be removed; the next sweep removes it`, errorText(e));
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
/** One spelling of a path for comparison: resolved, case-folded on Windows, else the native real path of both. */
|
|
267
|
+
const samePath = (a: string, b: string): boolean => {
|
|
268
|
+
const fold = (p: string): string => (platform === "win32" ? resolve(p).toLowerCase() : resolve(p));
|
|
269
|
+
if (fold(a) === fold(b)) return true;
|
|
270
|
+
try {
|
|
271
|
+
return fold(realpathSync.native(a)) === fold(realpathSync.native(b));
|
|
272
|
+
} catch {
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
/** L8: why a well-formed record must not be acted on, and whether its attempt's recovered work waits (null: accepted). */
|
|
278
|
+
const refusalOf = (rec: VerifyTreeRecord, file: string, slotsDir: string): { reason: string; park: boolean } | null => {
|
|
279
|
+
if (rec.platform !== platform) return { reason: `recorded on ${rec.platform}, swept on ${platform}`, park: false };
|
|
280
|
+
const expected = `${rec.taskId}#${rec.n}.json`;
|
|
281
|
+
if (file !== expected) return { reason: `the file name is not ${expected}`, park: true };
|
|
282
|
+
const slotPath = join(slotsDir, rec.slot.name);
|
|
283
|
+
const path = resolve(rec.slot.path);
|
|
284
|
+
if (!SLOT_NAME_PATTERN.test(rec.slot.name) || dirname(path) === path || !samePath(path, slotPath)) {
|
|
285
|
+
return { reason: `the slot path is not the pool's path of slot ${rec.slot.name} in ${slotsDir}: ${rec.slot.path}`, park: true };
|
|
286
|
+
}
|
|
287
|
+
const early = rec.roots.find((r) => r.startedAtMs < rec.server.startedAtMs);
|
|
288
|
+
if (early !== undefined) return { reason: `the server started after its root ${early.pid}`, park: true };
|
|
289
|
+
return null;
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
return {
|
|
293
|
+
journal(planId, taskId, n, slot) {
|
|
294
|
+
if (!isTaskId(taskId) || !isId(n)) throw new Error(`invalid verification journal id ${JSON.stringify(`${taskId}#${n}`)}`);
|
|
295
|
+
const path = join(dirOf(planId), `${taskId}#${n}.json`);
|
|
296
|
+
const header: JournalFile["header"] = {
|
|
297
|
+
version: 1,
|
|
298
|
+
platform,
|
|
299
|
+
server: { pid: d.self.pid, token: d.self.token, hostname: d.self.hostname, startedAtMs, startTicks: serverStartTicks },
|
|
300
|
+
heartbeatMs,
|
|
301
|
+
planId, taskId, n,
|
|
302
|
+
slot: { name: slot.name, path: slot.path },
|
|
303
|
+
};
|
|
304
|
+
const keyOf = (root: SpawnedProcess): string => `${root.pid}:${root.startedAtMs}`;
|
|
305
|
+
return {
|
|
306
|
+
spawned(root, command) {
|
|
307
|
+
const file = files.get(path) ?? { header, roots: new Map<string, RecordedRoot>() };
|
|
308
|
+
files.set(path, file);
|
|
309
|
+
file.roots.set(keyOf(root), {
|
|
310
|
+
pid: root.pid, startedAtMs: root.startedAtMs, pgid: root.pgid, command, deadlineMs: root.deadlineMs, exitedAtMs: null,
|
|
311
|
+
startTicks: startTicksOf(root.pid),
|
|
312
|
+
});
|
|
313
|
+
write(path, file);
|
|
314
|
+
},
|
|
315
|
+
exited(root, exitedAtMs) {
|
|
316
|
+
const file = files.get(path);
|
|
317
|
+
const known = file?.roots.get(keyOf(root));
|
|
318
|
+
if (file === undefined || known === undefined) return;
|
|
319
|
+
file.roots.set(keyOf(root), { ...known, exitedAtMs });
|
|
320
|
+
write(path, file);
|
|
321
|
+
},
|
|
322
|
+
settled(root) {
|
|
323
|
+
const file = files.get(path);
|
|
324
|
+
if (file === undefined || !file.roots.delete(keyOf(root))) return;
|
|
325
|
+
write(path, file);
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
async sweep(planId, opts) {
|
|
331
|
+
const alive: AliveVerifyTree[] = [];
|
|
332
|
+
const killed: number[] = [];
|
|
333
|
+
const refused: RefusedVerifyTree[] = [];
|
|
334
|
+
let cleared = 0;
|
|
335
|
+
let dir: string;
|
|
336
|
+
let names: string[];
|
|
337
|
+
try {
|
|
338
|
+
dir = dirOf(planId);
|
|
339
|
+
names = await readdir(dir);
|
|
340
|
+
} catch (e) {
|
|
341
|
+
if (errorCode(e) === "ENOENT") return { alive, killed, cleared, refused };
|
|
342
|
+
// Fail closed: nothing proves the trees gone, so every recovered verification of the plan waits.
|
|
343
|
+
alive.push({ slot: "", taskId: null, n: null, serverPid: null, pids: [], reason: `the journal directory could not be read: ${errorText(e)}` });
|
|
344
|
+
return { alive, killed, cleared, refused };
|
|
345
|
+
}
|
|
346
|
+
const candidates: Array<{ path: string; record: VerifyTreeRecord; group: RecordedTreeGroup }> = [];
|
|
347
|
+
for (const name of names.sort()) {
|
|
348
|
+
if (!name.endsWith(".json")) continue;
|
|
349
|
+
const path = join(dir, name);
|
|
350
|
+
// This process's own verification is still running: never swept.
|
|
351
|
+
if (files.has(path)) continue;
|
|
352
|
+
const attempt = attemptOfFile(name);
|
|
353
|
+
let text: string;
|
|
354
|
+
try {
|
|
355
|
+
text = await readFile(path, "utf8");
|
|
356
|
+
} catch (e) {
|
|
357
|
+
if (errorCode(e) === "ENOENT") continue;
|
|
358
|
+
// M3: a journal that cannot be read now (EBUSY, EPERM, EACCES) is kept, and its attempt's work waits.
|
|
359
|
+
alive.push({ slot: "", taskId: attempt?.taskId ?? null, n: attempt?.n ?? null, serverPid: null, pids: [],
|
|
360
|
+
reason: `the journal ${name} could not be read: ${errorText(e)}` });
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
// Re-review 1: the server's last heartbeat (the journal's mtime); unknown when the file vanished meanwhile.
|
|
364
|
+
let beatAtMs: number | null = null;
|
|
365
|
+
try {
|
|
366
|
+
beatAtMs = (await stat(path)).mtimeMs;
|
|
367
|
+
} catch {
|
|
368
|
+
beatAtMs = null;
|
|
369
|
+
}
|
|
370
|
+
const record = parseVerifyTreeRecord(text, planId);
|
|
371
|
+
if (record === null) {
|
|
372
|
+
// Written atomically, so only a foreign or damaged file: it names no process this sweep could prove its own.
|
|
373
|
+
refused.push({ file: name, reason: "not a journal record; removed" });
|
|
374
|
+
log("warn", `the verification process journal ${path} is not a journal record; removed`);
|
|
375
|
+
await remove(path);
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const server = record.server;
|
|
379
|
+
// Another host's journal (a shared repository): its processes are not this host's to judge.
|
|
380
|
+
if (server.hostname !== d.self.hostname) continue;
|
|
381
|
+
const refusal = refusalOf(record, name, opts.slotsDir);
|
|
382
|
+
if (refusal !== null) {
|
|
383
|
+
refused.push({ file: name, reason: refusal.reason });
|
|
384
|
+
log("warn", `the verification process journal ${path} was refused (${refusal.reason}); nothing was killed`);
|
|
385
|
+
if (refusal.park) {
|
|
386
|
+
alive.push({ slot: "", taskId: attempt?.taskId ?? null, n: attempt?.n ?? null, serverPid: null, pids: [],
|
|
387
|
+
reason: `the journal ${name} was refused (${refusal.reason}); nothing was killed: check it, then remove it` });
|
|
388
|
+
}
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
let serverPidLive: boolean;
|
|
392
|
+
/** Re-review 2: when the process holding the server's pid now was created, when that is known here. */
|
|
393
|
+
let heldSinceMs: number | null = null;
|
|
394
|
+
if (server.pid === d.self.pid) {
|
|
395
|
+
// This very process (its own journal is in `files`), or an earlier one whose pid it reuses: then dead, and no
|
|
396
|
+
// process created after this one's start is that server's child.
|
|
397
|
+
if (server.token === d.self.token) continue;
|
|
398
|
+
serverPidLive = false;
|
|
399
|
+
heldSinceMs = startedAtMs;
|
|
400
|
+
} else {
|
|
401
|
+
// L8: a pid that answers is checked by its start in the sweep (a later owner of the pid leaves the server dead).
|
|
402
|
+
serverPidLive = d.isAlive(server.pid);
|
|
403
|
+
}
|
|
404
|
+
if (record.roots.length === 0) {
|
|
405
|
+
await remove(path);
|
|
406
|
+
cleared += 1;
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
candidates.push({
|
|
410
|
+
path, record,
|
|
411
|
+
group: {
|
|
412
|
+
serverPid: server.pid, serverStartedAtMs: server.startedAtMs, serverStartTicks: server.startTicks, serverPidLive,
|
|
413
|
+
recordedUntilMs: beatAtMs === null ? null : beatAtMs + record.heartbeatMs + JOURNAL_HEARTBEAT_SLACK_MS,
|
|
414
|
+
serverPidHeldSinceMs: heldSinceMs,
|
|
415
|
+
slotPath: record.slot.path, roots: record.roots,
|
|
416
|
+
},
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
if (candidates.length === 0) return { alive, killed, cleared, refused };
|
|
420
|
+
|
|
421
|
+
// M2: one kill for every journal, bounded as a whole and aborted with the attachment.
|
|
422
|
+
const timeoutMs = d.sweepTimeoutMs ?? VERIFY_TREE_SWEEP_MS;
|
|
423
|
+
const controller = new AbortController();
|
|
424
|
+
let stoppedBy: string | undefined;
|
|
425
|
+
const stop = (why: string): void => {
|
|
426
|
+
stoppedBy ??= why;
|
|
427
|
+
controller.abort();
|
|
428
|
+
};
|
|
429
|
+
const onAbort = (): void => stop("the sweep was aborted");
|
|
430
|
+
if (opts.signal?.aborted === true) onAbort();
|
|
431
|
+
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
432
|
+
const timer = setTimeout(() => stop(`the sweep did not finish within ${timeoutMs} ms`), timeoutMs);
|
|
433
|
+
timer.unref?.();
|
|
434
|
+
const stopped = new Promise<"stopped">((res) => {
|
|
435
|
+
if (controller.signal.aborted) res("stopped");
|
|
436
|
+
else controller.signal.addEventListener("abort", () => res("stopped"), { once: true });
|
|
437
|
+
});
|
|
438
|
+
let result: RecordedTreeKill | Error | "stopped";
|
|
439
|
+
try {
|
|
440
|
+
result = await Promise.race([
|
|
441
|
+
kill({ groups: candidates.map((c) => c.group), until: startedAtMs, signal: controller.signal, timeoutMs }),
|
|
442
|
+
stopped,
|
|
443
|
+
]);
|
|
444
|
+
} catch (e) {
|
|
445
|
+
result = e instanceof Error ? e : new Error(String(e));
|
|
446
|
+
} finally {
|
|
447
|
+
clearTimeout(timer);
|
|
448
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
449
|
+
}
|
|
450
|
+
for (const [i, c] of candidates.entries()) {
|
|
451
|
+
const parkWith = (pids: readonly number[], reason: string, late?: readonly number[]): void => {
|
|
452
|
+
const base = { slot: c.record.slot.name, taskId: c.record.taskId, n: c.record.n, serverPid: c.record.server.pid, pids, reason };
|
|
453
|
+
alive.push(late === undefined || late.length === 0 ? base : { ...base, late });
|
|
454
|
+
};
|
|
455
|
+
const roots = c.record.roots.map((r) => r.pid);
|
|
456
|
+
if (stoppedBy !== undefined) {
|
|
457
|
+
parkWith(roots, stoppedBy);
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
if (result === "stopped") continue; // unreachable: stopping sets the reason first
|
|
461
|
+
if (result instanceof Error) {
|
|
462
|
+
parkWith(roots, result.message);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
const g = result.groups[i];
|
|
466
|
+
if (g === undefined) {
|
|
467
|
+
parkWith(roots, "the kill reported nothing for this journal");
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
// A live server's journal is its own: kept, not acted on.
|
|
471
|
+
if (g.serverAlive) continue;
|
|
472
|
+
killed.push(...g.killed);
|
|
473
|
+
if (g.killed.length > 0) {
|
|
474
|
+
log("info", `ended ${g.killed.length} process tree(s) a dead server's verification of ${c.record.taskId}#${c.record.n} left in slot ${c.record.slot.name}: pid ${g.killed.join(", ")}`);
|
|
475
|
+
}
|
|
476
|
+
if (g.alive.length === 0) {
|
|
477
|
+
await remove(c.path);
|
|
478
|
+
cleared += 1;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
parkWith(g.alive, g.reason ?? "the kill could not be confirmed", g.late);
|
|
482
|
+
}
|
|
483
|
+
return { alive, killed, cleared, refused };
|
|
484
|
+
},
|
|
485
|
+
|
|
486
|
+
async purge(planId) {
|
|
487
|
+
let dir: string;
|
|
488
|
+
try {
|
|
489
|
+
dir = dirOf(planId);
|
|
490
|
+
} catch {
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
for (const path of [...files.keys()]) if (dirname(path) === dir) files.delete(path);
|
|
494
|
+
syncBeat();
|
|
495
|
+
try {
|
|
496
|
+
await rm(dir, { recursive: true, force: true });
|
|
497
|
+
} catch (e) {
|
|
498
|
+
log("warn", `the verification process journals of plan ${planId} could not be removed`, errorText(e));
|
|
499
|
+
}
|
|
500
|
+
},
|
|
501
|
+
|
|
502
|
+
dispose() {
|
|
503
|
+
disposed = true;
|
|
504
|
+
syncBeat();
|
|
505
|
+
},
|
|
506
|
+
};
|
|
507
|
+
}
|
package/src/guard/enforce.ts
CHANGED
|
@@ -80,7 +80,8 @@ export function buildGuardPolicy(
|
|
|
80
80
|
deliverableFirst: g.deliverableFirst ?? true,
|
|
81
81
|
blockScriptWrites: g.blockScriptWrites ?? false,
|
|
82
82
|
deliverableSignal: null,
|
|
83
|
-
|
|
83
|
+
// #108 slice 5: a role's handle expansions (router_git_show with handle) are reads; tier agents keep the policy shape.
|
|
84
|
+
...(profile ? { reader: profile.kind === "reader", needMoreOnExhaustion: true, handleReads: true } : {}),
|
|
84
85
|
};
|
|
85
86
|
}
|
|
86
87
|
|
package/src/guard/fingerprint.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { isWellFormedExpansion } from "../router/diff-handles";
|
|
2
|
+
|
|
1
3
|
/** Fingerprint a read-only tool call for redundancy detection. */
|
|
2
4
|
export function fingerprintToolCall(tool: string, args: unknown): string {
|
|
3
5
|
const a = (args ?? {}) as Record<string, unknown>;
|
|
@@ -19,6 +21,13 @@ export function fingerprintToolCall(tool: string, args: unknown): string {
|
|
|
19
21
|
return `glob:${a.pattern ?? ""}:${a.path ?? ""}`;
|
|
20
22
|
case "ls":
|
|
21
23
|
return `ls:${a.path ?? ""}`;
|
|
24
|
+
case "router_git_show":
|
|
25
|
+
// #108 slice 5: a well-formed handle expansion is identified by handle, side, lines and force (not by argument order);
|
|
26
|
+
// anything else (a malformed handle, lines or side: refused before git runs) keeps the default capped fingerprint.
|
|
27
|
+
if (isWellFormedExpansion(a)) {
|
|
28
|
+
return `router_git_show:${String(a.handle)}:${String(a.side ?? "default")}:${String(a.lines ?? "all")}${a.force === true ? ":force" : ""}`;
|
|
29
|
+
}
|
|
30
|
+
return `${tool}:${JSON.stringify(a).slice(0, 120)}`;
|
|
22
31
|
default:
|
|
23
32
|
return `${tool}:${JSON.stringify(a).slice(0, 120)}`;
|
|
24
33
|
}
|
package/src/guard/guards.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { fingerprintToolCall } from "./fingerprint";
|
|
2
|
-
import { READ_ONLY_TOOLS } from "../router/sessions";
|
|
2
|
+
import { READ_ONLY_TOOLS, isHandleExpansion } from "../router/sessions";
|
|
3
3
|
import { REFUSAL_CAP } from "../router/guard-profile";
|
|
4
4
|
|
|
5
5
|
// ---------------------------------------------------------------------------
|
|
@@ -27,6 +27,11 @@ export interface GuardPolicy {
|
|
|
27
27
|
reader?: boolean;
|
|
28
28
|
/** Role budget (§2.6): on exhaustion the child is told to return `NEED MORE: budget` with a progress summary. */
|
|
29
29
|
needMoreOnExhaustion?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* #108 slice 5 (role profiles only): a `router_git_show` handle expansion is a read (clause 4 for everyone, clause 5 for
|
|
32
|
+
* producers). Absent/false: it is `other`, as every router_git_* call (tier policy, OpenCode v1).
|
|
33
|
+
*/
|
|
34
|
+
handleReads?: boolean;
|
|
30
35
|
}
|
|
31
36
|
|
|
32
37
|
export interface GuardCall {
|
|
@@ -174,6 +179,7 @@ export function classify(call: GuardCall, policy: GuardPolicy): GuardKind {
|
|
|
174
179
|
if (FINISH_TOOLS.has(call.tool)) return "finish";
|
|
175
180
|
if (isSelfScript(call, policy)) return "self_script";
|
|
176
181
|
if (READ_ONLY_TOOLS.has(call.tool)) return "read";
|
|
182
|
+
if (policy.handleReads === true && isHandleExpansion(call.tool, call.args)) return "read";
|
|
177
183
|
if (MUTATION_TOOLS.has(call.tool)) return "mutation";
|
|
178
184
|
return "other";
|
|
179
185
|
}
|