opencode-model-router 2.2.0 → 2.4.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.
Files changed (83) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +90 -12
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +24 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +1435 -44
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +496 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/guard/enforce.ts +186 -22
  13. package/src/guard/guards.ts +132 -6
  14. package/src/guard/store.ts +5 -0
  15. package/src/index.ts +1193 -56
  16. package/src/router/build-info.ts +151 -0
  17. package/src/router/config.ts +1611 -19
  18. package/src/router/dispatch-header.ts +46 -4
  19. package/src/router/git-tools.ts +1152 -0
  20. package/src/router/guard-profile.ts +100 -0
  21. package/src/router/plugin-agents.ts +433 -0
  22. package/src/router/prompts.ts +26 -1
  23. package/src/router/protocol.ts +180 -0
  24. package/src/router/read-only.ts +149 -0
  25. package/src/router/role-agents.ts +409 -0
  26. package/src/router/roles-config.ts +429 -0
  27. package/src/router/roles.ts +600 -0
  28. package/src/router/run-tools.ts +913 -0
  29. package/src/router/sensitive-paths.ts +101 -0
  30. package/src/router/sessions.ts +533 -9
  31. package/src/router/subagents.ts +28 -1
  32. package/src/routing/advisor/findings.ts +898 -0
  33. package/src/routing/advisor/index.ts +614 -0
  34. package/src/routing/classify/backends/host.ts +163 -0
  35. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  36. package/src/routing/classify/backends/shared.ts +741 -0
  37. package/src/routing/classify/backends/typesafe.ts +315 -0
  38. package/src/routing/classify/fences.ts +96 -0
  39. package/src/routing/classify/index.ts +594 -0
  40. package/src/routing/classify/route-line.ts +362 -0
  41. package/src/routing/classify/rules.ts +667 -0
  42. package/src/routing/classify/scrub.ts +214 -0
  43. package/src/routing/classify/state.ts +148 -0
  44. package/src/routing/classify/text.ts +20 -0
  45. package/src/routing/classify/types.ts +1310 -0
  46. package/src/routing/commands/annotate-plan.ts +652 -0
  47. package/src/routing/commands/stats.ts +134 -0
  48. package/src/routing/commands/v1-roles.ts +64 -0
  49. package/src/routing/engine/index.ts +32 -0
  50. package/src/routing/engine/kernel.ts +760 -0
  51. package/src/routing/engine/ladders.ts +802 -0
  52. package/src/routing/engine/plan.ts +404 -0
  53. package/src/routing/engine/protocol-line.ts +150 -0
  54. package/src/routing/engine/roles-taxonomy.ts +52 -0
  55. package/src/routing/engine/simulate.ts +167 -0
  56. package/src/routing/engine/types.ts +368 -0
  57. package/src/routing/file-lock.ts +53 -0
  58. package/src/routing/outcomes/beta.ts +147 -0
  59. package/src/routing/outcomes/cost.ts +313 -0
  60. package/src/routing/outcomes/index.ts +215 -0
  61. package/src/routing/outcomes/ingest.ts +960 -0
  62. package/src/routing/outcomes/persist.ts +1080 -0
  63. package/src/routing/outcomes/signals.ts +650 -0
  64. package/src/routing/outcomes/stats.ts +873 -0
  65. package/src/routing/outcomes/store.ts +673 -0
  66. package/src/routing/outcomes/types.ts +1093 -0
  67. package/src/routing/roles/authority.ts +495 -0
  68. package/src/routing/roles/binding.ts +543 -0
  69. package/src/routing/roles/policy.ts +416 -0
  70. package/src/routing/roles/work-root.ts +132 -0
  71. package/src/routing/wire/dispatch.ts +2088 -0
  72. package/src/routing/wire/hint.ts +222 -0
  73. package/src/routing/wire/host-info.ts +256 -0
  74. package/src/routing/wire/runtime.ts +348 -0
  75. package/src/v2.ts +40 -1
  76. package/src/verify/checker.ts +249 -7
  77. package/src/verify/deterministic.ts +10 -1
  78. package/src/verify/dispatch.ts +63 -6
  79. package/src/verify/dod.ts +127 -10
  80. package/src/verify/gate.ts +75 -7
  81. package/src/verify/types.ts +12 -0
  82. package/src/verify/wiring.ts +55 -10
  83. package/tiers.json +13 -5
