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.
Files changed (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -10,6 +10,7 @@
10
10
  // ---------------------------------------------------------------------------
11
11
 
12
12
  import type { Verdict as VerificationVerdict } from "../../verify/types";
13
+ import type { Risk } from "../classify/types";
13
14
 
14
15
  // ---------------------------------------------------------------------------
15
16
  // Primitives
@@ -570,6 +571,21 @@ export interface DecisionTrace {
570
571
  * `<need>:resumed-dispatch`. Before any narrowing: `facts.needs` is what was decided.
571
572
  */
572
573
  readonly needTerms?: readonly string[];
574
+ /**
575
+ * Role dispatches only: risk proposals before the raise-only merge. `base` is the rules class's base risk;
576
+ * `facts` includes any accepted backend raise, and `resumedDispatch` is the inherited risk, when present.
577
+ * Every proposal equal to `effective` is a joint winner (there is no risk tie-break). Older rows omit this field.
578
+ */
579
+ readonly riskSources?: {
580
+ readonly base: Risk;
581
+ readonly rules: Risk | null;
582
+ readonly routeLine: Risk | null;
583
+ readonly facts: Risk;
584
+ readonly resumedDispatch?: Risk;
585
+ readonly effective: Risk;
586
+ /** A bounded vocabulary label, never surrounding prompt text. */
587
+ readonly term?: string;
588
+ };
573
589
  }
574
590
 
575
591
  /**
@@ -579,6 +595,9 @@ export interface DecisionTrace {
579
595
  */
580
596
  export const NEED_TERM_RE = /^[a-z_]+:[a-z0-9=_ -]{1,48}$/;
581
597
 
598
+ /** A single bounded high-risk vocabulary word, or its table id for a match that could contain private text. */
599
+ export const RISK_TERM_RE = /^(?:[a-z-]{1,40}|term-[0-9]{1,3})$/;
600
+
582
601
  /** One routed dispatch (2.2) or one ladder attempt (2.3). Fields of §0.11 plus kind/v/decisionID/step/resume. */
583
602
  export interface DecisionRow extends LogRowBase {
584
603
  readonly kind: "decision";
@@ -703,6 +722,57 @@ export interface RefusalRow extends LogRowBase {
703
722
 
704
723
  export type LogRow = DecisionRow | VerdictRow | RefusalRow;
705
724
 
725
+ // ---------------------------------------------------------------------------
726
+ // Side logs: dispatch timings and orchestrator turns (timings.jsonl, turns.jsonl). Counters and labels only:
727
+ // no prompt, output or tool text is ever stored. They are NOT part of `LogRow` (decisions.jsonl is unchanged).
728
+ // ---------------------------------------------------------------------------
729
+
730
+ /** Schema version of both side-log rows; a reader skips rows with a greater `v`. */
731
+ export const SIDE_ROW_VERSION = 1;
732
+
733
+ export type DispatchTimingOutcome = "succeeded" | "failed" | "interrupted" | "unknown";
734
+ export type DispatchCapacity = "rate-limit" | "overload" | "usage-limit";
735
+
736
+ /** One finished (or abandoned) child dispatch: how long it took and how it ended. */
737
+ export interface DispatchTimingRow {
738
+ readonly kind: "dispatch-timing";
739
+ readonly v: typeof SIDE_ROW_VERSION;
740
+ /** ISO-8601 UTC time the row was written. */
741
+ readonly ts: string;
742
+ readonly parentSessionID: string;
743
+ readonly childSessionID: string;
744
+ readonly callID: string;
745
+ readonly role: string;
746
+ readonly class: string;
747
+ readonly scope: string;
748
+ readonly tier: string;
749
+ readonly model: string;
750
+ readonly background: boolean;
751
+ /** Epoch ms. */
752
+ readonly startedAt: number;
753
+ /** Epoch ms. */
754
+ readonly endedAt: number;
755
+ readonly durationMs: number;
756
+ readonly outcome: DispatchTimingOutcome;
757
+ /** Provider capacity condition that ended the dispatch, if any. */
758
+ readonly capacity: DispatchCapacity | null;
759
+ }
760
+
761
+ /** Token counters of one orchestrator turn (the steps between two prompt events of a root session). */
762
+ export interface OrchestratorTurnRow {
763
+ readonly kind: "orchestrator-turn";
764
+ readonly v: typeof SIDE_ROW_VERSION;
765
+ /** ISO-8601 UTC time the row was written. */
766
+ readonly ts: string;
767
+ readonly sessionID: string;
768
+ /** 1-based (or as numbered by the writer) turn index within the session. */
769
+ readonly turn: number;
770
+ readonly steps: number;
771
+ readonly input: number;
772
+ readonly cacheRead: number;
773
+ readonly cacheWrite: number;
774
+ }
775
+
706
776
  // ---------------------------------------------------------------------------
707
777
  // Persistence (persist.ts) — D15, A3
708
778
  // ---------------------------------------------------------------------------
@@ -725,6 +795,12 @@ export const DECISIONS_ROTATED_RE = /^decisions\.(\d{8}T\d{9}Z)-(\d+)\.jsonl$/;
725
795
  /** D15: rotate before the live log would exceed 5 MiB. */
726
796
  export const DECISIONS_MAX_BYTES = 5 * 1024 * 1024;
727
797
  export const DECISIONS_MAX_GENERATIONS = 3;
798
+ /** Side logs next to `decisions.jsonl`; same append path, size limit and generation count as the decision log. */
799
+ export const TIMINGS_FILE = "timings.jsonl";
800
+ export const TURNS_FILE = "turns.jsonl";
801
+ /** Rotated generations: `timings.<YYYYMMDDTHHMMSSmmmZ>-<pid>.jsonl` / `turns.<...>-<pid>.jsonl`. */
802
+ export const TIMINGS_ROTATED_RE = /^timings\.(\d{8}T\d{9}Z)-(\d+)\.jsonl$/;
803
+ export const TURNS_ROTATED_RE = /^turns\.(\d{8}T\d{9}Z)-(\d+)\.jsonl$/;
728
804
  /** D15: at most one flush per 30 s. */
729
805
  export const FLUSH_MIN_INTERVAL_MS = 30_000;
730
806
  export const FLUSH_BATCH_ROWS = 1_000;
@@ -828,6 +904,28 @@ export interface ReadRowsResult {
828
904
  readonly generations: number;
829
905
  }
830
906
 
907
+ /** Result of reading one side log (`timings.jsonl` or `turns.jsonl`), oldest generation first. */
908
+ export interface ReadSideRowsResult<Row> {
909
+ readonly rows: Row[];
910
+ /** Lines that failed JSON parsing or validation (a torn last line after a crash is expected); one warning per read. */
911
+ readonly skipped: number;
912
+ /** Rows written by a newer schema (`v` above {@link SIDE_ROW_VERSION}); skipped without a warning. */
913
+ readonly newer: number;
914
+ readonly files: string[];
915
+ }
916
+
917
+ /** Append/read access to `timings.jsonl` and `turns.jsonl` of one outcomes directory. Neither ever throws. */
918
+ export interface SideLogs {
919
+ readonly dir: string;
920
+ readonly timingsPath: string;
921
+ readonly turnsPath: string;
922
+ /** One append per call; rotates first when the live file would pass `maxBytes`. */
923
+ appendTimings(rows: readonly DispatchTimingRow[]): Promise<WriteResult>;
924
+ appendTurns(rows: readonly OrchestratorTurnRow[]): Promise<WriteResult>;
925
+ readTimings(): Promise<ReadSideRowsResult<DispatchTimingRow>>;
926
+ readTurns(): Promise<ReadSideRowsResult<OrchestratorTurnRow>>;
927
+ }
928
+
831
929
  /**
832
930
  * Result of checking `outcomes.json` for another writer (QA-1.3-4, QA-1.3-18):
833
931
  * - `unchanged`: nothing to merge (file untouched, removed, not ours, or unparseable and already moved aside);
@@ -15,6 +15,8 @@ import * as path from "node:path";
15
15
  import { configPath, overridePath, statePath } from "../../router/config";
16
16
  import { REPO_APPROVAL_CAP_DAYS } from "../../router/roles-config";
17
17
  import { permissionMatches } from "../../router/read-only";
18
+ import { resolvePendingJournalDir } from "../../verify/pending";
19
+ import { EXECUTOR_HOME_DIRNAME, resolveExecutorHome } from "../../executor/paths";
18
20
  // Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json
19
21
  // lookup fails. The cycle with admission.ts is safe: each side uses the other only inside functions.
20
22
  import * as admission from "./admission";
@@ -470,8 +472,10 @@ function opencodeConfigFileDir(): string | undefined {
470
472
  * The protected locations: the opencode config dir (the router's `dirname(overridePath())`, plus
471
473
  * `$XDG_CONFIG_HOME/opencode`), `OPENCODE_CONFIG_DIR`, the directory of the `OPENCODE_CONFIG` file and
472
474
  * `~/.opencode`, the opencode data, state and cache dirs, this plugin's install dir
473
- * (`dirname(configPath())`) and the store's dir (equal, ancestor or inside), and the user profile
474
- * (equal or ancestor). Filesystem roots are checked separately by {@link protectedProblem}.
475
+ * (`dirname(configPath())`), the store's dir and the router state directory of the pending journal
476
+ * (`resolvePendingJournalDir`) (equal, ancestor or inside), and the user profile (equal or ancestor).
477
+ * Filesystem roots are checked separately by {@link protectedProblem}; the executor home, which is per
478
+ * repository, by {@link inspectCandidate}.
475
479
  */
476
480
  export function protectedLocations(env: ApprovalsEnv = {}): ProtectedLocation[] {
477
481
  const out: ProtectedLocation[] = [];
@@ -490,6 +494,8 @@ export function protectedLocations(env: ApprovalsEnv = {}): ProtectedLocation[]
490
494
  for (const d of opencodeDirs("XDG_CACHE_HOME", ".cache")) add("the opencode cache directory", d);
491
495
  add("the plugin install directory", path.dirname(configPath()));
492
496
  add("the approvals store directory", path.dirname(approvalsPath(env)));
497
+ // The pending journal's directory, resolved as the v2 wiring resolves it: its verdict records are re-posted after a restart.
498
+ add("the router state directory", resolvePendingJournalDir({ homedir: os.homedir(), platform: process.platform, xdgStateHome: process.env.XDG_STATE_HOME }));
493
499
  add("the user profile", os.homedir(), "equal-or-ancestor");
494
500
  return out;
495
501
  }
@@ -578,6 +584,15 @@ export function sanitizeOrigin(raw: string | undefined): string {
578
584
  /** {@link inspectCandidate} results are cached this long per path (SD-P4-8). */
579
585
  export const INSPECT_CACHE_MS = 5_000;
580
586
 
587
+ /**
588
+ * QA-SYNC1-18: the one deadline of the executor-home check of {@link inspectCandidate}, shared by every ancestor it checks (it
589
+ * was the executor's 15 s git bound per ancestor). Past it the candidate is refused.
590
+ */
591
+ export const EXECUTOR_HOME_BOUND_MS = 15_000;
592
+
593
+ /** The value of the executor-home deadline when it wins the race against a resolver. */
594
+ const EXECUTOR_HOME_TIMED_OUT: unique symbol = Symbol("executor home deadline");
595
+
581
596
  /** What git says about a candidate main worktree (SD-P4-4, -8, -9). */
582
597
  export interface CandidateIdentity {
583
598
  /** Canonical path of the main worktree. */
@@ -622,6 +637,13 @@ export interface IdentityDeps {
622
637
  readonly now?: () => number;
623
638
  /** Default `process.platform`. */
624
639
  readonly platform?: NodeJS.Platform;
640
+ /**
641
+ * {@link inspectCandidate} only: the executor home resolved from `dir` (default `resolveExecutorHome`, hardened git);
642
+ * throws when `dir` has none.
643
+ */
644
+ readonly executorHome?: (dir: string) => Promise<string>;
645
+ /** {@link inspectCandidate} only: the one deadline of the executor-home check, all ancestors; default {@link EXECUTOR_HOME_BOUND_MS}. */
646
+ readonly executorHomeBoundMs?: number;
625
647
  }
626
648
 
627
649
  /** Injectable I/O and configuration of {@link inspectCandidate}. */
@@ -714,6 +736,61 @@ function gitDirectoryProblem(real: string, deps: IdentityDeps): string | undefin
714
736
  return undefined;
715
737
  }
716
738
 
739
+ /**
740
+ * QA-SYNC1-5: whether `text` or `canonical` is the executor home of a repository (`<git common dir>\omr-executor`, which holds
741
+ * the executor's plan directories and slot markers) or lies inside one. The home is per repository, so it is not a fixed
742
+ * {@link protectedLocations} entry: every ancestor named {@link EXECUTOR_HOME_DIRNAME} is checked against the home that
743
+ * `resolveExecutorHome` gives for its parent, exactly as the executor resolves it. Git runs only for such an ancestor.
744
+ * QA-SYNC1-18: all of these ancestors share one deadline ({@link EXECUTOR_HOME_BOUND_MS}, from the first git call; the
745
+ * default resolver gets what is left of it as its own git bound). Past the deadline the candidate is refused: an ancestor
746
+ * that could not be checked is never taken as "not the executor home".
747
+ */
748
+ async function executorHomeProblem(text: string, canonical: string, deps: IdentityDeps): Promise<string | undefined> {
749
+ const bound = Math.max(1, deps.executorHomeBoundMs ?? EXECUTOR_HOME_BOUND_MS);
750
+ let deadlineAt = 0;
751
+ let expired: Promise<typeof EXECUTOR_HOME_TIMED_OUT> | undefined;
752
+ let timer: ReturnType<typeof setTimeout> | undefined;
753
+ const resolveHome = deps.executorHome
754
+ ?? ((dir: string) => resolveExecutorHome(dir, { timeoutMs: Math.max(1, deadlineAt - Date.now()) }));
755
+ const timedOut = `could not be checked against the executor home within ${String(bound)} ms (git did not answer in time)`;
756
+ const name = pathKey(EXECUTOR_HOME_DIRNAME);
757
+ const checked = new Set<string>();
758
+ try {
759
+ for (const candidate of [text, canonical]) {
760
+ if (candidate === "" || !path.isAbsolute(candidate)) continue;
761
+ const self = cmpForm(candidate);
762
+ for (let dir = path.resolve(candidate); ; dir = path.dirname(dir)) {
763
+ const form = cmpForm(dir);
764
+ if (pathKey(path.basename(dir)) === name && !checked.has(form)) {
765
+ checked.add(form);
766
+ if (expired === undefined) {
767
+ // The one deadline, started at the first git call and raced by every ancestor after it.
768
+ deadlineAt = Date.now() + bound;
769
+ expired = new Promise<typeof EXECUTOR_HOME_TIMED_OUT>((resolve) => {
770
+ timer = setTimeout(() => resolve(EXECUTOR_HOME_TIMED_OUT), bound);
771
+ });
772
+ }
773
+ let home: string | typeof EXECUTOR_HOME_TIMED_OUT | undefined;
774
+ try {
775
+ home = await Promise.race([resolveHome(path.dirname(dir)), expired]);
776
+ } catch {
777
+ // A resolver that failed at the deadline (the default one's git bound is what is left of it) did not answer.
778
+ home = Date.now() >= deadlineAt ? EXECUTOR_HOME_TIMED_OUT : undefined;
779
+ }
780
+ if (home === EXECUTOR_HOME_TIMED_OUT) return timedOut;
781
+ if (home !== undefined && [cmpForm(home), cmpForm(realOrSelf(home))].some((h) => h === form || h === cmpForm(realOrSelf(dir)))) {
782
+ return form === self ? `is the executor home (${home})` : `is inside the executor home (${home})`;
783
+ }
784
+ }
785
+ if (path.dirname(dir) === dir) break;
786
+ }
787
+ }
788
+ return undefined;
789
+ } finally {
790
+ if (timer !== undefined) clearTimeout(timer);
791
+ }
792
+ }
793
+
717
794
  /** `routing.repoExclude` pattern matching `p` (as given and, on win32, with native separators), or undefined. */
718
795
  function excludedBy(p: string, exclude: readonly string[], win: boolean, matches: (input: string, pattern: string) => boolean): string | undefined {
719
796
  const forms = win && p.includes("/") ? [p, p.replace(/\//g, "\\")] : [p];
@@ -763,9 +840,11 @@ async function inspectGit(real: string, deps: IdentityDeps, adm: AdmissionModule
763
840
 
764
841
  /**
765
842
  * What git says about the candidate `text` (SD-P4-4, -8, -9): a problem phrase (to follow the path, as in "D:\x <problem>"), or
766
- * the identity of its canonical main worktree. Before any git call: {@link rootTextProblem} (admission.ts) on the text and on
767
- * the canonical form, `routing.repoExclude` on both, {@link protectedProblem}, and `<canonical>\.git` must be a local directory
768
- * (`lstat`: not a link, not a gitfile). Then hardened, bounded git: the canonical form must be the top level, its canonical common
843
+ * the identity of its canonical main worktree. In this order: {@link rootTextProblem} (admission.ts) on the text and on the
844
+ * canonical form, `routing.repoExclude` on both and {@link protectedProblem}, all without git; then the executor home
845
+ * (`executorHomeProblem`), which runs git only for an ancestor named like the executor home, every such ancestor within one
846
+ * shared {@link EXECUTOR_HOME_BOUND_MS} deadline; then, without git, `<canonical>\.git` must be a local directory (`lstat`: not
847
+ * a link, not a gitfile). Then hardened, bounded git: the canonical form must be the top level, its canonical common
769
848
  * dir must be `<canonical>\.git`, and it must have at least one commit. The git part is cached {@link INSPECT_CACHE_MS} per
770
849
  * canonical path (`deps.fresh` skips the cached result); the checks before it run every time. Never throws.
771
850
  */
@@ -793,6 +872,8 @@ export async function inspectCandidate(text: string, deps: InspectDeps = {}): Pr
793
872
  if (byReal !== undefined) return `resolves to ${displaySafe(real)}, which is excluded by routing.repoExclude (${byReal})`;
794
873
  const placed = protectedProblem(shown, real, deps.env);
795
874
  if (placed !== undefined) return placed;
875
+ const executorHome = await executorHomeProblem(shown, real, deps);
876
+ if (executorHome !== undefined) return executorHome;
796
877
  const gitDir = gitDirectoryProblem(real, deps);
797
878
  if (gitDir !== undefined) return gitDir;
798
879
 
@@ -37,6 +37,8 @@ import { randomUUID } from "node:crypto";
37
37
  import { isAbsolute } from "node:path";
38
38
  import type { AuthorityAction } from "../../router/roles";
39
39
  import { GRANT_NOTES, type DispatchGrant } from "./policy";
40
+ import { leaseTaskRef } from "../../executor/types";
41
+ import { forgetExecutorChildRound } from "../../executor/child-guards";
40
42
 
41
43
  export interface PendingDispatch {
42
44
  parentSessionID: string;
@@ -56,10 +58,30 @@ export type SessionLookup = (
56
58
  id: string,
57
59
  ) => Promise<{ parentID?: string; agent?: string; title?: string; firstText?: string } | undefined>;
58
60
 
61
+ /** The plan task a plan child works on (A3 handoff, 3.1.5): the 2.1 guard joins plan-child leases with this identity. */
62
+ export interface PlanChildIdentity {
63
+ planId: string;
64
+ taskId: string;
65
+ attempt: number;
66
+ /** `leaseTaskRef(planId, taskId)`: the owner of the child's leases. */
67
+ taskRef: string;
68
+ scope: "until-integrated";
69
+ }
70
+
71
+ export type UnknownBindingCause = "unregistered" | "retired" | "foreign" | "claimed" | "markers" | "noNonce" | "noParent" | "lookupFailed";
72
+
59
73
  export interface Binding {
74
+ /** Resolved executor route tier; its budget and cumulative ceiling must not fall back to the role floor. */
75
+ tier?: string;
76
+ /** Set only for a plan child ({@link bindPlanChild}). */
77
+ role?: string;
78
+ /** Set only for a plan child ({@link bindPlanChild}). */
79
+ plan?: PlanChildIdentity;
60
80
  childSessionID: string;
61
81
  /** `intersection` is part of the contract but never produced under R7 (ambiguity → unknown). */
62
82
  kind: "exact" | "intersection" | "unknown";
83
+ /** Set only for an unknown binding: why the session could not be matched to its dispatch. */
84
+ cause?: UnknownBindingCause;
63
85
  grant: DispatchGrant;
64
86
  /** callIDs of the pending dispatches that matched. */
65
87
  candidates: readonly string[];
@@ -312,11 +334,12 @@ function exact(childSessionID: string, entry: PendingDispatch): Binding {
312
334
  }
313
335
 
314
336
  /** Unknown: the local class, narrowed by every view to max ∩ local (I9) — never derived from a dispatch grant. */
315
- function unknown(childSessionID: string, cause: string): Binding {
337
+ function unknown(childSessionID: string, cause: UnknownBindingCause, note: string): Binding {
316
338
  return {
317
339
  childSessionID,
318
340
  kind: "unknown",
319
- grant: { actions: ordered(LOCAL_ACTIONS), notes: [BINDING_NOTES.unknown, cause], workRoot: null },
341
+ cause,
342
+ grant: { actions: ordered(LOCAL_ACTIONS), notes: [BINDING_NOTES.unknown, note], workRoot: null },
320
343
  candidates: [],
321
344
  decisionID: null,
322
345
  budget: null,
@@ -350,31 +373,34 @@ async function decide(childSessionID: string, getSession: SessionLookup): Promis
350
373
  session = undefined;
351
374
  }
352
375
  if (typeof session !== "object" || session === null) {
353
- return { binding: unknown(childSessionID, BINDING_NOTES.lookupFailed), parentSessionID: undefined, agent: undefined, cacheable: false };
376
+ return { binding: unknown(childSessionID, "lookupFailed", BINDING_NOTES.lookupFailed), parentSessionID: undefined, agent: undefined, cacheable: false };
354
377
  }
355
378
  const parent = text(session.parentID);
356
379
  const agent = text(session.agent);
357
380
  if (parent === undefined || agent === undefined) {
358
- return { binding: unknown(childSessionID, BINDING_NOTES.noParent), parentSessionID: parent, agent, cacheable: false };
381
+ return { binding: unknown(childSessionID, "noParent", BINDING_NOTES.noParent), parentSessionID: parent, agent, cacheable: false };
359
382
  }
360
383
  const out = (binding: Binding): Decision => ({ binding, parentSessionID: parent, agent, cacheable: true });
361
384
  const fromTitle = titleNonce(session.title);
362
385
  const fromPrompt = promptNonce(session.firstText);
363
386
  if (fromTitle !== undefined && fromPrompt !== undefined && fromTitle !== fromPrompt) {
364
- return out(unknown(childSessionID, BINDING_NOTES.markers));
387
+ return out(unknown(childSessionID, "markers", BINDING_NOTES.markers));
365
388
  }
366
389
  const nonce = fromPrompt ?? fromTitle;
367
- if (nonce === undefined) return out(unknown(childSessionID, BINDING_NOTES.noNonce));
390
+ if (nonce === undefined) return out(unknown(childSessionID, "noNonce", BINDING_NOTES.noNonce));
368
391
  const reg = registry();
369
392
  prune(reg, Date.now());
370
393
  // Live nonces are unique and never retired (registerPending refuses both), so a retired, unregistered or
371
394
  // forged nonce finds no slot.
372
395
  const slot = [...reg.pending.values()].find((s) => s.entry.nonce === nonce);
373
- if (slot === undefined || slot.entry.parentSessionID !== parent || slot.entry.agent !== agent) {
374
- return out(unknown(childSessionID, BINDING_NOTES.foreignNonce));
396
+ if (slot === undefined) {
397
+ return out(unknown(childSessionID, reg.retired.has(nonce) ? "retired" : "unregistered", BINDING_NOTES.foreignNonce));
398
+ }
399
+ if (slot.entry.parentSessionID !== parent || slot.entry.agent !== agent) {
400
+ return out(unknown(childSessionID, "foreign", BINDING_NOTES.foreignNonce));
375
401
  }
376
402
  if (slot.claimedBy !== undefined && slot.claimedBy !== childSessionID) {
377
- return out(unknown(childSessionID, BINDING_NOTES.claimed));
403
+ return out(unknown(childSessionID, "claimed", BINDING_NOTES.claimed));
378
404
  }
379
405
  slot.claimedBy = childSessionID;
380
406
  return out(exact(childSessionID, slot.entry));
@@ -463,6 +489,68 @@ export async function bind(childSessionID: string, getSession: SessionLookup, op
463
489
  }
464
490
  }
465
491
 
492
+ export interface PlanChildBindInput {
493
+ childSessionID: string;
494
+ tier?: string;
495
+ role: string;
496
+ agent: string;
497
+ workRoot: string;
498
+ grant: readonly string[];
499
+ planId: string;
500
+ taskId: string;
501
+ attempt: number;
502
+ /**
503
+ * QA-PDF21-2-20: the call budget of the plan child's route (its `budget=`), as a routed dispatch's binding carries; absent or
504
+ * null: the role's default budget.
505
+ */
506
+ budget?: number | null;
507
+ }
508
+
509
+ /**
510
+ * Binds a plan child (3.1.5): the executor knows the child's role, grant and work root, so it writes the record
511
+ * the lazy lookup would produce (an exact binding) and adds the plan identity. There is no pending dispatch to pair
512
+ * with. Fails closed: a child that already has a binding with another role or work root throws, and so does a
513
+ * deleted session. Binding the same child again with the same role and root replaces the plan identity.
514
+ */
515
+ export function bindPlanChild(input: PlanChildBindInput): void {
516
+ const reg = registry();
517
+ const now = Date.now();
518
+ const id = input.childSessionID;
519
+ if (text(id) === undefined || text(input.role) === undefined || text(input.agent) === undefined) {
520
+ throw new Error("[model-router] bindPlanChild needs a child session, a role and an agent");
521
+ }
522
+ const root = rootOrNull(input.workRoot);
523
+ if (root === null) throw new Error(`[model-router] bindPlanChild needs an absolute work root for ${id}`);
524
+ if (isDeleted(reg, id, now)) throw new Error(`[model-router] bindPlanChild: session ${id} was deleted`);
525
+ const existing = reg.bound.get(id);
526
+ if (existing !== undefined) {
527
+ const same = existing.binding.role === input.role && existing.binding.grant.workRoot === root;
528
+ if (!same) throw new Error(`[model-router] bindPlanChild: session ${id} is already bound with another role or work root`);
529
+ }
530
+ const known = new Set<string>(ACTION_ORDER);
531
+ const actions = ordered(input.grant.filter((a): a is AuthorityAction => known.has(a)));
532
+ const tier = input.tier ?? existing?.binding.tier;
533
+ const binding: Binding = {
534
+ role: input.role,
535
+ ...(tier === undefined ? {} : { tier }),
536
+ plan: {
537
+ planId: input.planId, taskId: input.taskId, attempt: input.attempt,
538
+ taskRef: leaseTaskRef(input.planId, input.taskId), scope: "until-integrated",
539
+ },
540
+ childSessionID: id,
541
+ kind: "exact",
542
+ grant: { actions, notes: [], workRoot: root },
543
+ candidates: [],
544
+ decisionID: null,
545
+ // QA-PDF21-2-20: the route's `budget=`; a re-bind of the same child that names none keeps the budget it was bound with.
546
+ budget: input.budget === undefined
547
+ ? existing?.binding.budget ?? null
548
+ : typeof input.budget === "number" && Number.isInteger(input.budget) && input.budget > 0 ? input.budget : null,
549
+ };
550
+ reg.inflight.delete(id);
551
+ remember(reg.bound, id, { binding, parentSessionID: undefined, agent: input.agent }, BOUND_MAX);
552
+ }
553
+
466
554
  /** The cached binding of a child ∩ the caller's max, or undefined when it is not bound. No lookup. */
467
555
  export function currentBinding(childSessionID: string, opts: BindOptions): Binding | undefined {
468
556
  const slot = registry().bound.get(childSessionID);
@@ -525,6 +613,7 @@ export function evictCall(parentSessionID: string, callID: string): void {
525
613
  * so neither a running lookup nor a later registration can attach anything to it.
526
614
  */
527
615
  export function evict(sessionID: string): void {
616
+ forgetExecutorChildRound(sessionID);
528
617
  const reg = registry();
529
618
  const now = Date.now();
530
619
  remember(reg.deleted, sessionID, now, DELETED_MAX);
@@ -548,6 +637,7 @@ export function dropBindingCacheForTests(childSessionID: string): void {
548
637
  /** Test only: empties the process-wide registry. */
549
638
  export function resetBindingRegistryForTests(): void {
550
639
  const reg = registry();
640
+ for (const child of reg.bound.keys()) forgetExecutorChildRound(child);
551
641
  reg.pending.clear();
552
642
  reg.bound.clear();
553
643
  reg.inflight.clear();
@@ -0,0 +1,68 @@
1
+ /** Process-wide, bounded observations of stale role children. No host sessions are changed. */
2
+ export type RoleOrphanAction = "refused" | "lost";
3
+
4
+ export interface RoleOrphanRecord {
5
+ readonly child: string;
6
+ /** Most recent occurrence of each action (epoch ms). */
7
+ readonly refused?: number;
8
+ readonly lost?: number;
9
+ }
10
+
11
+ interface Registry {
12
+ readonly version: 1;
13
+ readonly children: Map<string, RoleOrphanRecord>;
14
+ readonly counters: { refused: number; lost: number };
15
+ noticed: boolean;
16
+ /** Separate from the first-refusal notice; optional for existing copies of the @1 registry. */
17
+ bindingLookupNoticed?: boolean;
18
+ }
19
+
20
+ export const ROLE_ORPHANS_MAX = 512;
21
+ const REGISTRY_KEY = Symbol.for("opencode-model-router.role-orphans@1");
22
+
23
+ function isRegistry(value: unknown): value is Registry {
24
+ if (typeof value !== "object" || value === null) return false;
25
+ const r = value as Partial<Registry>;
26
+ return r.version === 1 && r.children instanceof Map && typeof r.noticed === "boolean"
27
+ && typeof r.counters?.refused === "number" && typeof r.counters?.lost === "number";
28
+ }
29
+
30
+ function registry(): Registry {
31
+ const existing: unknown = Reflect.get(globalThis, REGISTRY_KEY);
32
+ if (isRegistry(existing)) return existing;
33
+ const created: Registry = { version: 1, children: new Map(), counters: { refused: 0, lost: 0 }, noticed: false };
34
+ Reflect.set(globalThis, REGISTRY_KEY, created);
35
+ return created;
36
+ }
37
+
38
+ /** Records an action; true only for the first refusal in this process (the adapter logs that one at warn). */
39
+ export function recordRoleOrphan(child: string, action: RoleOrphanAction, at = Date.now()): boolean {
40
+ const reg = registry();
41
+ const previous = reg.children.get(child);
42
+ reg.children.delete(child);
43
+ reg.children.set(child, { ...previous, child, [action]: at });
44
+ while (reg.children.size > ROLE_ORPHANS_MAX) reg.children.delete(reg.children.keys().next().value!);
45
+ reg.counters[action]++;
46
+ const notice = action === "refused" && !reg.noticed;
47
+ if (notice) reg.noticed = true;
48
+ return notice;
49
+ }
50
+
51
+ /** True once per process for binding-lookup warnings; later lookup failures are debug-only. */
52
+ export function takeRoleBindingLookupNotice(): boolean {
53
+ const reg = registry();
54
+ if (reg.bindingLookupNoticed === true) return false;
55
+ reg.bindingLookupNoticed = true;
56
+ return true;
57
+ }
58
+
59
+ /** Detached snapshot for observability; counters include actions whose child record has aged out. */
60
+ export function readRoleOrphans(): { records: readonly RoleOrphanRecord[]; counters: Readonly<{ refused: number; lost: number }>; noticed: boolean } {
61
+ const reg = registry();
62
+ return { records: [...reg.children.values()].map((record) => ({ ...record })), counters: { ...reg.counters }, noticed: reg.noticed };
63
+ }
64
+
65
+ /** Test only: clears the shared observations and notice flag. */
66
+ export function resetRoleOrphansForTests(): void {
67
+ Reflect.deleteProperty(globalThis, REGISTRY_KEY);
68
+ }
@@ -221,9 +221,16 @@ function maxBuiltin(a: string, b: string): string {
221
221
  * - write without exec: deterministic → fast if risk low and scope single, else medium;
222
222
  * grader → medium; none → medium, heavy if risk high
223
223
  * - write + exec: deterministic → medium; grader / none → heavy
224
+ * Opt-in gated policy: grader → medium only below high risk with a gate at return.
224
225
  * An unknown detection is treated as `none` (the strictest column).
225
226
  */
226
- export function authorityFloor(grant: DispatchGrant, detection: Detection, risk: Risk, scope: Scope): string {
227
+ export function authorityFloor(
228
+ grant: DispatchGrant,
229
+ detection: Detection,
230
+ risk: Risk,
231
+ scope: Scope,
232
+ policy: { mode: "strict" | "gated"; gateAtReturn: boolean } = { mode: "strict", gateAtReturn: false },
233
+ ): string {
227
234
  const write = hasAny(grant.actions, WRITE);
228
235
  const exec = hasAny(grant.actions, EXEC);
229
236
  let floor = "fast";
@@ -233,7 +240,8 @@ export function authorityFloor(grant: DispatchGrant, detection: Detection, risk:
233
240
  else floor = risk === "high" ? "heavy" : "medium";
234
241
  }
235
242
  if (write && exec) {
236
- floor = maxBuiltin(floor, detection === "deterministic" ? "medium" : "heavy");
243
+ const gated = policy.mode === "gated" && detection === "grader" && risk !== "high" && policy.gateAtReturn;
244
+ floor = maxBuiltin(floor, detection === "deterministic" || gated ? "medium" : "heavy");
237
245
  }
238
246
  return floor;
239
247
  }
@@ -243,6 +251,8 @@ export function authorityFloor(grant: DispatchGrant, detection: Detection, risk:
243
251
  // ---------------------------------------------------------------------------
244
252
 
245
253
  export interface TierBoundsOptions {
254
+ /** Opt-in authority floor policy; absent keeps the strict floor and reasons unchanged. */
255
+ floorPolicy?: { mode: "strict" | "gated"; gateAtReturn: boolean };
246
256
  /** `enforcement.escalate.floorTier`, or null. */
247
257
  floorTier: string | null;
248
258
  /** The child's running tier on a resume (never move below it), or null. */
@@ -351,6 +361,7 @@ export function effectiveFactsOf(classified: ClassifiedDispatch): TaskFacts {
351
361
  * unknown ceiling or pin name is ignored.
352
362
  *
353
363
  * Reasons (deduplicated, in order of application):
364
+ * `gated:authority` the opt-in authority policy lowered the final floor compared with strict;
354
365
  * `floor:<source>` a source raised the floor (source = authority | floorTier | running);
355
366
  * `round:<source>:<from>-><to>` a built-in name missing from the order was rounded (source adds role | ceiling);
356
367
  * `unknown:<source>:<name>-><top>` an unknown floor name was placed at the top of the order (fail closed);
@@ -371,9 +382,11 @@ export function tierBounds(
371
382
  const reasons: string[] = [];
372
383
 
373
384
  const { risk, scope } = effectiveFactsOf(classified);
385
+ const authority = authorityFloor(grant, detection, risk, scope, opts.floorPolicy);
386
+ const strictAuthority = authorityFloor(grant, detection, risk, scope);
374
387
  const sources: Array<[FloorSource, string | null]> = [
375
388
  ["role", role.tierRange.floor],
376
- ["authority", authorityFloor(grant, detection, risk, scope)],
389
+ ["authority", authority],
377
390
  ["floorTier", opts.floorTier],
378
391
  ["running", opts.runningTier],
379
392
  ];
@@ -393,6 +406,11 @@ export function tierBounds(
393
406
  owner = source;
394
407
  }
395
408
  }
409
+ if (authority !== strictAuthority) {
410
+ const strictFloor = Math.max(0, ...sources.map(([source, tier]) =>
411
+ tier === null ? 0 : placeFloor(source === "authority" ? strictAuthority : tier, order).index));
412
+ if (floor < strictFloor) reasons.unshift("gated:authority");
413
+ }
396
414
  const lift = owner === "authority" ? "lift:authority" : "lift:floor";
397
415
 
398
416
  let ceiling = order.length - 1;
@@ -7,6 +7,7 @@
7
7
  import { lstatSync, realpathSync } from "node:fs";
8
8
  import { join, posix, win32 } from "node:path";
9
9
  import { permissionMatches } from "../../router/read-only";
10
+ import { isPathSeparator, trimEndWhile } from "../../util/linear-trim";
10
11
 
11
12
  /** A win32 8.3 short-name segment (`PROGRA~1`, `MARQUI~1.TXT`): refused, never expanded (S11, P-11: fail closed). */
12
13
  export const SHORT_NAME_SEGMENT = /(?:^|[\\/])[^\\/~]{1,8}~\d+(?:\.[^\\/.]{0,3})?(?=[\\/]|$)/;
@@ -41,7 +42,8 @@ export function canonicalAuthorityPath(
41
42
  }
42
43
  if (!api.isAbsolute(text) && !api.isAbsolute(base)) return undefined;
43
44
  const sep = platform === "win32" ? "\\" : "/";
44
- let head = api.isAbsolute(text) ? text : `${base.replace(/[\\/]+$/, "")}${sep}${text}`;
45
+ let head = text;
46
+ if (!api.isAbsolute(text)) head = `${trimEndWhile(base, isPathSeparator)}${sep}${text}`;
45
47
  const tail: string[] = [];
46
48
  const missing = (error: unknown): boolean => {
47
49
  const code = (error as { code?: unknown } | null)?.code;