opencode-model-router 2.3.0 → 2.5.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 +171 -0
- package/README.md +86 -11
- package/package.json +6 -1
- package/src/commands/output.ts +21 -1
- package/src/compat/v2-hooks.ts +1374 -24
- package/src/escalate/ladder.ts +12 -0
- package/src/guard/enforce.ts +186 -22
- package/src/guard/guards.ts +132 -6
- package/src/guard/store.ts +5 -0
- package/src/index.ts +718 -29
- package/src/router/config.ts +247 -1
- package/src/router/dispatch-header.ts +46 -4
- package/src/router/git-tools.ts +1152 -0
- package/src/router/guard-profile.ts +100 -0
- package/src/router/plugin-agents.ts +433 -0
- package/src/router/prompts.ts +26 -1
- package/src/router/protocol.ts +133 -0
- package/src/router/read-only.ts +149 -0
- package/src/router/role-agents.ts +409 -0
- package/src/router/roles-config.ts +429 -0
- package/src/router/roles.ts +600 -0
- package/src/router/run-tools.ts +913 -0
- package/src/router/sensitive-paths.ts +101 -0
- package/src/router/sessions.ts +92 -0
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +193 -1
- package/src/routing/advisor/index.ts +13 -5
- package/src/routing/classify/index.ts +23 -5
- package/src/routing/classify/route-line.ts +67 -3
- package/src/routing/classify/rules.ts +80 -20
- package/src/routing/classify/types.ts +34 -4
- package/src/routing/commands/stats.ts +3 -0
- package/src/routing/engine/kernel.ts +163 -0
- package/src/routing/engine/ladders.ts +242 -1
- package/src/routing/engine/protocol-line.ts +17 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/types.ts +99 -1
- package/src/routing/outcomes/beta.ts +10 -4
- package/src/routing/outcomes/index.ts +44 -1
- package/src/routing/outcomes/ingest.ts +163 -15
- package/src/routing/outcomes/persist.ts +23 -1
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +273 -2
- package/src/routing/outcomes/store.ts +25 -5
- package/src/routing/outcomes/types.ts +145 -6
- package/src/routing/roles/authority.ts +495 -0
- package/src/routing/roles/binding.ts +543 -0
- package/src/routing/roles/policy.ts +416 -0
- package/src/routing/roles/work-root.ts +132 -0
- package/src/routing/wire/dispatch.ts +1306 -17
- package/src/routing/wire/hint.ts +14 -0
- package/src/routing/wire/runtime.ts +117 -28
- package/src/tui/effort-channel.ts +220 -0
- package/src/tui/effort-rpc.ts +60 -0
- package/src/tui/host-types.ts +154 -0
- package/src/tui/opentui-solid.d.ts +16 -0
- package/src/tui/plugin.ts +1007 -0
- package/src/tui/status-model.ts +561 -0
- package/src/v2.ts +26 -1
- package/src/verify/checker.ts +249 -7
- package/src/verify/deterministic.ts +10 -1
- package/src/verify/dispatch.ts +63 -6
- package/src/verify/dod.ts +127 -10
- package/src/verify/gate.ts +75 -7
- package/src/verify/types.ts +12 -0
- package/src/verify/wiring.ts +55 -10
- package/tiers.json +13 -5
- package/tui.ts +4 -0
|
@@ -36,6 +36,30 @@ const ROUTE_MENTION_RE = /\[route/i;
|
|
|
36
36
|
*/
|
|
37
37
|
const NEEDS_LIST_RE = /(\bneeds=[a-z_]*)((?:\s*,\s*[a-z_]+(?![a-z_]|\s*=))+)/gi;
|
|
38
38
|
const LINE_SPLIT_RE = /(\r\n|\n|\r)/;
|
|
39
|
+
/** `root="D:\my dir"`: the only way to carry whitespace in a value; extracted before tokenising. */
|
|
40
|
+
const QUOTED_ROOT_RE = /\broot\s*=\s*"([^"]*)"/gi;
|
|
41
|
+
const QUOTED_PLACEHOLDER_RE = /^@q(\d+)$/;
|
|
42
|
+
/** `tier=` literals the parser can know; the engine validates against the active tier list. */
|
|
43
|
+
const TIER_NAMES = ["fast", "medium", "heavy"] as const;
|
|
44
|
+
export const ROUTE_BUDGET_MAX = 10000;
|
|
45
|
+
/** A drive-absolute Windows path (`D:\…`, `D:/…`) or a POSIX path with exactly one leading `/`. */
|
|
46
|
+
const WORK_ROOT_RE = /^(?:[A-Za-z]:[\\/]|\/(?![\\/]))/;
|
|
47
|
+
/** A `..` path segment, with either separator. */
|
|
48
|
+
const PARENT_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
|
|
49
|
+
/**
|
|
50
|
+
* A first line that starts like a route line (`[route` + a separator, `]` or the end) but is not one (QA-P12-1-6).
|
|
51
|
+
* `[router …]` and friends are other tags, not malformed route lines.
|
|
52
|
+
*/
|
|
53
|
+
const ROUTE_START_RE = /^[ \t]*\[route(?![A-Za-z0-9_-])/i;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* A role work root (QA-P12-1-6): a local, drive-absolute Windows path or a POSIX path. Rejected: relative and
|
|
57
|
+
* drive-relative paths, every `\\` or `//` prefix (UNC `\\host\share`, `\\?\`, `\\.\` device paths — a work root is a
|
|
58
|
+
* local worktree), any `..` segment, and NUL.
|
|
59
|
+
*/
|
|
60
|
+
function isWorkRootPath(value: string): boolean {
|
|
61
|
+
return WORK_ROOT_RE.test(value) && !PARENT_SEGMENT_RE.test(value) && !value.includes("\0");
|
|
62
|
+
}
|
|
39
63
|
|
|
40
64
|
function isMember<T extends string>(values: readonly T[], value: string): value is T {
|
|
41
65
|
return (values as readonly string[]).includes(value);
|
|
@@ -71,10 +95,15 @@ function parseFields(body: string): RouteLine {
|
|
|
71
95
|
let needs: readonly Need[] | undefined;
|
|
72
96
|
let detection: Detection | undefined;
|
|
73
97
|
let pin = false;
|
|
98
|
+
let tier: string | undefined;
|
|
99
|
+
let budget: number | undefined;
|
|
100
|
+
let root: string | undefined;
|
|
74
101
|
const ignored: string[] = [];
|
|
75
102
|
const seen = new Set<string>();
|
|
76
103
|
|
|
104
|
+
const quotedRoots: string[] = [];
|
|
77
105
|
const tokens = body
|
|
106
|
+
.replace(QUOTED_ROOT_RE, (_whole, path: string) => `root=@q${quotedRoots.push(path) - 1}`)
|
|
78
107
|
.replace(/\s*=\s*/g, "=")
|
|
79
108
|
.replace(NEEDS_LIST_RE, (_whole, head: string, tail: string) => head + tail.replace(/\s+/g, ""))
|
|
80
109
|
.split(/\s+/)
|
|
@@ -82,7 +111,8 @@ function parseFields(body: string): RouteLine {
|
|
|
82
111
|
for (const token of tokens) {
|
|
83
112
|
const eq = token.indexOf("=");
|
|
84
113
|
const key = stripTail((eq === -1 ? token : token.slice(0, eq)).toLowerCase());
|
|
85
|
-
const
|
|
114
|
+
const rawValue = eq === -1 ? null : token.slice(eq + 1);
|
|
115
|
+
const value = rawValue === null ? null : stripTail(rawValue.toLowerCase());
|
|
86
116
|
if (key === "") {
|
|
87
117
|
ignored.push(token);
|
|
88
118
|
continue;
|
|
@@ -121,6 +151,23 @@ function parseFields(body: string): RouteLine {
|
|
|
121
151
|
else pin = parsed;
|
|
122
152
|
break;
|
|
123
153
|
}
|
|
154
|
+
case "tier":
|
|
155
|
+
if (value !== null && isMember(TIER_NAMES, value)) tier = value;
|
|
156
|
+
else ignored.push(key);
|
|
157
|
+
break;
|
|
158
|
+
case "budget": {
|
|
159
|
+
const n = value !== null && /^\d+$/.test(value) ? Number(value) : 0;
|
|
160
|
+
if (n >= 1 && n <= ROUTE_BUDGET_MAX) budget = n;
|
|
161
|
+
else ignored.push(key);
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
case "root": {
|
|
165
|
+
const q = value === null ? null : QUOTED_PLACEHOLDER_RE.exec(value);
|
|
166
|
+
const candidate = q ? quotedRoots[Number(q[1])] : rawValue === null ? undefined : stripTail(rawValue);
|
|
167
|
+
if (candidate !== undefined && isWorkRootPath(candidate)) root = candidate;
|
|
168
|
+
else ignored.push(key);
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
124
171
|
default:
|
|
125
172
|
ignored.push(key);
|
|
126
173
|
}
|
|
@@ -132,6 +179,9 @@ function parseFields(body: string): RouteLine {
|
|
|
132
179
|
...(scope ? { scope } : {}),
|
|
133
180
|
...(needs ? { needs } : {}),
|
|
134
181
|
...(detection ? { detection } : {}),
|
|
182
|
+
...(tier ? { tier } : {}),
|
|
183
|
+
...(budget !== undefined ? { budget } : {}),
|
|
184
|
+
...(root ? { root } : {}),
|
|
135
185
|
pin,
|
|
136
186
|
ignored,
|
|
137
187
|
};
|
|
@@ -157,7 +207,7 @@ function isRecognisable(line: string, inFence: boolean): boolean {
|
|
|
157
207
|
}
|
|
158
208
|
|
|
159
209
|
function canonical(line: RouteLine): string {
|
|
160
|
-
return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin]);
|
|
210
|
+
return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin, line.tier, line.budget, line.root]);
|
|
161
211
|
}
|
|
162
212
|
|
|
163
213
|
/**
|
|
@@ -189,12 +239,18 @@ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
|
|
|
189
239
|
const risk = keep("risk", first.risk, (l) => l.risk);
|
|
190
240
|
const scope = keep("scope", first.scope, (l) => l.scope);
|
|
191
241
|
const needs = keep("needs", first.needs, (l) => l.needs);
|
|
242
|
+
const tier = keep("tier", first.tier, (l) => l.tier);
|
|
243
|
+
const budget = keep("budget", first.budget, (l) => l.budget);
|
|
244
|
+
const root = keep("root", first.root, (l) => l.root);
|
|
192
245
|
if (lines.some((l) => l.detection !== undefined)) ignored.push("conflict:d");
|
|
193
246
|
return {
|
|
194
247
|
...(taskClass ? { class: taskClass } : {}),
|
|
195
248
|
...(risk ? { risk } : {}),
|
|
196
249
|
...(scope ? { scope } : {}),
|
|
197
250
|
...(needs ? { needs } : {}),
|
|
251
|
+
...(tier ? { tier } : {}),
|
|
252
|
+
...(budget !== undefined ? { budget } : {}),
|
|
253
|
+
...(root ? { root } : {}),
|
|
198
254
|
// The first line is the directive; a later line cannot take its pin away or add one (A22).
|
|
199
255
|
pin: first.pin,
|
|
200
256
|
ignored,
|
|
@@ -242,6 +298,12 @@ export function parseRouteLine(text: string, options: RouteLineOptions = {}): Ro
|
|
|
242
298
|
lastNonEmpty = i;
|
|
243
299
|
});
|
|
244
300
|
|
|
301
|
+
// QA-P12-1-6: a first non-empty line that starts like a route line but does not parse is flagged, never silently
|
|
302
|
+
// dropped. It stays text (not stripped, not applied), so tier-mode facts are unchanged.
|
|
303
|
+
const head = firstNonEmpty >= 0 ? lines[firstNonEmpty]! : "";
|
|
304
|
+
const malformed = firstNonEmpty >= 0 && !fenced[firstNonEmpty] && !INDENTED_CODE_RE.test(head)
|
|
305
|
+
&& ROUTE_START_RE.test(head) && !isRecognisable(head, false);
|
|
306
|
+
|
|
245
307
|
const kept: string[] = [];
|
|
246
308
|
const parsed: RouteLine[] = [];
|
|
247
309
|
let edgeOnly = true;
|
|
@@ -259,15 +321,17 @@ export function parseRouteLine(text: string, options: RouteLineOptions = {}): Ro
|
|
|
259
321
|
parsed.push(parseFields(ROUTE_LINE_RE.exec(line)?.[1] ?? ""));
|
|
260
322
|
}
|
|
261
323
|
if (parsed.length === 0) {
|
|
262
|
-
return { line: null, count: 0, stripped: kept.join(""), conflict: false, edgeOnly: true };
|
|
324
|
+
return { line: null, count: 0, stripped: kept.join(""), conflict: false, edgeOnly: true, ...(malformed ? { malformed } : {}) };
|
|
263
325
|
}
|
|
264
326
|
const conflict = new Set(parsed.map(canonical)).size > 1;
|
|
265
327
|
return {
|
|
328
|
+
// QA-P12-2-2: the flag lives on the parse result only; the line's `ignored` list is the tier-mode one.
|
|
266
329
|
line: conflict ? resolveConflict(parsed) : parsed[0]!,
|
|
267
330
|
count: parsed.length,
|
|
268
331
|
stripped: kept.join(""),
|
|
269
332
|
conflict,
|
|
270
333
|
edgeOnly,
|
|
334
|
+
...(malformed ? { malformed } : {}),
|
|
271
335
|
};
|
|
272
336
|
}
|
|
273
337
|
const RISK_ORDER: readonly Risk[] = RISKS;
|
|
@@ -218,10 +218,20 @@ function scan(re: RegExp, s: string, visit: (match: RegExpExecArray) => boolean)
|
|
|
218
218
|
|
|
219
219
|
/** True when at least one term has an occurrence (not negated, unless `negation` is false). */
|
|
220
220
|
function hasHit(res: readonly RegExp[], s: string, negation: boolean): boolean {
|
|
221
|
-
|
|
222
|
-
|
|
221
|
+
return firstHit(res, s, negation) !== null;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** The first occurrence {@link hasHit} finds (terms in order): the index of its term and its text, or null. */
|
|
225
|
+
function firstHit(res: readonly RegExp[], s: string, negation: boolean): { readonly index: number; readonly text: string } | null {
|
|
226
|
+
for (const [index, re] of res.entries()) {
|
|
227
|
+
let hit: string | null = null;
|
|
228
|
+
if (scan(re, s, (m) => {
|
|
229
|
+
if (negation && isNegatedAt(s, m.index)) return false;
|
|
230
|
+
hit = m[0];
|
|
231
|
+
return true;
|
|
232
|
+
})) return { index, text: hit ?? "" };
|
|
223
233
|
}
|
|
224
|
-
return
|
|
234
|
+
return null;
|
|
225
235
|
}
|
|
226
236
|
|
|
227
237
|
// ---------------------------------------------------------------------------
|
|
@@ -417,17 +427,77 @@ function normalizePath(path: string): string {
|
|
|
417
427
|
return path.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
418
428
|
}
|
|
419
429
|
|
|
420
|
-
|
|
430
|
+
/** The first absolute path of `needsText` outside `cwd` (not negated), as written; null when there is none. */
|
|
431
|
+
function externalPath(needsText: string, cwd: string): string | null {
|
|
421
432
|
const base = normalizePath(cwd);
|
|
422
433
|
for (const re of ABS_PATH_RES) {
|
|
423
|
-
|
|
434
|
+
let found: string | null = null;
|
|
435
|
+
if (scan(re, needsText, (m) => {
|
|
424
436
|
if (isNegatedAt(needsText, m.index)) return false;
|
|
425
437
|
const path = normalizePath(trimPathTail(m[0]));
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
438
|
+
if (path === base || path.startsWith(base + "/")) return false;
|
|
439
|
+
found = trimPathTail(m[0]);
|
|
440
|
+
return true;
|
|
441
|
+
})) return found;
|
|
429
442
|
}
|
|
430
|
-
return
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* One need R9 found in a text, and why — never text of the prompt itself (D14, QA-G-B-2-2): the matched vocabulary word
|
|
448
|
+
* (lower-cased, e.g. `update`, `run the tests`), else the term's id in the needs table (`term-<n>`); `url` for a URL;
|
|
449
|
+
* `path` for an absolute path outside cwd; `implied-by-<need>`.
|
|
450
|
+
*/
|
|
451
|
+
export interface NeedMatch {
|
|
452
|
+
readonly need: Need;
|
|
453
|
+
readonly term: string;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** A matched vocabulary word: letters, blanks and hyphens only, short. Anything else (a URL, a path, a file name, `&&`) is not. */
|
|
457
|
+
const VOCABULARY_WORD = /^[a-z][a-z -]{0,39}$/;
|
|
458
|
+
|
|
459
|
+
/** QA-G-B-2-2: how a term match is named in a {@link NeedMatch} (see there). */
|
|
460
|
+
function termLabel(need: Need, hit: { readonly index: number; readonly text: string }): string {
|
|
461
|
+
if (need === "web" && /^https?:\/\//i.test(hit.text)) return "url";
|
|
462
|
+
const word = hit.text.toLowerCase().replace(/\s+/g, " ").trim();
|
|
463
|
+
return VOCABULARY_WORD.test(word) ? word : `term-${hit.index}`;
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* R9 on the needs text: the needs its vocabulary and its absolute paths outside `cwd` name (class-implied needs are added by the
|
|
468
|
+
* caller). `matches`, when given, collects why ({@link NeedMatch}).
|
|
469
|
+
*/
|
|
470
|
+
function scanNeeds(needsText: string, cwd: string | null, matches?: NeedMatch[]): Set<Need> {
|
|
471
|
+
const needs = new Set<Need>();
|
|
472
|
+
const pathFreeText = withoutPaths(needsText);
|
|
473
|
+
for (const rule of COMPILED_NEEDS) {
|
|
474
|
+
const hit = firstHit(rule.res, rule.need === "external_dir" ? needsText : pathFreeText, true);
|
|
475
|
+
if (hit === null) continue;
|
|
476
|
+
needs.add(rule.need);
|
|
477
|
+
matches?.push({ need: rule.need, term: termLabel(rule.need, hit) });
|
|
478
|
+
for (const implied of rule.implies) {
|
|
479
|
+
needs.add(implied);
|
|
480
|
+
matches?.push({ need: implied, term: `implied-by-${rule.need}` });
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (cwd !== null && !needs.has("external_dir") && externalPath(needsText, cwd) !== null) {
|
|
484
|
+
needs.add("external_dir");
|
|
485
|
+
matches?.push({ need: "external_dir", term: "path" });
|
|
486
|
+
}
|
|
487
|
+
return needs;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* #84 QA-G-B-3: the needs R9 finds in `text` itself (the text `analyzeRules` is given, the same `cwd` rule) and why, in the order
|
|
492
|
+
* of the needs table — never the class-implied needs, never text of the prompt (QA-G-B-2-2). Pure; decides nothing by itself.
|
|
493
|
+
*/
|
|
494
|
+
export function needMatchesOf(text: string, ctx?: { cwd?: string }): NeedMatch[] {
|
|
495
|
+
const raw = collapseLongRuns(String(text ?? "").slice(0, RULES_MAX_CHARS));
|
|
496
|
+
const body = prepareBody(raw);
|
|
497
|
+
const { needsText, environmentText } = splitSections(body);
|
|
498
|
+
const matches: NeedMatch[] = [];
|
|
499
|
+
scanNeeds(needsText, resolveCwd(body, environmentText, ctx), matches);
|
|
500
|
+
return matches;
|
|
431
501
|
}
|
|
432
502
|
|
|
433
503
|
// ---------------------------------------------------------------------------
|
|
@@ -547,17 +617,7 @@ export function analyzeRules(
|
|
|
547
617
|
: CONFIDENCE.rulesMultiple;
|
|
548
618
|
|
|
549
619
|
// R9 — needs
|
|
550
|
-
const needs =
|
|
551
|
-
const pathFreeText = withoutPaths(needsText);
|
|
552
|
-
for (const rule of COMPILED_NEEDS) {
|
|
553
|
-
if (hasHit(rule.res, rule.need === "external_dir" ? needsText : pathFreeText, true)) {
|
|
554
|
-
needs.add(rule.need);
|
|
555
|
-
for (const implied of rule.implies) needs.add(implied);
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
if (cwd !== null && !needs.has("external_dir") && hasExternalPath(needsText, cwd)) {
|
|
559
|
-
needs.add("external_dir");
|
|
560
|
-
}
|
|
620
|
+
const needs = scanNeeds(needsText, cwd);
|
|
561
621
|
for (const implied of CLASS_IMPLIED_NEEDS[taskClass]) needs.add(implied);
|
|
562
622
|
|
|
563
623
|
// R10 — scope
|
|
@@ -282,6 +282,21 @@ export interface RouteLine {
|
|
|
282
282
|
readonly needs?: readonly Need[];
|
|
283
283
|
/** Present only when `d=` carried a valid DETECTIONS value; then source is `plan`. */
|
|
284
284
|
readonly detection?: Detection;
|
|
285
|
+
/** `tier=fast|medium|heavy`; the engine checks it against the active tier list. */
|
|
286
|
+
readonly tier?: string;
|
|
287
|
+
/** `budget=<int>`, 1..10000. */
|
|
288
|
+
readonly budget?: number;
|
|
289
|
+
/**
|
|
290
|
+
* `root=<absolute path>`: the work root of a role dispatch (plan §2.2), as written (not normalised).
|
|
291
|
+
* - Accepted: a drive-absolute Windows path (`D:\…`, `D:/…`) or a POSIX path (`/…`). Rejected at parse
|
|
292
|
+
* (QA-P12-1-6): relative and drive-relative paths, any `\\`/`//` prefix (UNC `\\host\share`, `\\?\`, `\\.\`),
|
|
293
|
+
* any `..` segment, NUL. Quote it to carry spaces (`root="D:\My Work\Repo"`).
|
|
294
|
+
* - Limitation: a `]` cannot appear in the value (it closes the route line; even quoted).
|
|
295
|
+
* - Read it ONLY from `ClassifyResult.trace.routeLine` (QA-P12-1-9): never re-parse the prompt.
|
|
296
|
+
* - Handoff (P2.1): normalise the text (separators, case on Windows, trailing separator) and compare it with
|
|
297
|
+
* `git worktree list --porcelain` BEFORE any filesystem call on it; no match → no work root.
|
|
298
|
+
*/
|
|
299
|
+
readonly root?: string;
|
|
285
300
|
/** Bare `pin` flag (or `pin=true|yes|1`). */
|
|
286
301
|
readonly pin: boolean;
|
|
287
302
|
/** Keys that were unknown or whose values were invalid (for logging only). */
|
|
@@ -303,6 +318,12 @@ export interface RouteLineParse {
|
|
|
303
318
|
readonly conflict: boolean;
|
|
304
319
|
/** Every recognised route line is the first or the last non-empty line of the text (trusted positions). */
|
|
305
320
|
readonly edgeOnly: boolean;
|
|
321
|
+
/**
|
|
322
|
+
* QA-P12-1-6: the first non-empty line starts like a route line (`[route` then a blank, `]` or the end; not
|
|
323
|
+
* fenced, quoted or indented) but is not one (unbalanced, too long, ...). That line stays text and is neither
|
|
324
|
+
* applied nor stripped, and no `ignored` list changes (tier mode unchanged, QA-P12-2-2). Absent otherwise.
|
|
325
|
+
*/
|
|
326
|
+
readonly malformed?: true;
|
|
306
327
|
}
|
|
307
328
|
|
|
308
329
|
/** Structural facts from the classifyTrivial shape gates (rules.ts `shapeOf`). */
|
|
@@ -341,7 +362,16 @@ export interface ClassifyTrace {
|
|
|
341
362
|
readonly rules: TaskFacts;
|
|
342
363
|
readonly routeLine: RouteLine | null;
|
|
343
364
|
/** Route lines seen in the prompt, for the decision row (QA-1.2-2). */
|
|
344
|
-
readonly routeLines: {
|
|
365
|
+
readonly routeLines: {
|
|
366
|
+
readonly count: number;
|
|
367
|
+
readonly conflict: boolean;
|
|
368
|
+
readonly edgeOnly: boolean;
|
|
369
|
+
/**
|
|
370
|
+
* QA-P12-2-2: `RouteLineParse.malformed` — the sanctioned field for P2.1 to surface a malformed first route line.
|
|
371
|
+
* `classify()` copies it from the parse (absent = not malformed); the P2.1 role path refuses such a dispatch.
|
|
372
|
+
*/
|
|
373
|
+
readonly malformed?: true;
|
|
374
|
+
};
|
|
345
375
|
/** The backend was not consulted although the rules were unsure: the task names a credential (QA-1.2-1). */
|
|
346
376
|
readonly backendSkipped?: "credentials";
|
|
347
377
|
readonly backend: {
|
|
@@ -437,8 +467,8 @@ export interface KeywordRule {
|
|
|
437
467
|
|
|
438
468
|
/**
|
|
439
469
|
* The rules table. Shipped taskPatterns (tiers.json):
|
|
440
|
-
* fast: search, grep, read, git-info, ls, lookup-docs/types, count, exists-check
|
|
441
|
-
* medium: impl-feature, refactor, write-tests, bugfix(≤2), edit-logic, code-review,
|
|
470
|
+
* fast: search, grep, read, git-info, ls, lookup-docs/types, count, exists-check
|
|
471
|
+
* medium: rename, impl-feature, refactor, write-tests, bugfix(≤2), edit-logic, code-review,
|
|
442
472
|
* build-fix, create-file, db-migrate, api-endpoint, config-update
|
|
443
473
|
* heavy: arch-design, debug(≥3fail), sec-audit, perf-opt, migrate-strategy,
|
|
444
474
|
* multi-system-integration, tradeoff-analysis, rca
|
|
@@ -536,7 +566,7 @@ export const KEYWORD_RULES: readonly KeywordRule[] = [
|
|
|
536
566
|
},
|
|
537
567
|
{
|
|
538
568
|
pattern: "rename",
|
|
539
|
-
tier: "
|
|
569
|
+
tier: "medium",
|
|
540
570
|
class: "mechanical",
|
|
541
571
|
terms: [
|
|
542
572
|
/\brenam(?:e|es|ed|ing)\b/i,
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
*
|
|
11
11
|
* Failure policy (§0.10.10): never throws. A usage error or an unreadable store comes back as text with a non-zero `exit`, exactly
|
|
12
12
|
* as the script prints it on stderr; a failing flush is logged and the table is read from disk as it is.
|
|
13
|
+
*
|
|
14
|
+
* Role rows (P2.2): the "By role × tier" section is rendered by `runStatsCli` itself (`summarizeRoles` + `renderRoleMarkdown`), which is
|
|
15
|
+
* why the in-session output and the script agree for role rows; a log without role rows renders exactly as before.
|
|
13
16
|
*/
|
|
14
17
|
|
|
15
18
|
import { readFileSync } from "node:fs";
|
|
@@ -50,13 +50,17 @@ import type {
|
|
|
50
50
|
UnitCandidate,
|
|
51
51
|
} from "../outcomes/types";
|
|
52
52
|
import { makeKey, normalizeVariant, splitModelRef } from "../outcomes/types";
|
|
53
|
+
import { effectiveFactsOf } from "../roles/policy";
|
|
53
54
|
import type {
|
|
54
55
|
Candidate,
|
|
56
|
+
ChosenDispatch,
|
|
55
57
|
Decision,
|
|
56
58
|
DecisionInput,
|
|
57
59
|
DecisionReasonCode,
|
|
58
60
|
IneligibleReason,
|
|
59
61
|
Ladder,
|
|
62
|
+
RoleDecision,
|
|
63
|
+
RoleDecisionInput,
|
|
60
64
|
} from "./types";
|
|
61
65
|
|
|
62
66
|
// ---------------------------------------------------------------------------
|
|
@@ -595,3 +599,162 @@ function freezeDecision(d: Decision): Decision {
|
|
|
595
599
|
Object.freeze(d.ineligible);
|
|
596
600
|
return Object.freeze(d);
|
|
597
601
|
}
|
|
602
|
+
|
|
603
|
+
// ---------------------------------------------------------------------------
|
|
604
|
+
// Role dispatches (role-tier-assurance plan §2.1, §2.3, P1.2 T1.2.3/T1.2.4)
|
|
605
|
+
// ---------------------------------------------------------------------------
|
|
606
|
+
|
|
607
|
+
/** Upper bound of `routing.exploration.rate` (plan PLAN-14: off by default, at most one dispatch in five). */
|
|
608
|
+
export const MAX_EXPLORATION_RATE = 0.2;
|
|
609
|
+
|
|
610
|
+
/** The exploration rate actually used: finite values clamped to `[0, MAX_EXPLORATION_RATE]`, anything else 0 (off). */
|
|
611
|
+
export function explorationRate(rate: unknown): number {
|
|
612
|
+
return isFiniteNumber(rate) && rate > 0 ? Math.min(rate, MAX_EXPLORATION_RATE) : 0;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Deterministic draws in [0, 1) seeded by a string (FNV-1a 32-bit → mulberry32). Pure: the same seed yields the same
|
|
617
|
+
* sequence, so a decision row can be replayed from its `decisionID`.
|
|
618
|
+
*/
|
|
619
|
+
function seededDraws(seed: string): () => number {
|
|
620
|
+
let h = 0x811c9dc5;
|
|
621
|
+
for (let i = 0; i < seed.length; i++) {
|
|
622
|
+
h ^= seed.charCodeAt(i);
|
|
623
|
+
h = Math.imul(h, 0x01000193);
|
|
624
|
+
}
|
|
625
|
+
let s = h >>> 0;
|
|
626
|
+
return () => {
|
|
627
|
+
s = (s + 0x6d2b79f5) >>> 0;
|
|
628
|
+
let t = s;
|
|
629
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
630
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
631
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** `a` sits strictly above `b` on the escalate ladder: a higher rank, or `b`'s own model on a higher-effort variant at its rank. */
|
|
636
|
+
function rungAbove(a: Candidate, b: Candidate): boolean {
|
|
637
|
+
return a.rank > b.rank || (a.rank === b.rank && lowerEffortOnSameModel(b, a));
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** First candidate of the first window tier at or above `rank` that has one, else of the highest tier that has one. */
|
|
641
|
+
function roleCandidateAt(ladder: RoleDecisionInput["ladder"], rank: number): number | null {
|
|
642
|
+
for (const t of ladder.tiers) if (t.rank >= rank && t.first !== null) return t.first;
|
|
643
|
+
for (let i = ladder.tiers.length - 1; i >= 0; i--) if (ladder.tiers[i]!.first !== null) return ladder.tiers[i]!.first;
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* Decide one ROLE dispatch (T1.2.3, T1.2.4) on a `ladders.buildRoleLadder` graph. Tier-mode {@link decide} is untouched;
|
|
649
|
+
* this runs it with the role's pick and adds the role rules:
|
|
650
|
+
*
|
|
651
|
+
* 0. facts = `effectiveFactsOf(input.classified)` (raise-only risk/scope, QA-P12-1-1); `detection` is EFFECTIVE (branded).
|
|
652
|
+
* 1. base = the pinned tier's rung when the window has a pin, else the static default (class tier clamped into
|
|
653
|
+
* `[floor, ceiling]`); on a resume, raised to the running rung when that rung is a candidate above it
|
|
654
|
+
* (`resume:running`), else to the first rung at the running model's capability rank (`resume:off-ladder`) or, when
|
|
655
|
+
* that rank is unknown, to the window ceiling (`resume:off-ladder:lift`). Never below the running rung.
|
|
656
|
+
* 2. `decide` with `chosen` = base, `pin` = pinned, `floorRank` = the window floor: A27 (evidence gate) and A34
|
|
657
|
+
* (never-down against the capability rank) apply exactly as in tier mode; every candidate is inside the window.
|
|
658
|
+
* 3. `enforce` applies the kernel's switch, except on a resume (A30: `kept:resume`, the decision is only logged).
|
|
659
|
+
* 4. Exploration (T1.2.4, `enforce` only): with rate `r = explorationRate(exploration.rate)` > 0, never when pinned,
|
|
660
|
+
* resumed, `facts.risk == high` or `detection != deterministic`; targets = the candidates at or above the floor and
|
|
661
|
+
* strictly below the static default. Draw `u, v` from the `decisionID` seed: `u < r` → dispatch target
|
|
662
|
+
* `⌊v·|targets|⌋` (reason `explore`, `switched` false). This is the one documented exception to D9 "never down".
|
|
663
|
+
* `propensity` = P(dispatch) under this ε-greedy mixture: `(1 − r)·[dispatch = exploit] + r/|targets|·[dispatch ∈ targets]`,
|
|
664
|
+
* 1 when no draw was possible.
|
|
665
|
+
*
|
|
666
|
+
* I2: `dispatch` is always a candidate, so always inside `[floor, ceiling]`. An empty ladder → `dispatch` null
|
|
667
|
+
* (`window:no-candidates`): P2.1 refuses the role dispatch and never falls back to `buildEscalatePolicy`/`buildLadder`
|
|
668
|
+
* (QA-P12-1-5).
|
|
669
|
+
*/
|
|
670
|
+
export function decideRole(input: RoleDecisionInput): RoleDecision {
|
|
671
|
+
const { ladder } = input;
|
|
672
|
+
const facts = effectiveFactsOf(input.classified);
|
|
673
|
+
const cands = ladder.candidates;
|
|
674
|
+
const reasons: string[] = [...ladder.reasons];
|
|
675
|
+
const pinned = ladder.pinnedIndex !== null;
|
|
676
|
+
let base = ladder.pinnedIndex ?? ladder.staticDefault;
|
|
677
|
+
|
|
678
|
+
const resume = input.resume ?? null;
|
|
679
|
+
if (resume !== null && base !== null) {
|
|
680
|
+
const running = canonicalRung(resume);
|
|
681
|
+
const at = cands.findIndex((c) => {
|
|
682
|
+
const own = canonicalRung(c);
|
|
683
|
+
return own.model === running.model && own.variant === running.variant;
|
|
684
|
+
});
|
|
685
|
+
if (at >= 0) {
|
|
686
|
+
if (rungAbove(cands[at]!, cands[base]!)) {
|
|
687
|
+
base = at;
|
|
688
|
+
reasons.push("resume:running");
|
|
689
|
+
}
|
|
690
|
+
} else {
|
|
691
|
+
// QA-P12-1-3: a running model that is not a candidate is still never moved below: raise to the first rung at its
|
|
692
|
+
// capability rank (preset table); an unknown rank fails closed to the window ceiling.
|
|
693
|
+
const rank = capabilityRank(ladder, resume, null);
|
|
694
|
+
const lifted = rank === null ? roleCandidateAt(ladder, ladder.ceilingRank ?? Infinity) : roleCandidateAt(ladder, rank);
|
|
695
|
+
if (lifted !== null && cands[lifted]!.rank > cands[base]!.rank) base = lifted;
|
|
696
|
+
reasons.push(rank === null ? "resume:off-ladder:lift" : "resume:off-ladder");
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const chosen: ChosenDispatch = base === null
|
|
701
|
+
? { agent: { origin: "role", id: ladder.role }, model: "", variant: null }
|
|
702
|
+
: { agent: cands[base]!.agent, model: cands[base]!.model, variant: cands[base]!.variant };
|
|
703
|
+
const decision = decide({
|
|
704
|
+
facts,
|
|
705
|
+
chosen,
|
|
706
|
+
ladder,
|
|
707
|
+
detection: input.detection,
|
|
708
|
+
pin: pinned,
|
|
709
|
+
routing: input.routing,
|
|
710
|
+
store: input.store,
|
|
711
|
+
floorRank: ladder.floorRank,
|
|
712
|
+
orchestrator: input.orchestrator ?? null,
|
|
713
|
+
...(input.remainingTurns !== undefined ? { remainingTurns: input.remainingTurns } : {}),
|
|
714
|
+
});
|
|
715
|
+
if (base === null) {
|
|
716
|
+
return Object.freeze({ decision, base: null, dispatch: null, switched: false, explore: false, propensity: 1, reasons: Object.freeze(reasons) });
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const enforce = input.engine === "enforce";
|
|
720
|
+
const resumed = resume !== null;
|
|
721
|
+
if (resumed && decision.switched) reasons.push("kept:resume");
|
|
722
|
+
const switched = enforce && !resumed && decision.switched && decision.target !== null;
|
|
723
|
+
const exploit = switched ? cands.indexOf(decision.target!) : base;
|
|
724
|
+
|
|
725
|
+
// --- exploration (T1.2.4) --------------------------------------------------------------------------------
|
|
726
|
+
const rate = enforce ? explorationRate(input.exploration?.rate) : 0;
|
|
727
|
+
const targets: number[] = [];
|
|
728
|
+
const def = ladder.staticDefault;
|
|
729
|
+
const floorRank = ladder.floorRank;
|
|
730
|
+
const eligible = rate > 0 && !pinned && !resumed && facts.risk !== "high" && input.detection === "deterministic";
|
|
731
|
+
if (eligible && def !== null && floorRank !== null) {
|
|
732
|
+
for (let k = 0; k < cands.length; k++) {
|
|
733
|
+
if (cands[k]!.rank >= floorRank && rungAbove(cands[def]!, cands[k]!)) targets.push(k);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
let dispatch = exploit;
|
|
737
|
+
let explore = false;
|
|
738
|
+
let propensity = 1;
|
|
739
|
+
if (targets.length > 0) {
|
|
740
|
+
const draw = seededDraws(input.exploration!.decisionID);
|
|
741
|
+
const u = draw();
|
|
742
|
+
const v = draw();
|
|
743
|
+
if (u < rate) {
|
|
744
|
+
explore = true;
|
|
745
|
+
dispatch = targets[Math.min(targets.length - 1, Math.floor(v * targets.length))]!;
|
|
746
|
+
reasons.push("explore");
|
|
747
|
+
}
|
|
748
|
+
propensity = (dispatch === exploit ? 1 - rate : 0) + (targets.includes(dispatch) ? rate / targets.length : 0);
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
return Object.freeze({
|
|
752
|
+
decision,
|
|
753
|
+
base: cands[base]!,
|
|
754
|
+
dispatch: cands[dispatch]!,
|
|
755
|
+
switched: switched && !explore,
|
|
756
|
+
explore,
|
|
757
|
+
propensity,
|
|
758
|
+
reasons: Object.freeze(reasons),
|
|
759
|
+
});
|
|
760
|
+
}
|