opencode-model-router 2.7.0 → 2.9.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 +583 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +34 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2853 -109
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1789 -288
- package/src/router/config.ts +823 -26
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +266 -19
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +44 -10
- package/src/router/role-agents.ts +334 -20
- package/src/router/roles-config.ts +93 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/sessions.ts +11 -0
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/route-line.ts +96 -5
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/classify/types.ts +26 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/signals.ts +17 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +957 -0
- package/src/routing/roles/binding.ts +116 -13
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +30 -3
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +12 -2
- package/src/routing/wire/dispatch.ts +697 -30
- package/src/routing/wire/hint.ts +56 -8
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/v2.ts +94 -49
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +141 -0
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +268 -17
- package/src/verify/dispatch.ts +348 -37
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- package/src/verify/exec.ts +52 -9
- package/src/verify/gate.ts +349 -16
- package/src/verify/git-top.ts +43 -0
- package/src/verify/head.ts +107 -0
- package/src/verify/pending.ts +1846 -18
- package/src/verify/perimeter.ts +1186 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +297 -8
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +372 -16
- package/src/verify/types.ts +66 -2
- package/src/verify/wiring.ts +1594 -46
|
@@ -10,9 +10,13 @@
|
|
|
10
10
|
|
|
11
11
|
import { appendFile, mkdir, open, readFile, readdir, rename, stat, unlink } from "node:fs/promises";
|
|
12
12
|
import { isAbsolute, join, normalize, resolve } from "node:path";
|
|
13
|
+
import type { DurationSeams } from "./durations";
|
|
13
14
|
import type {
|
|
14
15
|
DecisionRow,
|
|
15
16
|
DecisionTrace,
|
|
17
|
+
DispatchCapacity,
|
|
18
|
+
DispatchTimingOutcome,
|
|
19
|
+
DispatchTimingRow,
|
|
16
20
|
FlusherDeps,
|
|
17
21
|
ForeignCheck,
|
|
18
22
|
FlusherOptions,
|
|
@@ -25,6 +29,7 @@ import type {
|
|
|
25
29
|
OutcomeKey,
|
|
26
30
|
OutcomeSnapshot,
|
|
27
31
|
OutcomeStore,
|
|
32
|
+
OrchestratorTurnRow,
|
|
28
33
|
OutcomesFile,
|
|
29
34
|
PersistDeps,
|
|
30
35
|
PersistFs,
|
|
@@ -32,8 +37,10 @@ import type {
|
|
|
32
37
|
Persister,
|
|
33
38
|
PersisterOptions,
|
|
34
39
|
ReadRowsResult,
|
|
40
|
+
ReadSideRowsResult,
|
|
35
41
|
RefusalRow,
|
|
36
42
|
RouteChoice,
|
|
43
|
+
SideLogs,
|
|
37
44
|
SignalKind,
|
|
38
45
|
VerdictRow,
|
|
39
46
|
WriteResult,
|
|
@@ -52,6 +59,7 @@ import {
|
|
|
52
59
|
MAX_QUEUED_ROWS,
|
|
53
60
|
MAX_CORRUPT_COPIES,
|
|
54
61
|
NEED_TERM_RE,
|
|
62
|
+
RISK_TERM_RE,
|
|
55
63
|
OUTCOMES_CORRUPT_PREFIX,
|
|
56
64
|
OUTCOMES_CORRUPT_RE,
|
|
57
65
|
OUTCOMES_FILE,
|
|
@@ -59,7 +67,12 @@ import {
|
|
|
59
67
|
OUTCOMES_SCHEMA_VERSION,
|
|
60
68
|
OUTCOMES_TMP_PREFIX,
|
|
61
69
|
RENAME_RETRY_DELAYS_MS,
|
|
70
|
+
SIDE_ROW_VERSION,
|
|
62
71
|
STALE_TMP_MS,
|
|
72
|
+
TIMINGS_FILE,
|
|
73
|
+
TIMINGS_ROTATED_RE,
|
|
74
|
+
TURNS_FILE,
|
|
75
|
+
TURNS_ROTATED_RE,
|
|
63
76
|
parseKey,
|
|
64
77
|
safeNow,
|
|
65
78
|
} from "./types";
|
|
@@ -283,6 +296,23 @@ function readChoice(x: unknown): RouteChoice | null {
|
|
|
283
296
|
return { key, agent, origin, model, variant };
|
|
284
297
|
}
|
|
285
298
|
|
|
299
|
+
function isRisk(x: unknown): x is NonNullable<DecisionTrace["riskSources"]>["effective"] {
|
|
300
|
+
return x === "low" || x === "medium" || x === "high";
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Additive audit metadata: an invalid proposal drops only this field, never the existing trace or decision. */
|
|
304
|
+
function readRiskSources(x: unknown): DecisionTrace["riskSources"] {
|
|
305
|
+
if (!isRec(x)) return undefined;
|
|
306
|
+
const { base, rules, routeLine, facts, effective } = x;
|
|
307
|
+
if (!isRisk(base) || !isRisk(facts) || !isRisk(effective)
|
|
308
|
+
|| (rules !== null && !isRisk(rules)) || (routeLine !== null && !isRisk(routeLine))) return undefined;
|
|
309
|
+
return {
|
|
310
|
+
base, rules, routeLine, facts, effective,
|
|
311
|
+
...(isRisk(x.resumedDispatch) ? { resumedDispatch: x.resumedDispatch } : {}),
|
|
312
|
+
...(typeof x.term === "string" && RISK_TERM_RE.test(x.term) ? { term: x.term } : {}),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
286
316
|
/** A trace is optional and cosmetic: a malformed one is dropped, never a reason to lose the row. */
|
|
287
317
|
function readTrace(x: unknown): DecisionTrace | undefined {
|
|
288
318
|
if (!isRec(x) || !isRec(x.routeLines)) return undefined;
|
|
@@ -302,6 +332,7 @@ function readTrace(x: unknown): DecisionTrace | undefined {
|
|
|
302
332
|
};
|
|
303
333
|
}
|
|
304
334
|
const argmin = readChoice(x.argmin);
|
|
335
|
+
const riskSources = readRiskSources(x.riskSources);
|
|
305
336
|
return {
|
|
306
337
|
routeLines: { count, conflict, edgeOnly },
|
|
307
338
|
backend,
|
|
@@ -309,6 +340,7 @@ function readTrace(x: unknown): DecisionTrace | undefined {
|
|
|
309
340
|
...(argmin === null ? {} : { argmin }),
|
|
310
341
|
// QA-G-B-2-2 (D14): only well-shaped need terms; one that could carry prompt text (an older row's URL or path) is dropped.
|
|
311
342
|
...(isStringArray(x.needTerms) ? { needTerms: x.needTerms.filter((term) => NEED_TERM_RE.test(term)) } : {}),
|
|
343
|
+
...(riskSources === undefined ? {} : { riskSources }),
|
|
312
344
|
};
|
|
313
345
|
}
|
|
314
346
|
function readLadderStep(x: unknown): (typeof LADDER_STEP_KINDS)[number] | null {
|
|
@@ -845,6 +877,383 @@ export function createPersister(dir: string, deps: PersistDeps, options: Persist
|
|
|
845
877
|
};
|
|
846
878
|
}
|
|
847
879
|
|
|
880
|
+
// ---------------------------------------------------------------------------
|
|
881
|
+
// Side logs: timings.jsonl and turns.jsonl (counters and labels only, never prompt or output text)
|
|
882
|
+
// ---------------------------------------------------------------------------
|
|
883
|
+
|
|
884
|
+
const TIMING_OUTCOMES: readonly string[] = ["succeeded", "failed", "interrupted", "unknown"];
|
|
885
|
+
const CAPACITIES: readonly string[] = ["rate-limit", "overload", "usage-limit"];
|
|
886
|
+
/**
|
|
887
|
+
* A label (role, class, scope, tier, model, ids) is one token of at most 256 characters, no whitespace: anything longer or
|
|
888
|
+
* with spaces could be free text, so the row is refused rather than stored (QA-1.1-5). Printable non-whitespace ASCII, so model ids
|
|
889
|
+
* such as `anthropic/claude-sonnet-5-5#low`, `anthropic/claude-opus-5-5[1m]`, Vertex `@20250101` and Bedrock `-v1:0` match
|
|
890
|
+
* (QA-1.1-19). The timing recorder maps a label that still fails to `unknown` instead of losing the row.
|
|
891
|
+
*/
|
|
892
|
+
const LABEL_RE = /^[!-~]{1,256}$/;
|
|
893
|
+
|
|
894
|
+
function isLabel(x: unknown): x is string {
|
|
895
|
+
return typeof x === "string" && LABEL_RE.test(x);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/** True when `label` would be stored as it is (the rule of the side-log rows). */
|
|
899
|
+
export function isSideLogLabel(label: string): boolean {
|
|
900
|
+
return LABEL_RE.test(label);
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/** Appends to one file are serialized per path within the process, whichever side-log instance issues them (QA-1.1-16). */
|
|
904
|
+
const appendChains = new Map<string, Promise<void>>();
|
|
905
|
+
|
|
906
|
+
async function serialized<T>(key: string, task: () => Promise<T>): Promise<T> {
|
|
907
|
+
const previous = appendChains.get(key) ?? Promise.resolve();
|
|
908
|
+
const run = previous.then(task); // `previous` is a tail that never rejects
|
|
909
|
+
const tail: Promise<void> = run.then(
|
|
910
|
+
() => undefined,
|
|
911
|
+
() => undefined,
|
|
912
|
+
);
|
|
913
|
+
appendChains.set(key, tail);
|
|
914
|
+
void tail.then(() => {
|
|
915
|
+
if (appendChains.get(key) === tail) appendChains.delete(key);
|
|
916
|
+
});
|
|
917
|
+
return run;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
function chainKey(path: string): string {
|
|
921
|
+
const abs = resolve(path);
|
|
922
|
+
return process.platform === "win32" ? abs.toLowerCase() : abs;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function isCount(x: unknown): x is number {
|
|
926
|
+
return isFiniteNum(x) && x >= 0;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
function isIsoTs(x: unknown): x is string {
|
|
930
|
+
return typeof x === "string" && Number.isFinite(Date.parse(x));
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/** `"newer"`: a valid JSON row of a later schema (skipped quietly); `null`: not a row of this kind. */
|
|
934
|
+
type SideParse<Row> = Row | "newer" | null;
|
|
935
|
+
|
|
936
|
+
function sideEnvelope(line: string, kind: string): Rec | "newer" | null {
|
|
937
|
+
let json: unknown;
|
|
938
|
+
try {
|
|
939
|
+
json = JSON.parse(line);
|
|
940
|
+
} catch {
|
|
941
|
+
return null;
|
|
942
|
+
}
|
|
943
|
+
if (!isRec(json) || json.kind !== kind) return null;
|
|
944
|
+
if (isFiniteNum(json.v) && json.v > SIDE_ROW_VERSION) return "newer";
|
|
945
|
+
return json.v === SIDE_ROW_VERSION ? json : null;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** Validate one `timings.jsonl` line. Unknown extra fields are dropped. */
|
|
949
|
+
export function parseTimingLine(line: string): SideParse<DispatchTimingRow> {
|
|
950
|
+
const json = sideEnvelope(line, "dispatch-timing");
|
|
951
|
+
if (json === null || json === "newer") return json;
|
|
952
|
+
const { ts, parentSessionID, childSessionID, callID, role, scope, tier, model, background, startedAt, endedAt, durationMs, outcome, capacity } = json;
|
|
953
|
+
const cls = json.class;
|
|
954
|
+
if (!isIsoTs(ts) || !isLabel(parentSessionID) || !isLabel(childSessionID) || !isLabel(callID)) return null;
|
|
955
|
+
if (!isLabel(role) || !isLabel(cls) || !isLabel(scope) || !isLabel(tier) || !isLabel(model)) return null;
|
|
956
|
+
if (typeof background !== "boolean" || !isCount(startedAt) || !isCount(endedAt) || !isCount(durationMs)) return null;
|
|
957
|
+
if (!oneOf(TIMING_OUTCOMES, outcome)) return null;
|
|
958
|
+
if (capacity !== null && !oneOf(CAPACITIES, capacity)) return null;
|
|
959
|
+
return {
|
|
960
|
+
kind: "dispatch-timing",
|
|
961
|
+
v: SIDE_ROW_VERSION,
|
|
962
|
+
ts,
|
|
963
|
+
parentSessionID,
|
|
964
|
+
childSessionID,
|
|
965
|
+
callID,
|
|
966
|
+
role,
|
|
967
|
+
class: cls,
|
|
968
|
+
scope,
|
|
969
|
+
tier,
|
|
970
|
+
model,
|
|
971
|
+
background,
|
|
972
|
+
startedAt,
|
|
973
|
+
endedAt,
|
|
974
|
+
durationMs,
|
|
975
|
+
outcome: outcome as DispatchTimingOutcome,
|
|
976
|
+
capacity: capacity as DispatchCapacity | null,
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
/** Validate one `turns.jsonl` line. Unknown extra fields are dropped. */
|
|
981
|
+
export function parseTurnLine(line: string): SideParse<OrchestratorTurnRow> {
|
|
982
|
+
const json = sideEnvelope(line, "orchestrator-turn");
|
|
983
|
+
if (json === null || json === "newer") return json;
|
|
984
|
+
const { ts, sessionID, turn, steps, input, cacheRead, cacheWrite } = json;
|
|
985
|
+
if (!isIsoTs(ts) || !isLabel(sessionID)) return null;
|
|
986
|
+
if (!isCount(turn) || !isCount(steps) || !isCount(input) || !isCount(cacheRead) || !isCount(cacheWrite)) return null;
|
|
987
|
+
return { kind: "orchestrator-turn", v: SIDE_ROW_VERSION, ts, sessionID, turn, steps, input, cacheRead, cacheWrite };
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** Only the declared fields are written, so a row carrying anything extra never reaches the disk with it. */
|
|
991
|
+
function serializeTiming(row: DispatchTimingRow): string {
|
|
992
|
+
return JSON.stringify({
|
|
993
|
+
kind: row.kind,
|
|
994
|
+
v: row.v,
|
|
995
|
+
ts: row.ts,
|
|
996
|
+
parentSessionID: row.parentSessionID,
|
|
997
|
+
childSessionID: row.childSessionID,
|
|
998
|
+
callID: row.callID,
|
|
999
|
+
role: row.role,
|
|
1000
|
+
class: row.class,
|
|
1001
|
+
scope: row.scope,
|
|
1002
|
+
tier: row.tier,
|
|
1003
|
+
model: row.model,
|
|
1004
|
+
background: row.background,
|
|
1005
|
+
startedAt: row.startedAt,
|
|
1006
|
+
endedAt: row.endedAt,
|
|
1007
|
+
durationMs: row.durationMs,
|
|
1008
|
+
outcome: row.outcome,
|
|
1009
|
+
capacity: row.capacity,
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
function serializeTurn(row: OrchestratorTurnRow): string {
|
|
1014
|
+
return JSON.stringify({
|
|
1015
|
+
kind: row.kind,
|
|
1016
|
+
v: row.v,
|
|
1017
|
+
ts: row.ts,
|
|
1018
|
+
sessionID: row.sessionID,
|
|
1019
|
+
turn: row.turn,
|
|
1020
|
+
steps: row.steps,
|
|
1021
|
+
input: row.input,
|
|
1022
|
+
cacheRead: row.cacheRead,
|
|
1023
|
+
cacheWrite: row.cacheWrite,
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/** Options of {@link createSideLogs}: the rotation knobs of the decision log, plus an observer. */
|
|
1028
|
+
export interface SideLogOptions extends PersisterOptions {
|
|
1029
|
+
/** Called once per row after it was appended (not for refused rows or failed writes). Must not throw; if it does it is logged. */
|
|
1030
|
+
readonly onRow?: (row: DispatchTimingRow | OrchestratorTurnRow) => void;
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
/** Adapts the timing side log to the duration estimator's seam (`createDurationModel`). */
|
|
1034
|
+
export function durationSeamsFor(sideLogs: Pick<SideLogs, "readTimings">, now: () => number): DurationSeams {
|
|
1035
|
+
return {
|
|
1036
|
+
readTimings: async () => (await sideLogs.readTimings()).rows,
|
|
1037
|
+
now,
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
interface SideSpec<Row> {
|
|
1042
|
+
readonly file: string;
|
|
1043
|
+
/** Rotated names are `<prefix>.<stamp>-<pid>.jsonl`. */
|
|
1044
|
+
readonly prefix: string;
|
|
1045
|
+
readonly rotatedRe: RegExp;
|
|
1046
|
+
readonly parse: (line: string) => SideParse<Row>;
|
|
1047
|
+
readonly serialize: (row: Row) => string;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
const TIMINGS_SPEC: SideSpec<DispatchTimingRow> = {
|
|
1051
|
+
file: TIMINGS_FILE,
|
|
1052
|
+
prefix: "timings",
|
|
1053
|
+
rotatedRe: TIMINGS_ROTATED_RE,
|
|
1054
|
+
parse: parseTimingLine,
|
|
1055
|
+
serialize: serializeTiming,
|
|
1056
|
+
};
|
|
1057
|
+
|
|
1058
|
+
const TURNS_SPEC: SideSpec<OrchestratorTurnRow> = {
|
|
1059
|
+
file: TURNS_FILE,
|
|
1060
|
+
prefix: "turns",
|
|
1061
|
+
rotatedRe: TURNS_ROTATED_RE,
|
|
1062
|
+
parse: parseTurnLine,
|
|
1063
|
+
serialize: serializeTurn,
|
|
1064
|
+
};
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* `timings.jsonl` and `turns.jsonl` next to `decisions.jsonl`: the same append path (one `appendText`, a torn last
|
|
1068
|
+
* line is not glued to the next batch) and the same rotation rule as the decision log, generalized over the file name
|
|
1069
|
+
* (the decision-log code itself is untouched). Readers skip a torn last line with one warning per read and rows of a
|
|
1070
|
+
* newer schema without one.
|
|
1071
|
+
*/
|
|
1072
|
+
export function createSideLogs(dir: string, deps: PersistDeps, options: SideLogOptions = {}): SideLogs {
|
|
1073
|
+
const { fs, sleep, logger, pid } = deps;
|
|
1074
|
+
const now = (): number => safeNow(deps.now);
|
|
1075
|
+
const maxBytes = options.maxBytes ?? DECISIONS_MAX_BYTES;
|
|
1076
|
+
const maxGenerations = Math.max(0, Math.floor(options.maxGenerations ?? DECISIONS_MAX_GENERATIONS));
|
|
1077
|
+
const delays = options.renameRetryDelaysMs ?? RENAME_RETRY_DELAYS_MS;
|
|
1078
|
+
|
|
1079
|
+
function createFile<Row extends DispatchTimingRow | OrchestratorTurnRow>(spec: SideSpec<Row>): {
|
|
1080
|
+
readonly path: string;
|
|
1081
|
+
append(rows: readonly Row[]): Promise<WriteResult>;
|
|
1082
|
+
read(): Promise<ReadSideRowsResult<Row>>;
|
|
1083
|
+
} {
|
|
1084
|
+
const path = join(dir, spec.file);
|
|
1085
|
+
const key = chainKey(path);
|
|
1086
|
+
let knownEnd: number | null = null;
|
|
1087
|
+
let warnedRefusal = false;
|
|
1088
|
+
const rotated = (names: readonly string[]): string[] => names.filter((name) => spec.rotatedRe.test(name)).sort();
|
|
1089
|
+
|
|
1090
|
+
async function sizeOrNull(target: string): Promise<number | null> {
|
|
1091
|
+
try {
|
|
1092
|
+
return (await fs.stat(target))?.size ?? null;
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
logger.info?.("[router] side log stat failed", { path: target, error: describeError(error) });
|
|
1095
|
+
return null;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
async function rotate(): Promise<void> {
|
|
1100
|
+
try {
|
|
1101
|
+
let ms = now();
|
|
1102
|
+
const newest = rotated(await fs.readdir(dir)).at(-1);
|
|
1103
|
+
const match = newest === undefined ? null : spec.rotatedRe.exec(newest);
|
|
1104
|
+
const newestMs = match === null ? null : stampToMs(match[1] as string);
|
|
1105
|
+
if (newestMs !== null && ms <= newestMs) ms = newestMs + 1; // names stay unique and chronological
|
|
1106
|
+
try {
|
|
1107
|
+
// Another process may have rotated while we listed generations. Do not rotate its small new file.
|
|
1108
|
+
const current = await fs.stat(path);
|
|
1109
|
+
if (current === null || current.size < maxBytes) return;
|
|
1110
|
+
// QA-1.1-16: never rename over an existing generation (a second writer of the same stamp and pid): probe a free name.
|
|
1111
|
+
let target = "";
|
|
1112
|
+
for (let attempt = 0; attempt < 20 && target === ""; attempt++) {
|
|
1113
|
+
const candidate = join(dir, `${spec.prefix}.${compactStamp(ms)}-${pid}.jsonl`);
|
|
1114
|
+
if ((await fs.stat(candidate)) === null) target = candidate;
|
|
1115
|
+
else ms += 1;
|
|
1116
|
+
}
|
|
1117
|
+
if (target === "") throw new Error("no free rotated side log name");
|
|
1118
|
+
await renameWithRetry(fs, path, target, sleep, delays);
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
if (errorCode(error) !== "ENOENT") throw error; // ENOENT: another process rotated first
|
|
1121
|
+
}
|
|
1122
|
+
const generations = rotated(await fs.readdir(dir));
|
|
1123
|
+
for (const name of generations.slice(0, Math.max(0, generations.length - maxGenerations))) {
|
|
1124
|
+
try {
|
|
1125
|
+
await fs.unlink(join(dir, name));
|
|
1126
|
+
} catch (error) {
|
|
1127
|
+
logger.warn("[router] could not prune a rotated side log", { name, error: describeError(error) });
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
} catch (error) {
|
|
1131
|
+
logger.warn("[router] side log rotation failed; appending to the live file", { file: spec.file, error: describeError(error) });
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
return {
|
|
1136
|
+
path,
|
|
1137
|
+
async append(rows: readonly Row[]): Promise<WriteResult> {
|
|
1138
|
+
if (rows.length === 0) return { ok: true };
|
|
1139
|
+
// QA-1.1-5: only a row the reader would accept again is written (labels without whitespace, finite non-negative times).
|
|
1140
|
+
const accepted: Row[] = [];
|
|
1141
|
+
const lines: string[] = [];
|
|
1142
|
+
let refused = 0;
|
|
1143
|
+
for (const row of rows) {
|
|
1144
|
+
let line: string | null = null;
|
|
1145
|
+
try {
|
|
1146
|
+
const text = spec.serialize(row);
|
|
1147
|
+
const back = spec.parse(text);
|
|
1148
|
+
if (back !== null && back !== "newer") line = text;
|
|
1149
|
+
} catch {
|
|
1150
|
+
line = null; // a row that cannot even be serialized is refused like any other invalid row
|
|
1151
|
+
}
|
|
1152
|
+
if (line === null) {
|
|
1153
|
+
refused += 1;
|
|
1154
|
+
} else {
|
|
1155
|
+
accepted.push(row);
|
|
1156
|
+
lines.push(line);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (refused > 0 && !warnedRefusal) {
|
|
1160
|
+
warnedRefusal = true;
|
|
1161
|
+
logger.warn("[router] side log rows that do not validate were refused (labels are single tokens of at most 256 characters)", {
|
|
1162
|
+
file: spec.file,
|
|
1163
|
+
refused,
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
if (lines.length === 0) return { ok: true };
|
|
1167
|
+
return serialized(key, async (): Promise<WriteResult> => {
|
|
1168
|
+
try {
|
|
1169
|
+
await fs.mkdirp(dir);
|
|
1170
|
+
const body = lines.join("\n") + "\n";
|
|
1171
|
+
let size = (await sizeOrNull(path)) ?? 0;
|
|
1172
|
+
if (size > 0 && size + Buffer.byteLength(body, "utf8") + 1 > maxBytes) {
|
|
1173
|
+
await rotate();
|
|
1174
|
+
size = (await sizeOrNull(path)) ?? 0;
|
|
1175
|
+
}
|
|
1176
|
+
// A crash can leave a torn last line without its newline: the batch that follows starts on a fresh line.
|
|
1177
|
+
let lead = "";
|
|
1178
|
+
if (size > 0 && size !== knownEnd) {
|
|
1179
|
+
try {
|
|
1180
|
+
const existing = await fs.readText(path);
|
|
1181
|
+
if (existing !== null && !existing.endsWith("\n")) lead = "\n";
|
|
1182
|
+
} catch (readError) {
|
|
1183
|
+
lead = "\n"; // cannot tell: a blank line is harmless, a glued row is not
|
|
1184
|
+
logger.info?.("[router] side log end not checked", { file: spec.file, error: describeError(readError) });
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
await fs.appendText(path, lead + body);
|
|
1188
|
+
knownEnd = size + Buffer.byteLength(lead + body, "utf8");
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
return failure(error);
|
|
1191
|
+
}
|
|
1192
|
+
for (const row of accepted) {
|
|
1193
|
+
try {
|
|
1194
|
+
options.onRow?.(row);
|
|
1195
|
+
} catch (hookError) {
|
|
1196
|
+
logger.warn("[router] side log onRow observer failed", { file: spec.file, error: describeError(hookError) });
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return { ok: true };
|
|
1200
|
+
});
|
|
1201
|
+
},
|
|
1202
|
+
async read(): Promise<ReadSideRowsResult<Row>> {
|
|
1203
|
+
const rows: Row[] = [];
|
|
1204
|
+
const files: string[] = [];
|
|
1205
|
+
let skipped = 0;
|
|
1206
|
+
let newer = 0;
|
|
1207
|
+
let names: string[];
|
|
1208
|
+
try {
|
|
1209
|
+
names = await fs.readdir(dir);
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
logger.warn("[router] side log directory unreadable", { dir, error: describeError(error) });
|
|
1212
|
+
return { rows, skipped, newer, files };
|
|
1213
|
+
}
|
|
1214
|
+
for (const name of [...rotated(names), spec.file]) {
|
|
1215
|
+
const target = join(dir, name);
|
|
1216
|
+
let text: string | null;
|
|
1217
|
+
try {
|
|
1218
|
+
text = await withRetry(() => fs.readText(target), sleep, delays);
|
|
1219
|
+
} catch (error) {
|
|
1220
|
+
logger.warn("[router] side log unreadable; skipped", { path: target, error: describeError(error) });
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
if (text === null) continue;
|
|
1224
|
+
files.push(target);
|
|
1225
|
+
for (const line of (text.charCodeAt(0) === 0xfeff ? text.slice(1) : text).split(/\r?\n/)) {
|
|
1226
|
+
if (line.trim() === "") continue;
|
|
1227
|
+
const row = spec.parse(line);
|
|
1228
|
+
if (row === null) skipped += 1;
|
|
1229
|
+
else if (row === "newer") newer += 1;
|
|
1230
|
+
else rows.push(row);
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
if (skipped > 0) {
|
|
1234
|
+
logger.warn("[router] side log had unreadable lines (a torn last line is expected after a crash); they were skipped", {
|
|
1235
|
+
file: spec.file,
|
|
1236
|
+
skipped,
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
return { rows, skipped, newer, files };
|
|
1240
|
+
},
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
const timings = createFile(TIMINGS_SPEC);
|
|
1245
|
+
const turns = createFile(TURNS_SPEC);
|
|
1246
|
+
return {
|
|
1247
|
+
dir,
|
|
1248
|
+
timingsPath: timings.path,
|
|
1249
|
+
turnsPath: turns.path,
|
|
1250
|
+
appendTimings: timings.append,
|
|
1251
|
+
appendTurns: turns.append,
|
|
1252
|
+
readTimings: timings.read,
|
|
1253
|
+
readTurns: turns.read,
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
|
|
848
1257
|
// ---------------------------------------------------------------------------
|
|
849
1258
|
// Flusher: coalescing, throttled, never on the hot path
|
|
850
1259
|
// ---------------------------------------------------------------------------
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
// child's own `NEED MORE: budget` / `ESCALATE: authority` claim is not an exemption, only the guard's state is.
|
|
15
15
|
// ---------------------------------------------------------------------------
|
|
16
16
|
|
|
17
|
+
import type { DoD } from "../../verify/dod";
|
|
17
18
|
import type {
|
|
18
19
|
DecisionFacts,
|
|
19
20
|
DecisionRow,
|
|
@@ -333,6 +334,22 @@ export function runSignal(input: RunSignalInput): SignalObservation | null {
|
|
|
333
334
|
return observe("run", "pass", SIGNAL_WEIGHTS.run);
|
|
334
335
|
}
|
|
335
336
|
|
|
337
|
+
/** Exact npm forms of a deterministic check's command → the `routing.run` script it names (`npm test`, `npm run <name>`). */
|
|
338
|
+
const NPM_SCRIPT_RE = /^npm(?:\.cmd)?\s+(?:(test|t)|run(?:-script)?\s+([A-Za-z0-9_][A-Za-z0-9_.:@+-]*))$/;
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The acceptance commands of a dispatch's DoD as `routing.run` names (handoff 13): only exact npm script forms count.
|
|
342
|
+
* P2c.2: a check with its own `cwd` does not run in the work root, so the dispatch gets no run signal at all (`[]`).
|
|
343
|
+
*/
|
|
344
|
+
export function acceptanceScriptsOf(dod: DoD): string[] {
|
|
345
|
+
if (dod.kind !== "deterministic") return [];
|
|
346
|
+
if (dod.checks.some((check) => check.cwd !== undefined)) return [];
|
|
347
|
+
return dod.checks.flatMap((check) => {
|
|
348
|
+
const match = typeof check.command === "string" ? NPM_SCRIPT_RE.exec(check.command.trim()) : null;
|
|
349
|
+
return match === null ? [] : [match[1] !== undefined ? "test" : (match[2] as string)];
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
|
|
336
353
|
// ---------------------------------------------------------------------------
|
|
337
354
|
// Re-dispatch of the same task to a higher tier
|
|
338
355
|
// ---------------------------------------------------------------------------
|