@@ -0,0 +1,667 @@
1
+ /**
2
+ * Deterministic task classifier (M2, rules layer) — design R1–R14 of
3
+ * `docs/qa/cost-aware-routing/phase-1.2.md`.
4
+ *
5
+ * Pure: no I/O, no clock, no randomness. Every regex is compiled once at module
6
+ * load (a `gi` copy of the `i` regexes of the `types.ts` table); the only
7
+ * per-call allocations are strings, sets and the result object.
8
+ *
9
+ * Two regex-state rules keep this module safe to call repeatedly:
10
+ * - the compiled `gi` copies are private to this module and every scan resets
11
+ * `lastIndex` before and after use (the loops below are synchronous);
12
+ * - the GLOBAL `SHAPE_GATES.pathToken` / `bareFilename` regexes that
13
+ * `classifyTrivial` also uses are touched only through `String#match`.
14
+ */
15
+
16
+ import type { RouterConfig } from "../../router/config";
17
+ import { normTaskKw } from "../../router/sessions";
18
+ import { collapseLongRuns } from "./text";
19
+ import {
20
+ ACCEPTANCE_BLOCK_RE,
21
+ CLASS_BASE_RISK,
22
+ CLASS_COST_RANK,
23
+ CLASS_EXCLUDED_SECTIONS,
24
+ CLASS_IMPLIED_NEEDS,
25
+ CONFIDENCE,
26
+ CWD_LINE_RE,
27
+ DIRECTIVE_LINE_RES,
28
+ ENGLISH_MARKERS,
29
+ HIGH_RISK_CASE_SENSITIVE_TERMS,
30
+ HIGH_RISK_TERMS,
31
+ KEYWORD_RULES,
32
+ MEDIUM_RISK_TERMS,
33
+ NEED_RULES,
34
+ NEEDS,
35
+ NEEDS_EXCLUDED_SECTIONS,
36
+ NEGATION_PREFIX_RE,
37
+ NEGATION_WINDOW_CHARS,
38
+ NON_ASCII_LETTER_SHARE,
39
+ NON_ENGLISH_MARKERS,
40
+ NON_ENGLISH_MIN_LETTERS,
41
+ NON_ENGLISH_MIN_WORDS,
42
+ POSIX_ABS_PATH_RE,
43
+ PROHIBITION_SECTIONS,
44
+ REPO_SCOPE_TERMS,
45
+ RISKS,
46
+ RULES_MAX_CHARS,
47
+ SECTION_HEADER_RE,
48
+ SHAPE_GATES,
49
+ TEMPLATE_MIN_SECTIONS,
50
+ TEMPLATE_SECTION_LABELS,
51
+ TIER_DEFAULT_CLASS,
52
+ WINDOWS_ABS_PATH_RE,
53
+ type Need,
54
+ type Risk,
55
+ type RulesAnalysis,
56
+ type Scope,
57
+ type ShapeFacts,
58
+ type StaticTier,
59
+ type TaskClass,
60
+ type TaskFacts,
61
+ } from "./types";
62
+
63
+ type RulesConfig = Pick<RouterConfig, "taskPatterns">;
64
+
65
+ /** Prefix of the class text measured by the shape gates (see analyzeRules). */
66
+ const SHAPE_WINDOW_CHARS = 2000;
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // Module-load compilation
70
+ // ---------------------------------------------------------------------------
71
+
72
+ function globalCopy(re: RegExp): RegExp {
73
+ return new RegExp(re.source, "gi");
74
+ }
75
+
76
+ function escapeRegExp(s: string): string {
77
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
78
+ }
79
+
80
+ interface CompiledRule {
81
+ readonly pattern: string;
82
+ readonly class: TaskClass;
83
+ readonly res: readonly RegExp[];
84
+ }
85
+
86
+ /**
87
+ * One compiled rule per `KEYWORD_RULES` entry: its terms plus the pattern's
88
+ * stem. Two entries share the pattern `read` (search and recon); the stem
89
+ * belongs to the FIRST one only, otherwise every "read X" would also credit
90
+ * `recon` and a single lookup could never be classified `search`.
91
+ */
92
+ const COMPILED_RULES: readonly CompiledRule[] = (() => {
93
+ const stemmed = new Set<string>();
94
+ return KEYWORD_RULES.map((rule): CompiledRule => {
95
+ const res = rule.terms.map(globalCopy);
96
+ const stem = normTaskKw(rule.pattern);
97
+ if (stem.length >= 3 && !stemmed.has(rule.pattern)) {
98
+ res.push(new RegExp("\\b" + escapeRegExp(stem) + "\\b", "gi"));
99
+ }
100
+ stemmed.add(rule.pattern);
101
+ return { pattern: rule.pattern, class: rule.class, res };
102
+ });
103
+ })();
104
+
105
+ interface CompiledNeed {
106
+ readonly need: Need;
107
+ readonly implies: readonly Need[];
108
+ readonly res: readonly RegExp[];
109
+ }
110
+
111
+ const COMPILED_NEEDS: readonly CompiledNeed[] = NEED_RULES.map((rule) => ({
112
+ need: rule.need,
113
+ implies: rule.implies ?? [],
114
+ res: rule.terms.map(globalCopy),
115
+ }));
116
+
117
+ const HIGH_RISK_RES: readonly RegExp[] = [
118
+ ...HIGH_RISK_TERMS.map(globalCopy),
119
+ ...HIGH_RISK_CASE_SENSITIVE_TERMS.map((re) => new RegExp(re.source, "g")),
120
+ ];
121
+ const MEDIUM_RISK_RES: readonly RegExp[] = MEDIUM_RISK_TERMS.map(globalCopy);
122
+ const REPO_SCOPE_RES: readonly RegExp[] = REPO_SCOPE_TERMS.map(globalCopy);
123
+ const ABS_PATH_RES: readonly RegExp[] = [WINDOWS_ABS_PATH_RE, POSIX_ABS_PATH_RE].map(globalCopy);
124
+ const ACCEPTANCE_ALL_RE = new RegExp(ACCEPTANCE_BLOCK_RE.source, "gi");
125
+ const CWD_LINE_ALL_RE = new RegExp(CWD_LINE_RE.source, "gi");
126
+
127
+ /**
128
+ * Path-like tokens, removed before the needs vocabulary runs (external_dir is
129
+ * the exception: it reads paths). `D:\git\repo` and `~/git/x` are places, not
130
+ * the `git` tool; "read/search/write" is a list, not a write (QA-1.2-5). URLs
131
+ * are left alone: a candidate may not start right after `:` or `/`.
132
+ */
133
+ const PATHLIKE_RES: readonly RegExp[] = [
134
+ globalCopy(WINDOWS_ABS_PATH_RE),
135
+ /(?<![\w:/.~-])\/[\w.@+-]+(?:\/[\w.@+-]*)*/g,
136
+ /(?<!\w)~[\\/][^\s"'`]*/g,
137
+ /(?<![\w:/\\.~@+-])[\w.@+-]+(?:[\\/][\w.@+-]*)+/g,
138
+ ];
139
+
140
+ function withoutPaths(text: string): string {
141
+ let out = text;
142
+ for (const re of PATHLIKE_RES) out = out.replace(re, " ");
143
+ return out;
144
+ }
145
+
146
+ const TEMPLATE_LABELS: ReadonlySet<string> = new Set(TEMPLATE_SECTION_LABELS);
147
+ const CLASS_EXCLUDED: ReadonlySet<string> = new Set(CLASS_EXCLUDED_SECTIONS);
148
+ const NEEDS_EXCLUDED: ReadonlySet<string> = new Set(NEEDS_EXCLUDED_SECTIONS);
149
+ const PROHIBITIONS: ReadonlySet<string> = new Set(PROHIBITION_SECTIONS);
150
+ const ENGLISH_WORDS: ReadonlySet<string> = new Set(ENGLISH_MARKERS);
151
+ const NON_ENGLISH_WORDS: ReadonlySet<string> = new Set(NON_ENGLISH_MARKERS);
152
+
153
+ /** `tier:pattern` pairs of the table; a user entry equal to one of them is a built-in. */
154
+ const BUILTIN_PAIRS: ReadonlySet<string> = new Set(
155
+ KEYWORD_RULES.map((rule) => `${rule.tier}\u0000${rule.pattern}`),
156
+ );
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // Matching and negation (R5)
160
+ // ---------------------------------------------------------------------------
161
+
162
+ function isSpace(code: number): boolean {
163
+ return code === 32 || code === 9 || code === 10 || code === 13 || code === 0xa0;
164
+ }
165
+
166
+ /**
167
+ * Does the character at `k` of `s` end a clause? `; : ! ? ,` and newline always
168
+ * do; an em dash does; a `.` only when whitespace (or the end) follows it, so the
169
+ * dot of `a.ts` or `1.2` does not cut a negation window short; a hyphen or en
170
+ * dash only as a spaced separator (` - `, ` – `), never inside `read-only`
171
+ * (QA-1.2-13).
172
+ */
173
+ function isClauseBoundaryAt(s: string, k: number): boolean {
174
+ const code = s.charCodeAt(k);
175
+ if (code === 59 || code === 58 || code === 33 || code === 63 || code === 44 || code === 10) return true;
176
+ if (code === 0x2014) return true;
177
+ if (code === 46) return k + 1 >= s.length || isSpace(s.charCodeAt(k + 1));
178
+ if (code === 45 || code === 0x2013) {
179
+ return k > 0 && k + 1 < s.length && isSpace(s.charCodeAt(k - 1)) && isSpace(s.charCodeAt(k + 1));
180
+ }
181
+ return false;
182
+ }
183
+
184
+ /** R5: is the occurrence of a term at `index` of `s` preceded by a negator in its clause? */
185
+ function isNegatedAt(s: string, index: number): boolean {
186
+ let start = index - NEGATION_WINDOW_CHARS;
187
+ if (start < 0) start = 0;
188
+ for (let k = index - 1; k >= start; k--) {
189
+ if (isClauseBoundaryAt(s, k)) {
190
+ start = k + 1;
191
+ break;
192
+ }
193
+ }
194
+ if (start >= index) return false;
195
+ return NEGATION_PREFIX_RE.test(s.slice(start, index));
196
+ }
197
+
198
+ /**
199
+ * Visit every occurrence of `re` (a private `g` regex) in `s` until `visit`
200
+ * returns true. Resets `lastIndex` on every exit so no state leaks between calls.
201
+ */
202
+ function scan(re: RegExp, s: string, visit: (match: RegExpExecArray) => boolean): boolean {
203
+ re.lastIndex = 0;
204
+ let m: RegExpExecArray | null;
205
+ while ((m = re.exec(s)) !== null) {
206
+ if (m[0].length === 0) {
207
+ re.lastIndex++;
208
+ continue;
209
+ }
210
+ if (visit(m)) {
211
+ re.lastIndex = 0;
212
+ return true;
213
+ }
214
+ }
215
+ re.lastIndex = 0;
216
+ return false;
217
+ }
218
+
219
+ /** True when at least one term has an occurrence (not negated, unless `negation` is false). */
220
+ function hasHit(res: readonly RegExp[], s: string, negation: boolean): boolean {
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 ?? "" };
233
+ }
234
+ return null;
235
+ }
236
+
237
+ // ---------------------------------------------------------------------------
238
+ // User taskPatterns not in the table (R6)
239
+ // ---------------------------------------------------------------------------
240
+
241
+ interface CustomPattern {
242
+ readonly re: RegExp;
243
+ readonly class: TaskClass;
244
+ readonly anchor: string;
245
+ }
246
+
247
+ const CUSTOM_TIERS: readonly StaticTier[] = ["fast", "medium", "heavy"];
248
+ const NO_CUSTOM: readonly CustomPattern[] = [];
249
+ const CUSTOM_CACHE = new WeakMap<object, readonly CustomPattern[]>();
250
+
251
+ function customPatterns(taskPatterns: RulesConfig["taskPatterns"]): readonly CustomPattern[] {
252
+ if (typeof taskPatterns !== "object" || taskPatterns === null) return NO_CUSTOM;
253
+ const cached = CUSTOM_CACHE.get(taskPatterns);
254
+ if (cached) return cached;
255
+ const out: CustomPattern[] = [];
256
+ for (const tier of CUSTOM_TIERS) {
257
+ const list: unknown = taskPatterns[tier];
258
+ if (!Array.isArray(list)) continue;
259
+ for (const kw of list) {
260
+ if (typeof kw !== "string") continue;
261
+ if (BUILTIN_PAIRS.has(`${tier}\u0000${kw}`)) continue;
262
+ const stem = normTaskKw(kw);
263
+ if (stem.length < 3) continue;
264
+ out.push({
265
+ re: new RegExp("\\b" + escapeRegExp(stem) + "\\b", "gi"),
266
+ class: TIER_DEFAULT_CLASS[tier],
267
+ anchor: `custom:${tier}:${kw}`,
268
+ });
269
+ }
270
+ }
271
+ CUSTOM_CACHE.set(taskPatterns, out);
272
+ return out;
273
+ }
274
+
275
+ // ---------------------------------------------------------------------------
276
+ // R4 — shape gates
277
+ // ---------------------------------------------------------------------------
278
+
279
+ /** classifyTrivial's shape clauses 5–7, on the string given (R4). Length is reported, never a class signal. */
280
+ export function shapeOf(input: string): ShapeFacts {
281
+ // The shared gate regexes are quadratic on long runs of path characters; `chars` stays the true length.
282
+ const raw = collapseLongRuns(input);
283
+ const lower = raw.toLowerCase();
284
+ const paths = new Set<string>((lower.match(SHAPE_GATES.pathToken) ?? []).map((p) => p.trim()));
285
+ for (const bare of raw.match(SHAPE_GATES.bareFilename) ?? []) paths.add(bare.toLowerCase());
286
+ const multiStep = SHAPE_GATES.multiStep.test(raw);
287
+ const enumeration = SHAPE_GATES.enumeration.test(raw);
288
+ const distributive = SHAPE_GATES.distributive.test(raw);
289
+ const imperativeLines = raw
290
+ .split(/\r?\n/)
291
+ .filter((line) => SHAPE_GATES.imperativeLine.test(line)).length;
292
+ const breadth =
293
+ multiStep ||
294
+ enumeration ||
295
+ distributive ||
296
+ imperativeLines > 1 ||
297
+ paths.size > SHAPE_GATES.maxSingleShotPaths;
298
+ return {
299
+ chars: input.length,
300
+ paths: paths.size,
301
+ multiStep,
302
+ enumeration,
303
+ distributive,
304
+ imperativeLines,
305
+ breadth,
306
+ singleShot: !breadth && input.length <= SHAPE_GATES.maxSingleShotChars,
307
+ };
308
+ }
309
+
310
+ // ---------------------------------------------------------------------------
311
+ // R1–R3 — text preparation, sections, cwd
312
+ // ---------------------------------------------------------------------------
313
+
314
+ /** R1: drop directive lines, then every `[acceptance]` block. */
315
+ function prepareBody(raw: string): string {
316
+ const kept: string[] = [];
317
+ for (const line of raw.split(/\r?\n/)) {
318
+ if (DIRECTIVE_LINE_RES.some((re) => re.test(line))) continue;
319
+ kept.push(line);
320
+ }
321
+ return kept.join("\n").replace(ACCEPTANCE_ALL_RE, "\n");
322
+ }
323
+
324
+ interface Sections {
325
+ readonly templated: boolean;
326
+ readonly focusText: string;
327
+ readonly needsText: string;
328
+ /** Content of the ENVIRONMENT section(s), where the host states the working directory ("" when none). */
329
+ readonly environmentText: string;
330
+ /** Everything the risk vocabulary scans with negation IGNORED: the whole body minus the prohibition paragraphs. */
331
+ readonly riskText: string;
332
+ /** The first paragraph of the MUST NOT DO / CONSTRAINTS sections, scanned with negation honoured (A22). */
333
+ readonly prohibitionText: string;
334
+ }
335
+
336
+ /**
337
+ * R2: split a dispatch template into sections; text outside templates is used
338
+ * whole. Excluded sections hide only their own paragraph: the text after the
339
+ * first blank line of such a section is included again.
340
+ */
341
+ function splitSections(body: string): Sections {
342
+ const lines = body.split("\n");
343
+ const headers: Array<{ line: number; label: string; prefixLength: number }> = [];
344
+ for (let i = 0; i < lines.length; i++) {
345
+ const m = SECTION_HEADER_RE.exec(lines[i]!);
346
+ if (m === null) continue;
347
+ const label = (m[1] ?? "").trim();
348
+ if (TEMPLATE_LABELS.has(label)) headers.push({ line: i, label, prefixLength: m[0].length });
349
+ }
350
+ if (headers.length < TEMPLATE_MIN_SECTIONS) {
351
+ return { templated: false, focusText: body, needsText: body, environmentText: "", riskText: body, prohibitionText: "" };
352
+ }
353
+ const focus: string[] = [];
354
+ const needs: string[] = [];
355
+ const environment: string[] = [];
356
+ const risk: string[] = [];
357
+ const prohibitions: string[] = [];
358
+ const first = headers[0]!.line;
359
+ if (first > 0) {
360
+ const preamble = lines.slice(0, first).join("\n");
361
+ focus.push(preamble);
362
+ needs.push(preamble);
363
+ risk.push(preamble);
364
+ }
365
+ for (let h = 0; h < headers.length; h++) {
366
+ const header = headers[h]!;
367
+ const end = h + 1 < headers.length ? headers[h + 1]!.line : lines.length;
368
+ const content = [lines[header.line]!.slice(header.prefixLength), ...lines.slice(header.line + 1, end)];
369
+ // An excluded section ends at its first blank line: whatever follows is task text again (QA-1.2-4).
370
+ const blank = content.findIndex((line, i) => i > 0 && line.trim() === "");
371
+ const afterBlank = blank === -1 ? "" : content.slice(blank + 1).join("\n");
372
+ const whole = content.join("\n");
373
+ if (header.label === "ENVIRONMENT") environment.push(whole);
374
+ if (PROHIBITIONS.has(header.label)) {
375
+ // Only the first paragraph is a list of prohibitions; text after a blank line is task text again.
376
+ prohibitions.push(blank === -1 ? whole : content.slice(0, blank).join("\n"));
377
+ risk.push(afterBlank);
378
+ } else {
379
+ risk.push(whole);
380
+ }
381
+ focus.push(CLASS_EXCLUDED.has(header.label) ? afterBlank : whole);
382
+ needs.push(NEEDS_EXCLUDED.has(header.label) ? afterBlank : whole);
383
+ }
384
+ return {
385
+ templated: true,
386
+ focusText: focus.join("\n"),
387
+ needsText: needs.join("\n"),
388
+ environmentText: environment.join("\n"),
389
+ riskText: risk.join("\n"),
390
+ prohibitionText: prohibitions.join("\n"),
391
+ };
392
+ }
393
+
394
+ function trimPathTail(path: string): string {
395
+ return path.replace(/[.,;:)]+$/, "");
396
+ }
397
+
398
+ /** The path of the LAST `Working directory:` line in `text`, or null. */
399
+ function lastWorkingDirectory(text: string): string | null {
400
+ let found: string | null = null;
401
+ scan(CWD_LINE_ALL_RE, text, (m) => {
402
+ const path = m[1] ? trimPathTail(m[1]) : "";
403
+ if (path !== "") found = path;
404
+ return false;
405
+ });
406
+ return found;
407
+ }
408
+
409
+ /**
410
+ * R3: the dispatch working directory. The caller's `cwd` wins (the orchestrator
411
+ * knows the task's worktree); otherwise the `Working directory:` line of the
412
+ * ENVIRONMENT section, where the host writes it; otherwise the LAST such line
413
+ * anywhere (a quoted log or an earlier example must not outvote the footer
414
+ * that closes the prompt; QA-1.2-15).
415
+ */
416
+ function resolveCwd(body: string, environmentText: string, ctx: { cwd?: string } | undefined): string | null {
417
+ const given = ctx?.cwd;
418
+ if (typeof given === "string" && given.trim() !== "") return given.trim();
419
+ return lastWorkingDirectory(environmentText) ?? lastWorkingDirectory(body);
420
+ }
421
+
422
+ // ---------------------------------------------------------------------------
423
+ // R9 helpers — external_dir from absolute paths
424
+ // ---------------------------------------------------------------------------
425
+
426
+ function normalizePath(path: string): string {
427
+ return path.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
428
+ }
429
+
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 {
432
+ const base = normalizePath(cwd);
433
+ for (const re of ABS_PATH_RES) {
434
+ let found: string | null = null;
435
+ if (scan(re, needsText, (m) => {
436
+ if (isNegatedAt(needsText, m.index)) return false;
437
+ const path = normalizePath(trimPathTail(m[0]));
438
+ if (path === base || path.startsWith(base + "/")) return false;
439
+ found = trimPathTail(m[0]);
440
+ return true;
441
+ })) return found;
442
+ }
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;
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // R13 — language gate
505
+ // ---------------------------------------------------------------------------
506
+
507
+ function isNonEnglish(text: string): boolean {
508
+ const letters = text.match(/\p{L}/gu);
509
+ if (letters !== null && letters.length >= NON_ENGLISH_MIN_LETTERS) {
510
+ let nonAscii = 0;
511
+ for (const letter of letters) {
512
+ if ((letter.codePointAt(0) ?? 0) > 0x7f) nonAscii++;
513
+ }
514
+ if (nonAscii / letters.length > NON_ASCII_LETTER_SHARE) return true;
515
+ }
516
+ const words = text.toLowerCase().match(/\p{L}+/gu);
517
+ if (words !== null && words.length >= NON_ENGLISH_MIN_WORDS) {
518
+ let english = 0;
519
+ let other = 0;
520
+ for (const word of words) {
521
+ if (ENGLISH_WORDS.has(word)) english++;
522
+ else if (NON_ENGLISH_WORDS.has(word)) other++;
523
+ }
524
+ return other > english;
525
+ }
526
+ return false;
527
+ }
528
+
529
+ // ---------------------------------------------------------------------------
530
+ // Ordering helpers
531
+ // ---------------------------------------------------------------------------
532
+
533
+ function round2(n: number): number {
534
+ return Math.round(n * 100) / 100;
535
+ }
536
+
537
+ function orderedNeeds(set: ReadonlySet<Need>): Need[] {
538
+ return NEEDS.filter((need) => set.has(need));
539
+ }
540
+
541
+ function maxRisk(a: Risk, b: Risk): Risk {
542
+ return RISKS.indexOf(a) >= RISKS.indexOf(b) ? a : b;
543
+ }
544
+
545
+ // ---------------------------------------------------------------------------
546
+ // analyzeRules / classifyByRules
547
+ // ---------------------------------------------------------------------------
548
+
549
+ /**
550
+ * R6 + R7 on one text: the classes with a non-negated hit (built-in rules and the
551
+ * user's extra taskPatterns), the search/recon family merged by `breadth`, highest
552
+ * cost first. `anchors` (optional) collects the patterns that hit.
553
+ */
554
+ function matchClasses(
555
+ text: string,
556
+ cfg: RulesConfig,
557
+ breadth: boolean,
558
+ anchors?: Set<string>,
559
+ ): TaskClass[] {
560
+ const candidates = new Set<TaskClass>();
561
+ for (const rule of COMPILED_RULES) {
562
+ if (hasHit(rule.res, text, true)) {
563
+ candidates.add(rule.class);
564
+ anchors?.add(rule.pattern);
565
+ }
566
+ }
567
+ for (const custom of customPatterns(cfg?.taskPatterns)) {
568
+ if (hasHit([custom.re], text, true)) {
569
+ candidates.add(custom.class);
570
+ anchors?.add(custom.anchor);
571
+ }
572
+ }
573
+ if (candidates.has("search") || candidates.has("recon")) {
574
+ const recon = candidates.has("recon");
575
+ candidates.delete("search");
576
+ candidates.delete("recon");
577
+ candidates.add(recon || breadth ? "recon" : "search");
578
+ }
579
+ return [...candidates].sort((a, b) => CLASS_COST_RANK[b] - CLASS_COST_RANK[a]);
580
+ }
581
+
582
+ export function analyzeRules(
583
+ text: string,
584
+ cfg: RulesConfig,
585
+ ctx?: { cwd?: string },
586
+ ): RulesAnalysis {
587
+ const raw = collapseLongRuns(String(text ?? "").slice(0, RULES_MAX_CHARS));
588
+ const body = prepareBody(raw);
589
+ const { templated, focusText, needsText, environmentText, riskText, prohibitionText } = splitSections(body);
590
+ const cwd = resolveCwd(body, environmentText, ctx);
591
+ // The gates are quadratic in the longest run of path characters (a token just under the collapse
592
+ // threshold still costs ~its length squared), so only the head of a long prompt is measured; breadth
593
+ // markers show up long before 2000 characters. `chars` then reports the head, never the full length.
594
+ const shape = shapeOf(focusText.length > SHAPE_WINDOW_CHARS ? focusText.slice(0, SHAPE_WINDOW_CHARS) : focusText);
595
+ const nonEnglish = isNonEnglish(focusText);
596
+
597
+ // R6/R7 — class candidates, lookup family resolved by shape
598
+ const anchors = new Set<string>();
599
+ const matched = matchClasses(focusText, cfg, shape.breadth, anchors);
600
+ const taskClass: TaskClass = matched[0] ?? "other";
601
+
602
+ // QA-1.2-30: class words that occur only inside excluded paragraphs (TOOLS, CONTEXT, …) never choose
603
+ // the class, but when they point at a more expensive class the class label is not to be trusted.
604
+ const hiddenClasses: TaskClass[] =
605
+ focusText === body
606
+ ? []
607
+ : matchClasses(body, cfg, shape.breadth).filter(
608
+ (name) => CLASS_COST_RANK[name] > CLASS_COST_RANK[taskClass],
609
+ );
610
+
611
+ // R8 — confidence
612
+ let confidence: number =
613
+ matched.length === 0
614
+ ? CONFIDENCE.rulesNone
615
+ : matched.length === 1
616
+ ? CONFIDENCE.rulesSingle
617
+ : CONFIDENCE.rulesMultiple;
618
+
619
+ // R9 — needs
620
+ const needs = scanNeeds(needsText, cwd);
621
+ for (const implied of CLASS_IMPLIED_NEEDS[taskClass]) needs.add(implied);
622
+
623
+ // R10 — scope
624
+ const scope: Scope = hasHit(REPO_SCOPE_RES, focusText, true)
625
+ ? "repo"
626
+ : shape.breadth
627
+ ? "multi"
628
+ : "single";
629
+
630
+ // R11 — risk (negation ignored for the high-risk vocabulary)
631
+ let risk: Risk = CLASS_BASE_RISK[taskClass];
632
+ // Risk vocabulary is scanned over the WHOLE body, every section included: a section header must
633
+ // not hide "production", "credentials" or "deploy" from the risk estimate (QA-1.2-4).
634
+ // Prohibition paragraphs (MUST NOT DO, CONSTRAINTS) count only where the risky word is not itself prohibited.
635
+ if (hasHit(HIGH_RISK_RES, riskText, false) || hasHit(HIGH_RISK_RES, prohibitionText, true)) risk = "high";
636
+ else if (hasHit(MEDIUM_RISK_RES, riskText, false) || hasHit(MEDIUM_RISK_RES, prohibitionText, true)) {
637
+ risk = maxRisk(risk, "medium");
638
+ }
639
+ if (
640
+ (scope === "repo" && needs.has("edit")) ||
641
+ (needs.has("external_dir") && needs.has("edit")) ||
642
+ needs.has("network")
643
+ ) {
644
+ risk = maxRisk(risk, "medium");
645
+ }
646
+
647
+ // R12 — caps and output
648
+ if (nonEnglish) confidence = Math.min(confidence, CONFIDENCE.nonEnglishCap);
649
+ if (hiddenClasses.length > 0) confidence = Math.min(confidence, CONFIDENCE.hiddenClassCap);
650
+ if (taskClass === "mechanical" && risk === "high") {
651
+ confidence = Math.min(confidence, CONFIDENCE.mechanicalHighRiskCap);
652
+ }
653
+
654
+ const facts: TaskFacts = Object.freeze({
655
+ class: taskClass,
656
+ risk,
657
+ scope,
658
+ needs: Object.freeze(orderedNeeds(needs)),
659
+ confidence: round2(confidence),
660
+ source: "rules" as const,
661
+ });
662
+ return { facts, matched, anchors: [...anchors], shape, nonEnglish, templated, hiddenClasses };
663
+ }
664
+
665
+ export function classifyByRules(text: string, cfg: RulesConfig, ctx?: { cwd?: string }): TaskFacts {
666
+ return analyzeRules(text, cfg, ctx).facts;
667
+ }