opencode-model-router 2.8.0 → 2.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +372 -0
- package/README.md +22 -2
- package/package.json +5 -1
- package/src/commands/output.ts +23 -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 +2656 -114
- 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 +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- 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/rules.ts +11 -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/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
- package/tiers.json +5 -5
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
// src/executor/compile/residue.ts
|
|
2
|
+
// Phase 2.3.5 — the architect residue: request, response validation and monotone merge (memo 2.3.1 §6).
|
|
3
|
+
// Pure: no I/O, no git, no clock. Paths are checked lexically against the ledger's roots.
|
|
4
|
+
// `index.mergeResidue` (2.3.6) recomputes `conflict` edges, runs `validate` and sets the status afterwards.
|
|
5
|
+
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
|
|
8
|
+
import { parseRouteLine } from "../../routing/classify/route-line";
|
|
9
|
+
import type { Edge, JsonValue, LedgerV1, TaskId, TaskNode } from "../types";
|
|
10
|
+
|
|
11
|
+
/** Caps of one request (memo §6): anything over stays ⊤ (the caller warns `residue-capped`). */
|
|
12
|
+
export const RESIDUE_MAX_TASKS = 60;
|
|
13
|
+
export const RESIDUE_MAX_CANDIDATES = 120;
|
|
14
|
+
/** Per-task excerpt of the plan text sent to the architect. */
|
|
15
|
+
export const RESIDUE_EXCERPT_CHARS = 1500;
|
|
16
|
+
/** Maximum length of an `evidence` string in the response. */
|
|
17
|
+
export const RESIDUE_EVIDENCE_MAX = 300;
|
|
18
|
+
|
|
19
|
+
/** A candidate edge the compiler could not decide (unresolved phrase/graph ref, `merged first`, ownership, ...). */
|
|
20
|
+
export interface ResidueCandidate { from: string; to: string; why: string }
|
|
21
|
+
|
|
22
|
+
export interface ResidueFootprintEntry { taskId: TaskId; writes: string[]; reads: string[]; evidence: string }
|
|
23
|
+
export interface ResidueEdgeEntry { from: string; to: string; confidence: "medium" | "low"; evidence: string }
|
|
24
|
+
/** A validated response; paths are normalized repo-relative, `noChange` is always present. */
|
|
25
|
+
export interface ResidueResponse {
|
|
26
|
+
requestDigest: string;
|
|
27
|
+
footprints: ResidueFootprintEntry[];
|
|
28
|
+
edges: ResidueEdgeEntry[];
|
|
29
|
+
noChange: string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type ResidueValidation =
|
|
33
|
+
| { ok: true; value: ResidueResponse }
|
|
34
|
+
| { ok: false; code: string; at: string; detail: JsonValue };
|
|
35
|
+
|
|
36
|
+
/** JSON Schema of the response (`additionalProperties: false` at every level). */
|
|
37
|
+
export const RESIDUE_SCHEMA: JsonValue = {
|
|
38
|
+
type: "object",
|
|
39
|
+
required: ["requestDigest", "footprints", "edges"],
|
|
40
|
+
additionalProperties: false,
|
|
41
|
+
properties: {
|
|
42
|
+
requestDigest: { type: "string", pattern: "^[0-9a-f]{16}$" },
|
|
43
|
+
footprints: {
|
|
44
|
+
type: "array",
|
|
45
|
+
items: {
|
|
46
|
+
type: "object",
|
|
47
|
+
required: ["taskId", "writes", "reads", "evidence"],
|
|
48
|
+
additionalProperties: false,
|
|
49
|
+
properties: {
|
|
50
|
+
taskId: { type: "string" },
|
|
51
|
+
writes: { type: "array", items: { type: "string", minLength: 1 } },
|
|
52
|
+
reads: { type: "array", items: { type: "string", minLength: 1 } },
|
|
53
|
+
evidence: { type: "string", minLength: 1, maxLength: RESIDUE_EVIDENCE_MAX },
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
edges: {
|
|
58
|
+
type: "array",
|
|
59
|
+
items: {
|
|
60
|
+
type: "object",
|
|
61
|
+
required: ["from", "to", "confidence", "evidence"],
|
|
62
|
+
additionalProperties: false,
|
|
63
|
+
properties: {
|
|
64
|
+
from: { type: "string" },
|
|
65
|
+
to: { type: "string" },
|
|
66
|
+
confidence: { enum: ["medium", "low"] },
|
|
67
|
+
evidence: { type: "string", minLength: 1, maxLength: RESIDUE_EVIDENCE_MAX },
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
noChange: { type: "array", items: { type: "string" } },
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
76
|
+
// Task set and digest
|
|
77
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
/** Classes that read or think but do not edit (memo §4 "Editing"); `needs` decides first. */
|
|
80
|
+
const NON_EDITING_CLASSES: ReadonlySet<string> = new Set(["review", "design", "search", "recon"]);
|
|
81
|
+
const NON_EDITING_KINDS: ReadonlySet<string> = new Set(["manual", "preflight", "qa"]);
|
|
82
|
+
|
|
83
|
+
function has(o: object, key: string): boolean {
|
|
84
|
+
return Object.hasOwn(o, key);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Editing task (memo §4): not manual/preflight/qa; any write, or `needs` has `edit`, or no `needs` and an editing class. */
|
|
88
|
+
function isEditing(t: TaskNode): boolean {
|
|
89
|
+
if (NON_EDITING_KINDS.has(t.kind)) return false;
|
|
90
|
+
if (t.footprint.writes.length > 0) return true;
|
|
91
|
+
const fields = t.route.line === "" ? null : parseRouteLine(t.route.line, { positions: "any" }).line;
|
|
92
|
+
if (fields?.needs !== undefined) return fields.needs.includes("edit");
|
|
93
|
+
if (fields?.class === undefined) return true; // no information: an editing task writes ⊤, fail closed
|
|
94
|
+
return !NON_EDITING_CLASSES.has(fields.class);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function residueTaskIdsUncapped(draft: LedgerV1): TaskId[] {
|
|
98
|
+
const out: TaskId[] = [];
|
|
99
|
+
for (const [id, t] of Object.entries(draft.tasks)) {
|
|
100
|
+
if (!isEditing(t)) continue;
|
|
101
|
+
const c = t.footprint.confidence;
|
|
102
|
+
if (c === "unknown" || c === "inferred") out.push(id);
|
|
103
|
+
}
|
|
104
|
+
return out;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Tasks the architect is asked about: editing tasks whose footprint is `unknown` or `inferred`, in plan order,
|
|
109
|
+
* capped at `RESIDUE_MAX_TASKS`. Pure from the draft, so the digest is recomputable at validation time.
|
|
110
|
+
* Footprints that are `explicit` or `ownership` are never asked about, even when a suffix/basename match made them
|
|
111
|
+
* low-confidence: the ledger does not record that flag. An ownership-assumed footprint is `inferred` (QA-2.3-5), so it
|
|
112
|
+
* is asked about and the architect may add to it.
|
|
113
|
+
*/
|
|
114
|
+
export function residueTaskIds(draft: LedgerV1): TaskId[] {
|
|
115
|
+
return residueTaskIdsUncapped(draft).slice(0, RESIDUE_MAX_TASKS);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** How many tasks are over the cap (they stay ⊤); the caller emits warning `residue-capped` when > 0. */
|
|
119
|
+
export function residueOverflow(draft: LedgerV1): number {
|
|
120
|
+
return Math.max(0, residueTaskIdsUncapped(draft).length - RESIDUE_MAX_TASKS);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** First 16 hex of `sha256(planDigest + "\n" + taskIds.join(","))`. */
|
|
124
|
+
export function residueDigestOf(planDigest: string, taskIds: readonly TaskId[]): string {
|
|
125
|
+
return createHash("sha256").update(`${planDigest}\n${taskIds.join(",")}`).digest("hex").slice(0, 16);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
129
|
+
// Request
|
|
130
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
/** A role work root the route-line parser accepts (route-line.ts `isWorkRootPath`) and that can be written in `root=`. */
|
|
133
|
+
function routeRoot(toplevel: string): string | null {
|
|
134
|
+
if (!/^(?:[A-Za-z]:[\\/]|\/(?![\\/]))/.test(toplevel)) return null;
|
|
135
|
+
if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(toplevel) || toplevel.includes("\0")) return null;
|
|
136
|
+
if (/["\]\r\n]/.test(toplevel)) return null;
|
|
137
|
+
return /\s/.test(toplevel) ? `root="${toplevel}"` : `root=${toplevel}`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function cutExcerpt(text: string): string {
|
|
141
|
+
if (text.length <= RESIDUE_EXCERPT_CHARS) return text;
|
|
142
|
+
let end = RESIDUE_EXCERPT_CHARS;
|
|
143
|
+
const code = text.charCodeAt(end - 1);
|
|
144
|
+
if (code >= 0xd800 && code <= 0xdbff) end -= 1; // do not split a surrogate pair
|
|
145
|
+
return text.slice(0, end);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* The residue request, or `undefined` when there is nothing to ask. The prompt is one route line (so the router
|
|
150
|
+
* sends it to a heavy, pinned design role), `Writes: none.`, the request JSON (one line), the schema and the rules.
|
|
151
|
+
*/
|
|
152
|
+
export function residueRequestOf(
|
|
153
|
+
draft: LedgerV1,
|
|
154
|
+
candidates: readonly ResidueCandidate[],
|
|
155
|
+
): { prompt: string; schema: JsonValue; taskIds: TaskId[] } | undefined {
|
|
156
|
+
const taskIds = residueTaskIds(draft);
|
|
157
|
+
const capped = candidates.slice(0, RESIDUE_MAX_CANDIDATES);
|
|
158
|
+
if (taskIds.length === 0 && capped.length === 0) return undefined;
|
|
159
|
+
|
|
160
|
+
const requestDigest = residueDigestOf(draft.planDigest, taskIds);
|
|
161
|
+
const tasks: JsonValue[] = taskIds.map((id) => {
|
|
162
|
+
const t = draft.tasks[id] as TaskNode;
|
|
163
|
+
return {
|
|
164
|
+
id,
|
|
165
|
+
title: t.title,
|
|
166
|
+
kind: t.kind,
|
|
167
|
+
phase: t.phase,
|
|
168
|
+
routeLine: t.route.line,
|
|
169
|
+
footprint: {
|
|
170
|
+
writes: [...t.footprint.writes],
|
|
171
|
+
reads: [...t.footprint.reads],
|
|
172
|
+
confidence: t.footprint.confidence,
|
|
173
|
+
sources: [...t.footprint.sources],
|
|
174
|
+
},
|
|
175
|
+
excerpt: cutExcerpt(t.text),
|
|
176
|
+
};
|
|
177
|
+
});
|
|
178
|
+
const request: JsonValue = {
|
|
179
|
+
requestDigest,
|
|
180
|
+
tasks,
|
|
181
|
+
candidates: capped.map((c) => ({ from: c.from, to: c.to, why: c.why })),
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const root = routeRoot(draft.repo.toplevel);
|
|
185
|
+
const routeLine = `[route class=design risk=medium scope=multi d=none${root === null ? "" : ` ${root}`} tier=heavy pin]`;
|
|
186
|
+
const prompt = [
|
|
187
|
+
routeLine,
|
|
188
|
+
"Writes: none.",
|
|
189
|
+
"",
|
|
190
|
+
"You are the architect for a plan compiler. For the tasks below the compiler could not decide the files they",
|
|
191
|
+
"write or read, or the order between them. Read the repository (read-only) and answer with the missing facts.",
|
|
192
|
+
"",
|
|
193
|
+
"Request (JSON):",
|
|
194
|
+
JSON.stringify(request),
|
|
195
|
+
"",
|
|
196
|
+
"Response schema (JSON Schema):",
|
|
197
|
+
JSON.stringify(RESIDUE_SCHEMA),
|
|
198
|
+
"",
|
|
199
|
+
"Rules:",
|
|
200
|
+
"- Paths are repo-relative, '/'-separated: no drive, no '..', no URL, no ':'. Use a directory path only for a whole directory.",
|
|
201
|
+
"- For every task you list under `footprints`, restate its FULL footprint: every path already in `writes` and `reads`, plus the additions.",
|
|
202
|
+
" An entry that omits an existing path, or changes the write set of an `explicit` or `ownership` task, is rejected.",
|
|
203
|
+
"- `edges` order two tasks (`from` runs before `to`); `from` may be `gate:<phase>`. Use `confidence` `medium` or `low`.",
|
|
204
|
+
" Edges must not create a cycle. You cannot remove or delete anything.",
|
|
205
|
+
"- List in `noChange` the tasks that are confirmed to write nothing.",
|
|
206
|
+
`- Copy \`requestDigest\` exactly: ${requestDigest}. Every \`evidence\` is one short sentence (at most ${RESIDUE_EVIDENCE_MAX} characters).`,
|
|
207
|
+
"- Return `DONE:` followed by exactly one ```json block holding the response, nothing else.",
|
|
208
|
+
].join("\n");
|
|
209
|
+
|
|
210
|
+
return { prompt, schema: RESIDUE_SCHEMA, taskIds };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
214
|
+
// Parse
|
|
215
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
216
|
+
|
|
217
|
+
/** Last ```json block of `text`, else the whole text. `undefined` when it does not parse. */
|
|
218
|
+
export function parseResidue(text: string): unknown {
|
|
219
|
+
const re = /```json[^\S\r\n]*\r?\n([\s\S]*?)\r?\n?[^\S\r\n]*```/gi;
|
|
220
|
+
let last: string | undefined;
|
|
221
|
+
for (let m = re.exec(text); m !== null; m = re.exec(text)) last = m[1];
|
|
222
|
+
const source = last ?? text;
|
|
223
|
+
try {
|
|
224
|
+
return JSON.parse(source.trim()) as unknown;
|
|
225
|
+
} catch {
|
|
226
|
+
return undefined;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
231
|
+
// Validate
|
|
232
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
type Rec = Record<string, unknown>;
|
|
235
|
+
|
|
236
|
+
function isRec(v: unknown): v is Rec {
|
|
237
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function fail(code: string, at: string, extra: { [k: string]: JsonValue } = {}): ResidueValidation {
|
|
241
|
+
return { ok: false, code, at, detail: { code, at, ...extra } };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const DELETE_KEY_RE = /^(remove|delete|drop)/i;
|
|
245
|
+
|
|
246
|
+
function childPath(at: string, key: string): string {
|
|
247
|
+
return /^[A-Za-z_$][\w$]*$/.test(key) ? `${at}.${key}` : `${at}[${JSON.stringify(key)}]`;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** JSON path of the first key that asks for a removal (`remove*`/`delete*`/`drop*` or `op`) anywhere, else null. */
|
|
251
|
+
function findDeleteKey(root: unknown): string | null {
|
|
252
|
+
const stack: Array<{ v: unknown; at: string }> = [{ v: root, at: "$" }];
|
|
253
|
+
const seen = new Set<object>();
|
|
254
|
+
while (stack.length > 0) {
|
|
255
|
+
const cur = stack.pop() as { v: unknown; at: string };
|
|
256
|
+
if (typeof cur.v !== "object" || cur.v === null || seen.has(cur.v)) continue;
|
|
257
|
+
seen.add(cur.v);
|
|
258
|
+
if (Array.isArray(cur.v)) {
|
|
259
|
+
for (let i = cur.v.length - 1; i >= 0; i--) stack.push({ v: cur.v[i], at: `${cur.at}[${i}]` });
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const keys = Object.keys(cur.v);
|
|
263
|
+
for (const k of keys) if (DELETE_KEY_RE.test(k) || k === "op") return childPath(cur.at, k);
|
|
264
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
265
|
+
const k = keys[i] as string;
|
|
266
|
+
stack.push({ v: (cur.v as Rec)[k], at: childPath(cur.at, k) });
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
type SchemaResult = { ok: true; value: ResidueResponse } | { ok: false; at: string; why: string };
|
|
273
|
+
|
|
274
|
+
const DIGEST_RE = /^[0-9a-f]{16}$/;
|
|
275
|
+
|
|
276
|
+
function schemaFail(at: string, why: string): SchemaResult {
|
|
277
|
+
return { ok: false, at, why };
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function extraKey(o: Rec, allowed: readonly string[]): string | null {
|
|
281
|
+
for (const k of Object.keys(o)) if (!allowed.includes(k)) return k;
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function stringArray(v: unknown, at: string, nonEmpty: boolean): { ok: true; value: string[] } | { ok: false; at: string; why: string } {
|
|
286
|
+
if (!Array.isArray(v)) return { ok: false, at, why: "expected an array" };
|
|
287
|
+
const out: string[] = [];
|
|
288
|
+
for (let i = 0; i < v.length; i++) {
|
|
289
|
+
const s: unknown = v[i];
|
|
290
|
+
if (typeof s !== "string") return { ok: false, at: `${at}[${i}]`, why: "expected a string" };
|
|
291
|
+
if (nonEmpty && s.length === 0) return { ok: false, at: `${at}[${i}]`, why: "expected a non-empty string" };
|
|
292
|
+
out.push(s);
|
|
293
|
+
}
|
|
294
|
+
return { ok: true, value: out };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function evidenceOf(o: Rec, at: string): { ok: true; value: string } | { ok: false; at: string; why: string } {
|
|
298
|
+
const e = o.evidence;
|
|
299
|
+
if (typeof e !== "string") return { ok: false, at: `${at}.evidence`, why: "expected a string" };
|
|
300
|
+
if (e.length < 1 || e.length > RESIDUE_EVIDENCE_MAX) {
|
|
301
|
+
return { ok: false, at: `${at}.evidence`, why: `expected 1..${RESIDUE_EVIDENCE_MAX} characters` };
|
|
302
|
+
}
|
|
303
|
+
return { ok: true, value: e };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Hand-written check of `RESIDUE_SCHEMA`; the first violation wins. */
|
|
307
|
+
function checkSchema(v: unknown): SchemaResult {
|
|
308
|
+
if (!isRec(v)) return schemaFail("$", "expected an object");
|
|
309
|
+
for (const k of ["requestDigest", "footprints", "edges"]) {
|
|
310
|
+
if (!has(v, k)) return schemaFail(childPath("$", k), "required property is missing");
|
|
311
|
+
}
|
|
312
|
+
const extra = extraKey(v, ["requestDigest", "footprints", "edges", "noChange"]);
|
|
313
|
+
if (extra !== null) return schemaFail(childPath("$", extra), "additional property");
|
|
314
|
+
const digest = v.requestDigest;
|
|
315
|
+
if (typeof digest !== "string" || !DIGEST_RE.test(digest)) {
|
|
316
|
+
return schemaFail("$.requestDigest", "expected 16 lowercase hex characters");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const footprints: ResidueFootprintEntry[] = [];
|
|
320
|
+
if (!Array.isArray(v.footprints)) return schemaFail("$.footprints", "expected an array");
|
|
321
|
+
for (let i = 0; i < v.footprints.length; i++) {
|
|
322
|
+
const at = `$.footprints[${i}]`;
|
|
323
|
+
const e: unknown = v.footprints[i];
|
|
324
|
+
if (!isRec(e)) return schemaFail(at, "expected an object");
|
|
325
|
+
for (const k of ["taskId", "writes", "reads", "evidence"]) {
|
|
326
|
+
if (!has(e, k)) return schemaFail(childPath(at, k), "required property is missing");
|
|
327
|
+
}
|
|
328
|
+
const x = extraKey(e, ["taskId", "writes", "reads", "evidence"]);
|
|
329
|
+
if (x !== null) return schemaFail(childPath(at, x), "additional property");
|
|
330
|
+
if (typeof e.taskId !== "string") return schemaFail(`${at}.taskId`, "expected a string");
|
|
331
|
+
const writes = stringArray(e.writes, `${at}.writes`, true);
|
|
332
|
+
if (!writes.ok) return schemaFail(writes.at, writes.why);
|
|
333
|
+
const reads = stringArray(e.reads, `${at}.reads`, true);
|
|
334
|
+
if (!reads.ok) return schemaFail(reads.at, reads.why);
|
|
335
|
+
const ev = evidenceOf(e, at);
|
|
336
|
+
if (!ev.ok) return schemaFail(ev.at, ev.why);
|
|
337
|
+
footprints.push({ taskId: e.taskId, writes: writes.value, reads: reads.value, evidence: ev.value });
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const edges: ResidueEdgeEntry[] = [];
|
|
341
|
+
if (!Array.isArray(v.edges)) return schemaFail("$.edges", "expected an array");
|
|
342
|
+
for (let i = 0; i < v.edges.length; i++) {
|
|
343
|
+
const at = `$.edges[${i}]`;
|
|
344
|
+
const e: unknown = v.edges[i];
|
|
345
|
+
if (!isRec(e)) return schemaFail(at, "expected an object");
|
|
346
|
+
for (const k of ["from", "to", "confidence", "evidence"]) {
|
|
347
|
+
if (!has(e, k)) return schemaFail(childPath(at, k), "required property is missing");
|
|
348
|
+
}
|
|
349
|
+
const x = extraKey(e, ["from", "to", "confidence", "evidence"]);
|
|
350
|
+
if (x !== null) return schemaFail(childPath(at, x), "additional property");
|
|
351
|
+
if (typeof e.from !== "string") return schemaFail(`${at}.from`, "expected a string");
|
|
352
|
+
if (typeof e.to !== "string") return schemaFail(`${at}.to`, "expected a string");
|
|
353
|
+
if (e.confidence !== "medium" && e.confidence !== "low") {
|
|
354
|
+
return schemaFail(`${at}.confidence`, "expected \"medium\" or \"low\"");
|
|
355
|
+
}
|
|
356
|
+
const ev = evidenceOf(e, at);
|
|
357
|
+
if (!ev.ok) return schemaFail(ev.at, ev.why);
|
|
358
|
+
edges.push({ from: e.from, to: e.to, confidence: e.confidence, evidence: ev.value });
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
let noChange: string[] = [];
|
|
362
|
+
if (has(v, "noChange")) {
|
|
363
|
+
const n = stringArray(v.noChange, "$.noChange", false);
|
|
364
|
+
if (!n.ok) return schemaFail(n.at, n.why);
|
|
365
|
+
noChange = n.value;
|
|
366
|
+
}
|
|
367
|
+
return { ok: true, value: { requestDigest: digest, footprints, edges, noChange } };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// --- paths -----------------------------------------------------------------------------------------------------
|
|
371
|
+
|
|
372
|
+
type PathResult = { ok: true; path: string } | { ok: false; reason: string };
|
|
373
|
+
|
|
374
|
+
/** `/`-separated root without trailing slash; `ci` for drive roots (win32). */
|
|
375
|
+
function rootKey(root: string): { text: string; ci: boolean } {
|
|
376
|
+
const text = root.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
377
|
+
return { text, ci: /^[A-Za-z]:/.test(text) };
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Lexical normalization of one response path against the roots (no git, no filesystem): repo-relative, `/`-separated,
|
|
382
|
+
* no `.`/`..` segment, no trailing `/`, no `:` segment, no NUL. An absolute path is accepted only under a root.
|
|
383
|
+
*/
|
|
384
|
+
function normalizeResiduePath(raw: string, roots: ReadonlyArray<{ text: string; ci: boolean }>): PathResult {
|
|
385
|
+
if (raw.includes("\0")) return { ok: false, reason: "nul" };
|
|
386
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(raw) || /^file:/i.test(raw)) return { ok: false, reason: "url" };
|
|
387
|
+
let p = raw.replace(/\\/g, "/");
|
|
388
|
+
if (p.startsWith("//")) return { ok: false, reason: /^\/\/[?.]\//.test(p) ? "device" : "unc" };
|
|
389
|
+
if (/^\/\?\?\//.test(p)) return { ok: false, reason: "device" };
|
|
390
|
+
const absolute = p.startsWith("/") || /^[A-Za-z]:/.test(p);
|
|
391
|
+
if (absolute) {
|
|
392
|
+
let rel: string | null = null;
|
|
393
|
+
for (const r of roots) {
|
|
394
|
+
if (r.text === "") continue;
|
|
395
|
+
const head = p.slice(0, r.text.length);
|
|
396
|
+
const same = r.ci ? head.toLowerCase() === r.text.toLowerCase() : head === r.text;
|
|
397
|
+
if (same && p.charAt(r.text.length) === "/") {
|
|
398
|
+
rel = p.slice(r.text.length + 1);
|
|
399
|
+
break;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (rel === null) {
|
|
403
|
+
if (/^[A-Za-z]:/.test(p)) return { ok: false, reason: p.charAt(2) === "/" ? "other-drive" : "drive-relative" };
|
|
404
|
+
return { ok: false, reason: p.startsWith("/") && roots.some((r) => r.ci) ? "drive-less" : "outside" };
|
|
405
|
+
}
|
|
406
|
+
p = rel;
|
|
407
|
+
}
|
|
408
|
+
const out: string[] = [];
|
|
409
|
+
for (const seg of p.split("/")) {
|
|
410
|
+
if (seg === "" || seg === ".") continue;
|
|
411
|
+
if (seg === "..") {
|
|
412
|
+
if (out.length === 0) return { ok: false, reason: "escape" };
|
|
413
|
+
out.pop();
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (seg.includes(":")) return { ok: false, reason: "colon" };
|
|
417
|
+
out.push(seg);
|
|
418
|
+
}
|
|
419
|
+
if (out.length === 0) return { ok: false, reason: "empty" };
|
|
420
|
+
return { ok: true, path: out.join("/") };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function normalizeList(
|
|
424
|
+
list: readonly string[],
|
|
425
|
+
at: string,
|
|
426
|
+
roots: ReadonlyArray<{ text: string; ci: boolean }>,
|
|
427
|
+
ci: boolean,
|
|
428
|
+
): { ok: true; value: string[] } | { ok: false; at: string; path: string; reason: string } {
|
|
429
|
+
const out: string[] = [];
|
|
430
|
+
const keys = new Set<string>();
|
|
431
|
+
for (let i = 0; i < list.length; i++) {
|
|
432
|
+
const raw = list[i] as string;
|
|
433
|
+
const r = normalizeResiduePath(raw, roots);
|
|
434
|
+
if (!r.ok) return { ok: false, at: `${at}[${i}]`, path: raw, reason: r.reason };
|
|
435
|
+
const k = foldKey(r.path, ci);
|
|
436
|
+
if (!keys.has(k)) { keys.add(k); out.push(r.path); }
|
|
437
|
+
}
|
|
438
|
+
return { ok: true, value: out };
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// --- graph -----------------------------------------------------------------------------------------------------
|
|
442
|
+
|
|
443
|
+
function gateName(phase: string): string {
|
|
444
|
+
return `gate:${phase}`;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Shortest cycle through the first non-trivial strongly connected component, or null. Iterative, O(V+E) to detect. */
|
|
448
|
+
function findMinimalCycle(nodes: readonly string[], edges: ReadonlyArray<{ from: string; to: string }>): string[] | null {
|
|
449
|
+
const index = new Map<string, number>();
|
|
450
|
+
nodes.forEach((n, i) => index.set(n, i));
|
|
451
|
+
const adj: number[][] = nodes.map(() => []);
|
|
452
|
+
for (const e of edges) {
|
|
453
|
+
const a = index.get(e.from);
|
|
454
|
+
const b = index.get(e.to);
|
|
455
|
+
if (a !== undefined && b !== undefined) (adj[a] as number[]).push(b);
|
|
456
|
+
}
|
|
457
|
+
const n = nodes.length;
|
|
458
|
+
// Tarjan, iterative.
|
|
459
|
+
const idx: number[] = new Array<number>(n).fill(-1);
|
|
460
|
+
const low: number[] = new Array<number>(n).fill(0);
|
|
461
|
+
const onStack: boolean[] = new Array<boolean>(n).fill(false);
|
|
462
|
+
const comp: number[] = new Array<number>(n).fill(-1);
|
|
463
|
+
const stack: number[] = [];
|
|
464
|
+
let counter = 0;
|
|
465
|
+
let comps = 0;
|
|
466
|
+
const sizes: number[] = [];
|
|
467
|
+
for (let s = 0; s < n; s++) {
|
|
468
|
+
if (idx[s] !== -1) continue;
|
|
469
|
+
const work: Array<{ v: number; i: number }> = [{ v: s, i: 0 }];
|
|
470
|
+
idx[s] = low[s] = counter++;
|
|
471
|
+
stack.push(s);
|
|
472
|
+
onStack[s] = true;
|
|
473
|
+
while (work.length > 0) {
|
|
474
|
+
const top = work[work.length - 1] as { v: number; i: number };
|
|
475
|
+
const outs = adj[top.v] as number[];
|
|
476
|
+
if (top.i < outs.length) {
|
|
477
|
+
const w = outs[top.i++] as number;
|
|
478
|
+
if (idx[w] === -1) {
|
|
479
|
+
idx[w] = low[w] = counter++;
|
|
480
|
+
stack.push(w);
|
|
481
|
+
onStack[w] = true;
|
|
482
|
+
work.push({ v: w, i: 0 });
|
|
483
|
+
} else if (onStack[w]) {
|
|
484
|
+
low[top.v] = Math.min(low[top.v] as number, idx[w] as number);
|
|
485
|
+
}
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
work.pop();
|
|
489
|
+
const parent = work[work.length - 1];
|
|
490
|
+
if (parent !== undefined) low[parent.v] = Math.min(low[parent.v] as number, low[top.v] as number);
|
|
491
|
+
if (low[top.v] === idx[top.v]) {
|
|
492
|
+
let size = 0;
|
|
493
|
+
for (;;) {
|
|
494
|
+
const w = stack.pop() as number;
|
|
495
|
+
onStack[w] = false;
|
|
496
|
+
comp[w] = comps;
|
|
497
|
+
size++;
|
|
498
|
+
if (w === top.v) break;
|
|
499
|
+
}
|
|
500
|
+
sizes.push(size);
|
|
501
|
+
comps++;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
// First component (by node order) that is non-trivial or has a self-loop.
|
|
506
|
+
let target = -1;
|
|
507
|
+
for (let v = 0; v < n && target === -1; v++) {
|
|
508
|
+
const c = comp[v] as number;
|
|
509
|
+
if ((sizes[c] as number) > 1 || (adj[v] as number[]).includes(v)) target = c;
|
|
510
|
+
}
|
|
511
|
+
if (target === -1) return null;
|
|
512
|
+
const members: number[] = [];
|
|
513
|
+
for (let v = 0; v < n; v++) if (comp[v] === target) members.push(v);
|
|
514
|
+
|
|
515
|
+
let best: number[] | null = null;
|
|
516
|
+
for (const start of members) {
|
|
517
|
+
const prev = new Map<number, number>();
|
|
518
|
+
const queue: number[] = [start];
|
|
519
|
+
let found = false;
|
|
520
|
+
for (let head = 0; head < queue.length && !found; head++) {
|
|
521
|
+
const u = queue[head] as number;
|
|
522
|
+
for (const w of adj[u] as number[]) {
|
|
523
|
+
if (comp[w] !== target) continue;
|
|
524
|
+
if (w === start) {
|
|
525
|
+
const path: number[] = [u];
|
|
526
|
+
while (path[path.length - 1] !== start) path.push(prev.get(path[path.length - 1] as number) as number);
|
|
527
|
+
path.reverse();
|
|
528
|
+
if (best === null || path.length < best.length) best = path;
|
|
529
|
+
found = true;
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
if (!prev.has(w) && w !== start) {
|
|
533
|
+
prev.set(w, u);
|
|
534
|
+
queue.push(w);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
if (best !== null && best.length <= 2) break;
|
|
539
|
+
}
|
|
540
|
+
return best === null ? null : best.map((i) => nodes[i] as string);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Existing edges plus the response's edges that are new pairs (the merge rule), as pairs. */
|
|
544
|
+
function newEdges(draft: LedgerV1, r: ResidueResponse): ResidueEdgeEntry[] {
|
|
545
|
+
const seen = new Set<string>(draft.edges.map((e) => `${e.from}>${e.to}`));
|
|
546
|
+
const out: ResidueEdgeEntry[] = [];
|
|
547
|
+
for (const e of r.edges) {
|
|
548
|
+
const key = `${e.from}>${e.to}`;
|
|
549
|
+
if (seen.has(key)) continue;
|
|
550
|
+
seen.add(key);
|
|
551
|
+
out.push(e);
|
|
552
|
+
}
|
|
553
|
+
return out;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// --- validate --------------------------------------------------------------------------------------------------
|
|
557
|
+
|
|
558
|
+
function foldKey(p: string, ci: boolean): string {
|
|
559
|
+
return ci ? p.toLowerCase() : p;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** The members of `old` that `now` does not contain (compared by folded key). */
|
|
563
|
+
function missingFrom(old: readonly string[], now: readonly string[], ci: boolean): string[] {
|
|
564
|
+
const keys = new Set(now.map((x) => foldKey(x, ci)));
|
|
565
|
+
return old.filter((p) => !keys.has(foldKey(p, ci)));
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* Validates a parsed response against the draft. Order (first failure wins): `residue-json`, `residue-delete`,
|
|
570
|
+
* `residue-schema`, `residue-digest`, `residue-unknown-task` (also a task that was not part of the request),
|
|
571
|
+
* `residue-path`, `residue-weaken`, `residue-cycle`. Paths are normalized before the weaken check and compared by
|
|
572
|
+
* case-folded key when `o.ci` (default true, the safe side for a response). On success the value carries normalized
|
|
573
|
+
* repo-relative paths.
|
|
574
|
+
*/
|
|
575
|
+
export function validateResidue(draft: LedgerV1, v: unknown, o: { ci?: boolean } = {}): ResidueValidation {
|
|
576
|
+
const ci = o.ci ?? true;
|
|
577
|
+
if (v === undefined) return fail("residue-json", "$", { reason: "no parseable JSON" });
|
|
578
|
+
|
|
579
|
+
const del = findDeleteKey(v);
|
|
580
|
+
if (del !== null) return fail("residue-delete", del, { reason: "a residue can only add, never remove" });
|
|
581
|
+
|
|
582
|
+
const sch = checkSchema(v);
|
|
583
|
+
if (!sch.ok) return fail("residue-schema", sch.at, { reason: sch.why });
|
|
584
|
+
const r = sch.value;
|
|
585
|
+
|
|
586
|
+
const expected = residueDigestOf(draft.planDigest, residueTaskIds(draft));
|
|
587
|
+
if (r.requestDigest !== expected) {
|
|
588
|
+
return fail("residue-digest", "$.requestDigest", { expected, actual: r.requestDigest });
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const phaseIds = new Set(draft.phases.map((p) => p.id));
|
|
592
|
+
// QA-2.3-6: footprints and noChange may only name the tasks that were asked about (the capped request set).
|
|
593
|
+
const asked = new Set(residueTaskIds(draft));
|
|
594
|
+
for (let i = 0; i < r.footprints.length; i++) {
|
|
595
|
+
const id = (r.footprints[i] as ResidueFootprintEntry).taskId;
|
|
596
|
+
if (!has(draft.tasks, id)) return fail("residue-unknown-task", `$.footprints[${i}].taskId`, { id });
|
|
597
|
+
if (!asked.has(id)) return fail("residue-unknown-task", `$.footprints[${i}].taskId`, { id, reason: "not part of the request" });
|
|
598
|
+
}
|
|
599
|
+
for (let i = 0; i < r.edges.length; i++) {
|
|
600
|
+
const e = r.edges[i] as ResidueEdgeEntry;
|
|
601
|
+
const fromOk = has(draft.tasks, e.from) || (e.from.startsWith("gate:") && phaseIds.has(e.from.slice(5)));
|
|
602
|
+
if (!fromOk) return fail("residue-unknown-task", `$.edges[${i}].from`, { id: e.from });
|
|
603
|
+
if (!has(draft.tasks, e.to)) return fail("residue-unknown-task", `$.edges[${i}].to`, { id: e.to });
|
|
604
|
+
}
|
|
605
|
+
for (let i = 0; i < r.noChange.length; i++) {
|
|
606
|
+
const id = r.noChange[i] as string;
|
|
607
|
+
if (!has(draft.tasks, id)) return fail("residue-unknown-task", `$.noChange[${i}]`, { id });
|
|
608
|
+
if (!asked.has(id)) return fail("residue-unknown-task", `$.noChange[${i}]`, { id, reason: "not part of the request" });
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// QA-2.3-15: paths are normalized first, then compared by case-folded key (a response may respell the case).
|
|
612
|
+
const roots = [rootKey(draft.repo.toplevel), rootKey(draft.integration.worktree)];
|
|
613
|
+
const value: ResidueResponse = { ...r, footprints: [] };
|
|
614
|
+
for (let i = 0; i < r.footprints.length; i++) {
|
|
615
|
+
const e = r.footprints[i] as ResidueFootprintEntry;
|
|
616
|
+
const writes = normalizeList(e.writes, `$.footprints[${i}].writes`, roots, ci);
|
|
617
|
+
if (!writes.ok) return fail("residue-path", writes.at, { path: writes.path, reason: writes.reason });
|
|
618
|
+
const reads = normalizeList(e.reads, `$.footprints[${i}].reads`, roots, ci);
|
|
619
|
+
if (!reads.ok) return fail("residue-path", reads.at, { path: reads.path, reason: reads.reason });
|
|
620
|
+
value.footprints.push({ ...e, writes: writes.value, reads: reads.value });
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
for (let i = 0; i < value.footprints.length; i++) {
|
|
624
|
+
const e = value.footprints[i] as ResidueFootprintEntry;
|
|
625
|
+
const old = (draft.tasks[e.taskId] as TaskNode).footprint;
|
|
626
|
+
const at = `$.footprints[${i}]`;
|
|
627
|
+
// An explicit or ownership task is never in the residue task list, so an entry for it is rejected earlier
|
|
628
|
+
// (`residue-unknown-task`, "not part of the request"); only the omitted-paths rule remains here.
|
|
629
|
+
const missingWrites = missingFrom(old.writes, e.writes, ci);
|
|
630
|
+
const missingReads = missingFrom(old.reads, e.reads, ci);
|
|
631
|
+
if (missingWrites.length > 0 || missingReads.length > 0) {
|
|
632
|
+
return fail("residue-weaken", at, {
|
|
633
|
+
reason: "omits existing paths",
|
|
634
|
+
taskId: e.taskId,
|
|
635
|
+
missingWrites,
|
|
636
|
+
missingReads,
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
const nodes: string[] = [...Object.keys(draft.tasks), ...draft.phases.map((p) => gateName(p.id))];
|
|
642
|
+
const pairs: Array<{ from: string; to: string }> = [
|
|
643
|
+
...draft.edges.map((e) => ({ from: e.from as string, to: e.to })),
|
|
644
|
+
...newEdges(draft, value).map((e) => ({ from: e.from, to: e.to })),
|
|
645
|
+
];
|
|
646
|
+
for (const [id, t] of Object.entries(draft.tasks)) {
|
|
647
|
+
if (t.phase !== null) pairs.push({ from: id, to: gateName(t.phase) }); // implicit: a task is part of its phase gate
|
|
648
|
+
}
|
|
649
|
+
const cycle = findMinimalCycle(nodes, pairs);
|
|
650
|
+
if (cycle !== null) return fail("residue-cycle", "$.edges", { cycle });
|
|
651
|
+
|
|
652
|
+
return { ok: true, value };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
656
|
+
// Merge
|
|
657
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
658
|
+
|
|
659
|
+
function union(a: readonly string[], b: readonly string[], ci: boolean): string[] {
|
|
660
|
+
const out = [...a];
|
|
661
|
+
const keys = new Set(a.map((p) => foldKey(p, ci)));
|
|
662
|
+
for (const p of b) {
|
|
663
|
+
const k = foldKey(p, ci);
|
|
664
|
+
if (!keys.has(k)) { keys.add(k); out.push(p); }
|
|
665
|
+
}
|
|
666
|
+
return out;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* Monotone merge of a validated response: write/read sets only grow, `llm` is added to the sources, `unknown`
|
|
671
|
+
* becomes `inferred` (never any other confidence change), `noChange` ids go `unknown` → `inferred` without paths.
|
|
672
|
+
* New edges are `kind:"llm"` with at most `medium` confidence; existing pairs are skipped. Status, `seq` and the
|
|
673
|
+
* `conflict` edges are the caller's (`index.mergeResidue`). The input is not modified.
|
|
674
|
+
*/
|
|
675
|
+
export function mergeResidueInto(draft: LedgerV1, r: ResidueResponse, o: { ci?: boolean } = {}): LedgerV1 {
|
|
676
|
+
const ci = o.ci ?? true;
|
|
677
|
+
const tasks: Record<TaskId, TaskNode> = { ...draft.tasks };
|
|
678
|
+
for (const e of r.footprints) {
|
|
679
|
+
const t = tasks[e.taskId];
|
|
680
|
+
if (t === undefined || !has(tasks, e.taskId)) continue;
|
|
681
|
+
const fp = t.footprint;
|
|
682
|
+
tasks[e.taskId] = {
|
|
683
|
+
...t,
|
|
684
|
+
footprint: {
|
|
685
|
+
writes: union(fp.writes, e.writes, ci),
|
|
686
|
+
reads: union(fp.reads, e.reads, ci),
|
|
687
|
+
confidence: fp.confidence === "unknown" ? "inferred" : fp.confidence,
|
|
688
|
+
sources: fp.sources.includes("llm") ? [...fp.sources] : [...fp.sources, "llm"],
|
|
689
|
+
},
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
for (const id of r.noChange) {
|
|
693
|
+
const t = tasks[id];
|
|
694
|
+
if (t === undefined || !has(tasks, id) || t.footprint.confidence !== "unknown") continue;
|
|
695
|
+
tasks[id] = { ...t, footprint: { ...t.footprint, writes: [...t.footprint.writes], reads: [...t.footprint.reads],
|
|
696
|
+
sources: [...t.footprint.sources], confidence: "inferred" } };
|
|
697
|
+
}
|
|
698
|
+
const added: Edge[] = newEdges(draft, r).map((e) => ({
|
|
699
|
+
from: e.from as Edge["from"],
|
|
700
|
+
to: e.to,
|
|
701
|
+
kind: "llm" as const,
|
|
702
|
+
confidence: e.confidence === "low" ? ("low" as const) : ("medium" as const),
|
|
703
|
+
evidence: `residue: ${e.evidence}`,
|
|
704
|
+
}));
|
|
705
|
+
return { ...draft, tasks, edges: [...draft.edges, ...added] };
|
|
706
|
+
}
|