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.
- package/CHANGELOG.md +214 -0
- package/README.md +90 -12
- package/package.json +4 -1
- package/src/commands/output.ts +24 -1
- package/src/compat/child-session.ts +43 -0
- package/src/compat/v2-client.ts +107 -7
- package/src/compat/v2-hooks.ts +1435 -44
- package/src/escalate/attempt-recorder.ts +263 -0
- package/src/escalate/ladder.ts +496 -10
- package/src/escalate/resume.ts +208 -0
- package/src/escalate/variants.ts +391 -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 +1193 -56
- package/src/router/build-info.ts +151 -0
- package/src/router/config.ts +1611 -19
- 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 +180 -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 +533 -9
- package/src/router/subagents.ts +28 -1
- package/src/routing/advisor/findings.ts +898 -0
- package/src/routing/advisor/index.ts +614 -0
- package/src/routing/classify/backends/host.ts +163 -0
- package/src/routing/classify/backends/openai-compatible.ts +275 -0
- package/src/routing/classify/backends/shared.ts +741 -0
- package/src/routing/classify/backends/typesafe.ts +315 -0
- package/src/routing/classify/fences.ts +96 -0
- package/src/routing/classify/index.ts +594 -0
- package/src/routing/classify/route-line.ts +362 -0
- package/src/routing/classify/rules.ts +667 -0
- package/src/routing/classify/scrub.ts +214 -0
- package/src/routing/classify/state.ts +148 -0
- package/src/routing/classify/text.ts +20 -0
- package/src/routing/classify/types.ts +1310 -0
- package/src/routing/commands/annotate-plan.ts +652 -0
- package/src/routing/commands/stats.ts +134 -0
- package/src/routing/commands/v1-roles.ts +64 -0
- package/src/routing/engine/index.ts +32 -0
- package/src/routing/engine/kernel.ts +760 -0
- package/src/routing/engine/ladders.ts +802 -0
- package/src/routing/engine/plan.ts +404 -0
- package/src/routing/engine/protocol-line.ts +150 -0
- package/src/routing/engine/roles-taxonomy.ts +52 -0
- package/src/routing/engine/simulate.ts +167 -0
- package/src/routing/engine/types.ts +368 -0
- package/src/routing/file-lock.ts +53 -0
- package/src/routing/outcomes/beta.ts +147 -0
- package/src/routing/outcomes/cost.ts +313 -0
- package/src/routing/outcomes/index.ts +215 -0
- package/src/routing/outcomes/ingest.ts +960 -0
- package/src/routing/outcomes/persist.ts +1080 -0
- package/src/routing/outcomes/signals.ts +650 -0
- package/src/routing/outcomes/stats.ts +873 -0
- package/src/routing/outcomes/store.ts +673 -0
- package/src/routing/outcomes/types.ts +1093 -0
- 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 +2088 -0
- package/src/routing/wire/hint.ts +222 -0
- package/src/routing/wire/host-info.ts +256 -0
- package/src/routing/wire/runtime.ts +348 -0
- package/src/v2.ts +40 -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
|
@@ -0,0 +1,2088 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Dispatch-time routing on v2 (M7, Phase 2.2.1): `route()` composes M2 (classify) → ladders → M4 (decide) for one
|
|
3
|
+
* `subagent` call and applies the engine mode; `commit()` writes the decision row (QA-G-A2) and registers the dispatch with the 2.1
|
|
4
|
+
* dispatch-facts registry once the FINAL input is known, so ingestion sees what really ran.
|
|
5
|
+
*
|
|
6
|
+
* Design (the order the adapter calls it in, `src/compat/v2-hooks.ts` `execute.before` / `execute.after`):
|
|
7
|
+
*
|
|
8
|
+
* 1. Engine first. `route()` runs before the `subagentTiers` override and before the legacy `tool.execute.before`.
|
|
9
|
+
* `subagentTiers` only fills a MISSING `model`: the engine sees the model it would fill (`callModel`) when it
|
|
10
|
+
* resolves the orchestrator's pick, and when it switches it always writes a model of its own, so the override
|
|
11
|
+
* never fires after a switch. The legacy hook runs last, so headers and the depth banner see the final agent.
|
|
12
|
+
* 2. Modes (§1.2): `static` returns before any host call, allocation or disk access. `shadow` classifies, decides and
|
|
13
|
+
* logs (a `switched` row is a would-switch); the input is untouched except that the first-line `[route …]` is
|
|
14
|
+
* stripped. `advise` is `shadow` plus the protocol/hint of the context hook. `enforce` additionally writes `agent`
|
|
15
|
+
* and `model#variant` when the kernel switches (D9, A16, A24, A27) and the dispatch is not pinned.
|
|
16
|
+
* 3. Only the orchestrator's own prompt is parsed: the session must be a root session, and the route line only counts
|
|
17
|
+
* on the first non-empty line of the prompt (A22); every other byte of the prompt passes through unchanged. A
|
|
18
|
+
* subagent's dispatch is left exactly as it is.
|
|
19
|
+
* 4. Errors never reach the session: any failure is logged and the dispatch proceeds as the orchestrator wrote it.
|
|
20
|
+
* 5. Registration (2.1 handoff, QA-2.1-R2-10; QA-2.2-2/3): once per execution of a child, from the FINAL input.
|
|
21
|
+
* `route()` only decides; its decision row is held until `commit()` (QA-G-A2: a call the hook chain rejects writes no row; a
|
|
22
|
+
* call the HOST then fails keeps its row, a known limit — no retraction row). After the legacy hook has had its say, the adapter calls `commit(callID, input)`
|
|
23
|
+
* with the input the host will execute: a resume (`sessionID` given) is registered at once; a fresh child does not
|
|
24
|
+
* exist yet, so the dispatch waits and is claimed by the `session.created` event of the child (parent, agent and
|
|
25
|
+
* title decide which one). `execute.after` then names the child (`onCallResult`): a dispatch still waiting is
|
|
26
|
+
* registered under it, and a heuristic claim that picked the wrong child is corrected before the verdict is
|
|
27
|
+
* recorded. A call that ends without a result, or whose hook chain throws, is dropped (`onCallFinished`).
|
|
28
|
+
* 6. Single writer with the delegate runner (QA-2.2-1, QA-2.3-1): the runner (2.3) dispatches its producer and grader children
|
|
29
|
+
* through the same native tool. It announces each call (`markRunnerDispatch`, keyed by the calling session, the agent and a hash of
|
|
30
|
+
* the prompt) and `route()` consumes the mark first: the call is left exactly as the runner wrote it (no rewrite, no route-line
|
|
31
|
+
* strip, no floor lift, no decision row, no registration). The runner's own recorder is the only writer for ladder attempts. A
|
|
32
|
+
* `session.created` that is the runner's child is never claimed for an orchestrator dispatch (already registered, or titled like a
|
|
33
|
+
* runner call). MEASURED on the real OpenCode 2.0.22 host (Phase 3.2, H4): the host does NOT run the plugin's `execute.before` /
|
|
34
|
+
* `execute.after` hooks for calls made through `ctx.tool.list()` natives, so on 2.0.22 `route()` never sees a runner call and the mark
|
|
35
|
+
* is withdrawn unconsumed (`v2-client.ts`). The mark and the "runner description" rule are defensive: they only matter on a host
|
|
36
|
+
* that does hook such calls.
|
|
37
|
+
* 7. Multi-instance (A3): MEASURED on 2.0.22 (Phase 3.2, H2): the host hands a SESSION EVENT to the plugin instance of every live
|
|
38
|
+
* location, but the TOOL HOOKS of a call only to the instance of the session's location. The receiving instance acts; the
|
|
39
|
+
* process-wide set of handled calls is defensive for hooks. What protects
|
|
40
|
+
* the store from a duplicated EVENT is the event-id LRU of the ingest (`firstDelivery`) and of the registry. Only the first instance
|
|
41
|
+
* whose engine is live acts on a call.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
import {
|
|
45
|
+
buildLadder, candidateKey, capabilityRank, coversNeeds, decide, detectionOf, escalateLadder, floorRankOf, lowerEffortOnSameModel, resolveChosen,
|
|
46
|
+
tierRankOf, weakerDetection,
|
|
47
|
+
} from "../engine";
|
|
48
|
+
import { buildRoleLadder, roleTierOrder, routerTierIds } from "../engine/ladders";
|
|
49
|
+
import { decideRole } from "../engine/kernel";
|
|
50
|
+
import type { Candidate, ChosenDispatch, Decision, HostAgentInfo, Ladder, RoleLadder } from "../engine/types";
|
|
51
|
+
import { CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches } from "../classify";
|
|
52
|
+
import type { ClassifyResult, Detection, Need, RouteLine, TaskFacts } from "../classify/types";
|
|
53
|
+
import { resolveVerifyBudget, type RouterConfig } from "../../router/config";
|
|
54
|
+
import { resolveEnforcementMode } from "../../router/enforcement";
|
|
55
|
+
import { roleGuardProfile } from "../../router/guard-profile";
|
|
56
|
+
import { resolveRoles, type AuthorityAction, type RoleSpec } from "../../router/roles";
|
|
57
|
+
import { parseVerifyDirectives } from "../../verify/directives";
|
|
58
|
+
import { buildDelegationDoD } from "../../verify/dispatch";
|
|
59
|
+
import { requestedVerificationCwd, verificationScope } from "../roles/work-root";
|
|
60
|
+
import { effectiveDetection, effectiveFactsOf, grantFor, tierBounds, type DispatchGrant, type EffectiveDetection } from "../roles/policy";
|
|
61
|
+
import {
|
|
62
|
+
BINDING_NOTES, LOCAL_ACTIONS, currentBinding, evictCall, newDispatchNonce, noncePromptLine, nonceTitleSuffix, registerPending, type Binding,
|
|
63
|
+
} from "../roles/binding";
|
|
64
|
+
import { realpathSync } from "node:fs";
|
|
65
|
+
import {
|
|
66
|
+
consumeRunnerDispatch, consumeRunnerDispatchLoose, forgetDispatch, lookupDispatch, rememberDispatch, runnerDescription,
|
|
67
|
+
updateDispatchVerification, type CarriedVerification, type DetectionDepth, type DispatchInput, type DispatchRecord,
|
|
68
|
+
} from "../../router/sessions";
|
|
69
|
+
import type { ChangedFile } from "../../verify/dispatch";
|
|
70
|
+
import type { ReferenceState } from "../../verify/types";
|
|
71
|
+
import { randomBytes } from "node:crypto";
|
|
72
|
+
import {
|
|
73
|
+
FLOOR_LIFT_REASON,
|
|
74
|
+
RESUME_REASON,
|
|
75
|
+
RESUME_RUNNING_REASON,
|
|
76
|
+
RESUME_PINNED_REASON,
|
|
77
|
+
RESUME_NAMED_NEEDS_REASON,
|
|
78
|
+
RESUME_NAMED_NEVER_DOWN_REASON,
|
|
79
|
+
ANNOTATION_REASON,
|
|
80
|
+
LOG_ROW_VERSION,
|
|
81
|
+
classifyAgentOrigin,
|
|
82
|
+
makeKey,
|
|
83
|
+
normalizeVariant,
|
|
84
|
+
safeNow,
|
|
85
|
+
splitModelRef,
|
|
86
|
+
type DecisionRow,
|
|
87
|
+
type DecisionTrace,
|
|
88
|
+
type RouteChoice,
|
|
89
|
+
} from "../outcomes/types";
|
|
90
|
+
import { agentModelRef, type AgentView } from "./host-info";
|
|
91
|
+
import { sessionRulesOf, type EngineRuntime, type Prepared, type RolePrepared, type WireLogger } from "./runtime";
|
|
92
|
+
|
|
93
|
+
/** A fresh dispatch can be claimed by a `session.created` event for at most this long. */
|
|
94
|
+
export const PENDING_TTL_MS = 120_000;
|
|
95
|
+
/** Bound on dispatches kept for claiming and for the result (oldest dropped first). */
|
|
96
|
+
export const MAX_PENDING = 200;
|
|
97
|
+
/** A dispatch whose result never arrives is forgotten after this long (the registry's own idle TTL). */
|
|
98
|
+
export const ENTRY_TTL_MS = 3_600_000;
|
|
99
|
+
/** Bound on the process-wide set of handled calls (LRU). */
|
|
100
|
+
export const MAX_HANDLED_CALLS = 4096;
|
|
101
|
+
|
|
102
|
+
export interface RouteCall {
|
|
103
|
+
/** The tool call id (`event.id`): the dispatch ends with the call. */
|
|
104
|
+
readonly callID: string;
|
|
105
|
+
/** The dispatching (orchestrator) session. */
|
|
106
|
+
readonly sessionID: string;
|
|
107
|
+
/** Its agent. */
|
|
108
|
+
readonly agent: string | undefined;
|
|
109
|
+
/** The call's input in the adapter's legacy vocabulary: `agent` (and `subagent_type`), `prompt`, `description`, `model`, `sessionID` (`task_id`). */
|
|
110
|
+
readonly args: Readonly<Record<string, unknown>>;
|
|
111
|
+
/** The model `subagentTiers` would fill in when the call sets none (the engine resolves the pick with it). */
|
|
112
|
+
readonly tierModel?: string | undefined;
|
|
113
|
+
/** The router config the caller already loaded for this call. */
|
|
114
|
+
readonly cfg?: RouterConfig | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* #84 P2.1, role dispatches only: actions widened for this resume (`consumeAuthority(…).widened`, P1.6). They enter
|
|
117
|
+
* `grantFor(…, widened, …)`, so the authority floor is recomputed on them (handoff 36). Absent = none.
|
|
118
|
+
*/
|
|
119
|
+
readonly widened?: readonly AuthorityAction[] | undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface RouteOutcome {
|
|
123
|
+
readonly mode: "static" | "shadow" | "advise" | "enforce";
|
|
124
|
+
/** The prompt without its first-line `[route …]`; only when something was stripped. Role dispatch: also ends with the nonce line. */
|
|
125
|
+
readonly prompt?: string;
|
|
126
|
+
/** `enforce`: the agent to dispatch instead (never for a pinned dispatch). */
|
|
127
|
+
readonly agent?: string;
|
|
128
|
+
/** `enforce`: `provider/model[#variant]` to dispatch with. Role dispatch: ALWAYS set, in every engine mode (I2). */
|
|
129
|
+
readonly model?: string;
|
|
130
|
+
readonly decisionID?: string;
|
|
131
|
+
/**
|
|
132
|
+
* #84 P2.1, a fresh role dispatch: the description with the nonce title suffix at its END (`nonceTitleSuffix`). The adapter
|
|
133
|
+
* must apply it like `prompt` (P2.1-C: `args.description = routed.description`).
|
|
134
|
+
*/
|
|
135
|
+
readonly description?: string;
|
|
136
|
+
/** #84 P2.1: what the role path decided (absent for every tier dispatch). */
|
|
137
|
+
readonly role?: RoleRouted;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** #84 P2.1: one routed role dispatch, as the adapter (P2.1-C) needs it (header root, guard profile, escalation hint). */
|
|
141
|
+
export interface RoleRouted {
|
|
142
|
+
readonly callID: string;
|
|
143
|
+
readonly parentSessionID: string;
|
|
144
|
+
/** The role agent. */
|
|
145
|
+
readonly agent: string;
|
|
146
|
+
/** The tier the dispatched rung belongs to (role × tier statistics, guard profile, escalation hint). */
|
|
147
|
+
readonly tier: string;
|
|
148
|
+
/** `provider/model[#variant]` set as the call's `model`. */
|
|
149
|
+
readonly model: string;
|
|
150
|
+
/** `tierBounds(…)` of the dispatch. */
|
|
151
|
+
readonly window: { readonly floor: string; readonly ceiling: string; readonly pinned: string | null };
|
|
152
|
+
readonly grant: DispatchGrant;
|
|
153
|
+
/** The validated work root (canonical long form), or null (no `root=` match, or the session directory could not be resolved). */
|
|
154
|
+
readonly workRoot: string | null;
|
|
155
|
+
/**
|
|
156
|
+
* #84 P3.3 DF2-F1 (QA-P33F1-1-1, 1-3): where the router's gate verifies this dispatch — the grant's work root (a resume keeps the
|
|
157
|
+
* child's bound root, whatever its prompt's route line says), else the canonical session directory (no validated work root).
|
|
158
|
+
*/
|
|
159
|
+
readonly verifyRoot: string;
|
|
160
|
+
/** The route line's `root=` as written, or null. */
|
|
161
|
+
readonly requestedRoot: string | null;
|
|
162
|
+
/** Work-root, grant and catalog notes (for the dispatch header / parent result). */
|
|
163
|
+
readonly notes: readonly string[];
|
|
164
|
+
readonly detection: EffectiveDetection;
|
|
165
|
+
/** The dispatch's total call budget (`roleGuardProfile(spec, tier, routeLine.budget).budget`). */
|
|
166
|
+
readonly budget: number;
|
|
167
|
+
/** The route line's `budget=`, or null (pass it to `roleGuardProfile`, handoff 27). */
|
|
168
|
+
readonly routeBudget: number | null;
|
|
169
|
+
/** The nonce registered for a fresh dispatch; null on a resume (no pending entry). */
|
|
170
|
+
readonly nonce: string | null;
|
|
171
|
+
/** The decision row's id; null when no row is written (`engine: static`). */
|
|
172
|
+
readonly decisionID: string | null;
|
|
173
|
+
/** The resumed child (`sessionID`/`task_id`), or null. */
|
|
174
|
+
readonly resumeID: string | null;
|
|
175
|
+
/** The next tier of the role's range above `tier` (escalation hint, P-8); null at the ceiling. */
|
|
176
|
+
readonly nextTier: string | null;
|
|
177
|
+
/** The effective task class of the dispatch (re-dispatch signal, handoff 17); null when unknown. */
|
|
178
|
+
readonly class: string | null;
|
|
179
|
+
/**
|
|
180
|
+
* QA-G-A1-2: a delegate's dispatch (`decideDelegateRoleDispatch`: unparsed, the floor rung of the local-only window). The adapter
|
|
181
|
+
* never consumes an authority request on it. Absent for every orchestrator dispatch.
|
|
182
|
+
*/
|
|
183
|
+
readonly delegate?: true;
|
|
184
|
+
/**
|
|
185
|
+
* QA-G-B-2-1: a resume that CARRIES the acceptance of the dispatch it resumes (it names no `[acceptance]` block of its own). Its
|
|
186
|
+
* gate runs at once — never deferred — on the child's cumulative change set since the attempt that introduced the block
|
|
187
|
+
* ({@link roleAttemptVerification}), and a check that ran no process is unverifiable. Absent otherwise.
|
|
188
|
+
*/
|
|
189
|
+
readonly carried?: true;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* #84 P2.1: a role dispatch the router refuses (malformed first route line, no candidate inside the tier window, the router could not
|
|
194
|
+
* route it). `route()` THROWS it — the one exception to "never throws" — so the adapter's `execute.before` fails the call with this
|
|
195
|
+
* message and the host never runs the child. It never falls back to a tier agent (QA-P12-1-5).
|
|
196
|
+
*/
|
|
197
|
+
export class RoleDispatchRefusal extends Error {
|
|
198
|
+
readonly agent: string;
|
|
199
|
+
readonly reason: string;
|
|
200
|
+
constructor(agent: string, reason: string) {
|
|
201
|
+
super(`[router] role dispatch @${agent} refused: ${reason}`);
|
|
202
|
+
this.name = "RoleDispatchRefusal";
|
|
203
|
+
this.agent = agent;
|
|
204
|
+
this.reason = reason;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** Exact refusal reasons of the role path (shared with the tests). */
|
|
209
|
+
export const ROLE_REFUSALS = {
|
|
210
|
+
malformed:
|
|
211
|
+
"the first line of the prompt starts like a route line but is not a valid one (unbalanced, too long, ...); fix it (`[route class=… root=<absolute path>]`) or remove it",
|
|
212
|
+
noPrompt: "the call carries no prompt",
|
|
213
|
+
noCandidate: (floor: string, ceiling: string, reasons: readonly string[]): string =>
|
|
214
|
+
`no model is available inside the tier window ${floor}..${ceiling} (${reasons.join(", ") || "window:no-candidates"}); the router never falls back to a tier agent — fix the preset, or dispatch a tier agent explicitly`,
|
|
215
|
+
failed: (detail: string): string => `the router could not route it (${detail}); retry, or dispatch a tier agent explicitly`,
|
|
216
|
+
session: (detail: string): string => `the dispatching session is unavailable (${detail}); retry`,
|
|
217
|
+
} as const;
|
|
218
|
+
|
|
219
|
+
const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Titles of the runner's own children (`description` of `v2-client.ts`: `Router <agent> delegation`, `Router result
|
|
223
|
+
* verification`): a `session.created` carrying one is the runner's, never an orchestrator dispatch's.
|
|
224
|
+
*/
|
|
225
|
+
const RUNNER_CHILD_TITLE = /^Router (?:.+ delegation|result verification)$/;
|
|
226
|
+
|
|
227
|
+
export interface DispatchRouter {
|
|
228
|
+
/**
|
|
229
|
+
* Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws, except
|
|
230
|
+
* {@link RoleDispatchRefusal} for a role dispatch the router refuses (#84 P2.1; tier dispatches never throw).
|
|
231
|
+
*/
|
|
232
|
+
route(call: RouteCall): Promise<RouteOutcome>;
|
|
233
|
+
/**
|
|
234
|
+
* The input the host is about to execute (`event.input` after the legacy hook ran): write the call's decision row, then register the
|
|
235
|
+
* dispatch from it. A call `route()` did not act on is ignored. Never throws.
|
|
236
|
+
*/
|
|
237
|
+
commit(callID: string, input: unknown): void;
|
|
238
|
+
/** A `session.created` event: claim the waiting dispatch of this child, if there is one. Never throws. */
|
|
239
|
+
onSessionCreated(created: { readonly sessionID: unknown; readonly parentID: unknown; readonly agent: unknown; readonly title: unknown }): void;
|
|
240
|
+
/** `execute.after`: the call's result names the child (or `null`). Registers/corrects, then forgets the call. Never throws. */
|
|
241
|
+
onCallResult(callID: string, childSessionID: string | null): void;
|
|
242
|
+
/** The call ended without a result, or its hook chain failed: forget it. */
|
|
243
|
+
onCallFinished(callID: string): void;
|
|
244
|
+
/**
|
|
245
|
+
* QA-P21-1-11 (handoff 20): a role child bound to its dispatch (`bind`). The first time per child, an annotation row records the
|
|
246
|
+
* OBSERVED binding kind (reason `note:binding:<kind>`, `note:binding:unknown` for an unknown one) against its dispatch's decision
|
|
247
|
+
* row; nothing when the engine writes no rows or the dispatch is unknown. Never throws.
|
|
248
|
+
*/
|
|
249
|
+
noteBinding(childSessionID: string, binding: Pick<Binding, "kind" | "decisionID">): void;
|
|
250
|
+
/** Dispatches still waiting to be claimed (diagnostics, tests). */
|
|
251
|
+
pendingCount(): number;
|
|
252
|
+
/** Children registered by a wrong heuristic claim and not yet taken over by their own dispatch (diagnostics, tests). */
|
|
253
|
+
misclaimedCount(): number;
|
|
254
|
+
/** This instance is gone: it no longer owns any session directory. Idempotent. */
|
|
255
|
+
dispose(): void;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export interface DispatchRouterDeps {
|
|
259
|
+
readonly runtime: EngineRuntime;
|
|
260
|
+
/** `ctx.session.get({ sessionID })`. */
|
|
261
|
+
readonly getSession: (sessionID: string) => Promise<unknown>;
|
|
262
|
+
/** The adapter's own grader agent id: never routed. */
|
|
263
|
+
readonly graderAgent: string;
|
|
264
|
+
/** The default directory of the plugin instance (fallback `cwd` of the classifier). */
|
|
265
|
+
readonly directory: string;
|
|
266
|
+
readonly logger: WireLogger;
|
|
267
|
+
readonly now?: () => number;
|
|
268
|
+
/**
|
|
269
|
+
* #84 P2.1 (role dispatches only): stdout of `git worktree list --porcelain` run in `cwd` (the session directory). Default:
|
|
270
|
+
* {@link gitWorktreeList} (the hardened spawn, 5 s timeout). Injected by tests.
|
|
271
|
+
*/
|
|
272
|
+
readonly listWorktrees?: (cwd: string) => Promise<string>;
|
|
273
|
+
/** #84 P2.1: canonical long form of an existing path (default `realpathSync.native`). Only called on an already matched root. */
|
|
274
|
+
readonly realpath?: (path: string) => string;
|
|
275
|
+
/** #84 P2.1: path rules of the work-root comparison (default `process.platform`). */
|
|
276
|
+
readonly platform?: NodeJS.Platform;
|
|
277
|
+
/** #84 P2.1: the router is bypassed for this session (`/bypass`, `src/index.ts`): the verification gate will not run (S10/P-9). */
|
|
278
|
+
readonly isBypassed?: (sessionID: string) => boolean;
|
|
279
|
+
/** #84 P2.1: environment of the enforcement-mode env gate (default `process.env`). */
|
|
280
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
281
|
+
/**
|
|
282
|
+
* QA-P21-1-8: the role path is live (the plugin STARTED in roles mode, so its role agents and tools exist). `false` → every role
|
|
283
|
+
* agent takes the tier path, as in tiers mode. Default: live.
|
|
284
|
+
*/
|
|
285
|
+
readonly rolesEnabled?: (agent: string) => boolean;
|
|
286
|
+
/**
|
|
287
|
+
* QA-P21-2 nit 3: `router_verify` is registered (index.ts `routerVerifyEnabled`); `false` → nothing is deferred, so a deferred
|
|
288
|
+
* directive does not weaken the detection. Absent: treated as registered.
|
|
289
|
+
*/
|
|
290
|
+
readonly routerVerifyEnabled?: () => boolean;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** What `route()` decided, until `commit()` has the final input. */
|
|
294
|
+
interface Decided {
|
|
295
|
+
readonly parentSessionID: string;
|
|
296
|
+
readonly decisionID: string;
|
|
297
|
+
readonly facts: DecisionRow["facts"];
|
|
298
|
+
readonly acceptance: DetectionDepth;
|
|
299
|
+
readonly description: string | null;
|
|
300
|
+
/**
|
|
301
|
+
* QA-G-A2: the decision row, written by `commit()` — i.e. only for a dispatch whose hook chain let it through to the host. A call the
|
|
302
|
+
* legacy hook rejects (`onCallFinished`) never writes it. Known limit: a call the HOST then fails (`onCallResult` with no child for a
|
|
303
|
+
* fresh dispatch) keeps its row; no retraction row is written.
|
|
304
|
+
*/
|
|
305
|
+
readonly row: DecisionRow | null;
|
|
306
|
+
/** Appends a row to the decision log (`Prepared.enqueue` of the call). */
|
|
307
|
+
readonly enqueue: (row: DecisionRow) => void;
|
|
308
|
+
/** A34 (QA-G-B8): the capability rank of what the host is handed (`row.capability.dispatched`); `null` = unknown. */
|
|
309
|
+
readonly capabilityOf: (ran: RanDispatch) => number | null;
|
|
310
|
+
/** What the engine dispatches: the fallback for what the final input leaves out. `null`: the pick resolved to no model (row only). */
|
|
311
|
+
readonly final: { readonly agent: string; readonly model: string; readonly variant: string | null } | null;
|
|
312
|
+
/** The agent the orchestrator NAMED for this dispatch, before the router changed anything: recorded with the child (QA-2.4-R3-1). */
|
|
313
|
+
readonly picked: string;
|
|
314
|
+
readonly routerIds: readonly string[];
|
|
315
|
+
/** Resolve an agent the legacy hook switched to (the same resolution the engine used for the pick). */
|
|
316
|
+
readonly resolve: (agent: string) => ChosenDispatch | null;
|
|
317
|
+
readonly at: number;
|
|
318
|
+
/** #84 P2.1: a role dispatch (absent for every tier dispatch). */
|
|
319
|
+
readonly role?: RoleCommit;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/** What `commit()` needs of a role dispatch. */
|
|
323
|
+
interface RoleCommit {
|
|
324
|
+
/** The tier of the dispatched rung: the registry's `tier` (running tier on a resume, role × tier rows of ingestion). */
|
|
325
|
+
readonly tier: string;
|
|
326
|
+
/** `false` when the engine is static: no instance may score the attempt (`DispatchInput.outcomes`). */
|
|
327
|
+
readonly outcomes: boolean;
|
|
328
|
+
/** The pending binding entry to register (a fresh dispatch); null on a resume. */
|
|
329
|
+
readonly pending: { readonly nonce: string; readonly grant: DispatchGrant; readonly budget: number; readonly description: string; readonly decisionID: string | null } | null;
|
|
330
|
+
/** QA-G-B-1: the verification this dispatch carries to its resumes (its own, or the one it carried itself); null: none. */
|
|
331
|
+
readonly verification: CarriedVerification | null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** A committed dispatch, kept until its call ends. */
|
|
335
|
+
interface Entry {
|
|
336
|
+
readonly callID: string;
|
|
337
|
+
readonly parentSessionID: string;
|
|
338
|
+
readonly agent: string;
|
|
339
|
+
readonly description: string | null;
|
|
340
|
+
readonly input: DispatchInput;
|
|
341
|
+
readonly at: number;
|
|
342
|
+
/** A resume: the child it was registered under, and what the registry held for it before (QA-2.2-R2-1). */
|
|
343
|
+
readonly resumeID?: string;
|
|
344
|
+
readonly previous?: DispatchRecord;
|
|
345
|
+
/** `waiting`: no child yet; `claimed`: a `session.created` was matched to it; `resumed`: registered at commit. */
|
|
346
|
+
state: "waiting" | "claimed" | "resumed";
|
|
347
|
+
claimedChild?: string;
|
|
348
|
+
/** #84 P2.1: a binding entry was registered for this call (`registerPending`); a rejected call evicts it. */
|
|
349
|
+
rolePending?: true;
|
|
350
|
+
/** QA-P21-1-11: a role dispatch's decision row and its log, for the binding annotation row (absent: no rows). */
|
|
351
|
+
roleRow?: { readonly row: DecisionRow; readonly enqueue: (row: DecisionRow) => void };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* A3: every plugin instance of the process may be handed the same hook event. The first instance whose engine is live
|
|
356
|
+
* claims the call; the others leave it alone (the first one already routed, logged and will register it).
|
|
357
|
+
*/
|
|
358
|
+
const handledCalls = new Set<string>();
|
|
359
|
+
|
|
360
|
+
function claimCall(key: string): boolean {
|
|
361
|
+
if (handledCalls.has(key)) return false;
|
|
362
|
+
handledCalls.add(key);
|
|
363
|
+
while (handledCalls.size > MAX_HANDLED_CALLS) handledCalls.delete(handledCalls.values().next().value as string);
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Bound on children with pending subagent-result annotations (oldest dropped first). */
|
|
368
|
+
export const MAX_ANNOTATED_CHILDREN = 256;
|
|
369
|
+
/** Bound on annotations kept per child (oldest dropped first). */
|
|
370
|
+
export const MAX_ANNOTATIONS_PER_CHILD = 8;
|
|
371
|
+
|
|
372
|
+
export interface SubagentAnnotation {
|
|
373
|
+
readonly kind: "budget" | "authority";
|
|
374
|
+
readonly text: string;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Process-wide: annotations for the parent's `subagent` result, keyed by child session. */
|
|
378
|
+
const subagentAnnotations = new Map<string, SubagentAnnotation[]>();
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Seam: record an annotation to be appended to the parent's `subagent` result of `childSessionID`.
|
|
382
|
+
* Bounded; consumed once by {@link takeSubagentAnnotations}.
|
|
383
|
+
*/
|
|
384
|
+
export function annotateSubagentResult(kind: "budget" | "authority", childSessionID: string, text: string): void {
|
|
385
|
+
const list = subagentAnnotations.get(childSessionID) ?? [];
|
|
386
|
+
subagentAnnotations.delete(childSessionID);
|
|
387
|
+
list.push({ kind, text });
|
|
388
|
+
while (list.length > MAX_ANNOTATIONS_PER_CHILD) list.shift();
|
|
389
|
+
subagentAnnotations.set(childSessionID, list);
|
|
390
|
+
while (subagentAnnotations.size > MAX_ANNOTATED_CHILDREN) subagentAnnotations.delete(subagentAnnotations.keys().next().value as string);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** The annotations recorded for `childSessionID`, in order; they are removed (a second call returns none). */
|
|
394
|
+
export function takeSubagentAnnotations(childSessionID: string): readonly SubagentAnnotation[] {
|
|
395
|
+
const list = subagentAnnotations.get(childSessionID);
|
|
396
|
+
if (list === undefined) return [];
|
|
397
|
+
subagentAnnotations.delete(childSessionID);
|
|
398
|
+
return list;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// ---------------------------------------------------------------------------
|
|
402
|
+
// #84 P2.1 (T2.1.2): role dispatch path — exported API for the adapter (P2.1-C)
|
|
403
|
+
// ---------------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
/** Bound on routed role dispatches kept for the adapter (oldest dropped first). */
|
|
406
|
+
export const MAX_ROUTED_ROLES = 1000;
|
|
407
|
+
|
|
408
|
+
/** Process-wide: the routed role dispatch of each call id, for the legacy hook (header) and `execute.after` (hint). */
|
|
409
|
+
const routedRoles = new Map<string, RoleRouted>();
|
|
410
|
+
|
|
411
|
+
function rememberRoutedRole(routed: RoleRouted): void {
|
|
412
|
+
routedRoles.delete(routed.callID);
|
|
413
|
+
routedRoles.set(routed.callID, routed);
|
|
414
|
+
while (routedRoles.size > MAX_ROUTED_ROLES) routedRoles.delete(routedRoles.keys().next().value as string);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** The role dispatch `route()` decided for `callID` (kept until {@link forgetRoutedRole}, a rejected call, or the LRU bound). */
|
|
418
|
+
export function routedRoleOf(callID: string): RoleRouted | undefined {
|
|
419
|
+
return routedRoles.get(callID);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Handoff 30: the routed decision's work root for `buildDispatchHeader` (canonical long form). `undefined` = not a routed role
|
|
424
|
+
* dispatch (tier dispatches: the tier path does not resolve roots); `null` = a role dispatch without a validated work root.
|
|
425
|
+
*/
|
|
426
|
+
export function routedWorkRoot(callID: string): string | null | undefined {
|
|
427
|
+
const routed = routedRoles.get(callID);
|
|
428
|
+
return routed === undefined ? undefined : routed.workRoot;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Drop what `route()` kept for `callID` (the adapter calls it once `execute.after` is done with it). */
|
|
432
|
+
export function forgetRoutedRole(callID: string): void {
|
|
433
|
+
routedRoles.delete(callID);
|
|
434
|
+
strippedRoots.delete(callID);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Handoff 30 (tier dispatches, v2 shadow/advise/enforce): the `root=` of the first-line route line `route()` stripped from the
|
|
439
|
+
* prompt, so the legacy hook's dispatch header can still name it (T1.5.3a). Process-wide, bounded like {@link routedRoles}.
|
|
440
|
+
*/
|
|
441
|
+
const strippedRoots = new Map<string, string>();
|
|
442
|
+
|
|
443
|
+
function rememberStrippedRoot(callID: string, root: string): void {
|
|
444
|
+
strippedRoots.delete(callID);
|
|
445
|
+
strippedRoots.set(callID, root);
|
|
446
|
+
while (strippedRoots.size > MAX_ROUTED_ROLES) strippedRoots.delete(strippedRoots.keys().next().value as string);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** The route line's `root=` of a tier dispatch whose route line `route()` stripped; undefined otherwise. */
|
|
450
|
+
export function strippedRouteRoot(callID: string): string | undefined {
|
|
451
|
+
return strippedRoots.get(callID);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** A role's max authority (allow − deny, never `execute`): the `maxOf` of `bind` / `currentBinding` (handoff 33). */
|
|
455
|
+
export function roleMaxActions(spec: RoleSpec | undefined): readonly AuthorityAction[] | undefined {
|
|
456
|
+
if (spec === undefined) return undefined;
|
|
457
|
+
return spec.authority.allow.filter((action) => action !== "execute" && !spec.authority.deny.includes(action));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Text form of a path for the work-root comparison, WITHOUT touching the filesystem: separators unified (win32: `/` → `\`),
|
|
462
|
+
* repeated separators and `.` segments dropped, the trailing separator dropped (a drive or POSIX root keeps it), case folded on win32.
|
|
463
|
+
*/
|
|
464
|
+
export function normalizeRootText(path: string, platform: NodeJS.Platform = process.platform): string {
|
|
465
|
+
const win = platform === "win32";
|
|
466
|
+
const sep = win ? "\\" : "/";
|
|
467
|
+
let text = path.trim();
|
|
468
|
+
if (win) text = text.replace(/\//g, "\\");
|
|
469
|
+
const absolute = text.startsWith(sep);
|
|
470
|
+
const parts = text.split(sep).filter((part) => part !== "" && part !== ".");
|
|
471
|
+
let out = (absolute ? sep : "") + parts.join(sep);
|
|
472
|
+
if (win && /^[A-Za-z]:$/.test(out)) out += sep; // `D:\` stays a root
|
|
473
|
+
if (out === "") out = absolute ? sep : "";
|
|
474
|
+
return win ? out.toLowerCase() : out;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* The worktree paths of `git worktree list --porcelain` output (the `worktree <path>` line of each entry), as git prints them, in
|
|
479
|
+
* git's order (the main worktree first). QA-P23-A4: an entry git marks `prunable` (its directory is gone or no longer points
|
|
480
|
+
* back) is dropped — it is not a work root any more, even if a plain directory now sits at its path.
|
|
481
|
+
*/
|
|
482
|
+
export function parseWorktreeList(porcelain: string): string[] {
|
|
483
|
+
const out: string[] = [];
|
|
484
|
+
let current: string | undefined;
|
|
485
|
+
let prunable = false;
|
|
486
|
+
const flush = (): void => {
|
|
487
|
+
if (current !== undefined && !prunable) out.push(current);
|
|
488
|
+
current = undefined;
|
|
489
|
+
prunable = false;
|
|
490
|
+
};
|
|
491
|
+
for (const raw of porcelain.split("\n")) {
|
|
492
|
+
const line = raw.replace(/\r$/, "");
|
|
493
|
+
if (line.startsWith("worktree ")) {
|
|
494
|
+
flush();
|
|
495
|
+
if (line.length > "worktree ".length) current = line.slice("worktree ".length);
|
|
496
|
+
} else if (line === "prunable" || line.startsWith("prunable ")) {
|
|
497
|
+
prunable = true;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
flush();
|
|
501
|
+
return out;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export interface WorkRootResolution {
|
|
505
|
+
/** Canonical long form (`realpathSync.native`) of the validated root; null = no validated work root. */
|
|
506
|
+
readonly workRoot: string | null;
|
|
507
|
+
/** The route line's `root=` as written, or null. */
|
|
508
|
+
readonly requested: string | null;
|
|
509
|
+
/** Why there is no work root (for the grant notes and the dispatch header); null when resolved. */
|
|
510
|
+
readonly note: string | null;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
export interface WorkRootDeps {
|
|
514
|
+
readonly listWorktrees: (cwd: string) => Promise<string>;
|
|
515
|
+
readonly realpath: (path: string) => string;
|
|
516
|
+
readonly platform: NodeJS.Platform;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* `git worktree list --porcelain` in `cwd` (stdout); rejects on any failure. QA-G-A2-3: the hardened spawn of `listWorktrees`
|
|
521
|
+
* (role-agents.ts) — the absolute git executable selected outside the work-root guards of `cwd` (`workRootGuards`), the
|
|
522
|
+
* `hardeningArgs()` flags, `gitEnvironment()` (no inherited GIT_*, no system/global config), no shell — bounded to 5 s and 1 MiB.
|
|
523
|
+
* QA-G-A2-2-1: the user's system/global `safe.directory` values are passed back as `-c safe.directory=…` pairs (as `inspectGit`
|
|
524
|
+
* does), so a repository trusted that way is still listed instead of failing with "dubious ownership".
|
|
525
|
+
*/
|
|
526
|
+
export async function gitWorktreeList(cwd: string): Promise<string> {
|
|
527
|
+
// Loaded lazily: the hardened git helpers are only needed when a worktree list actually runs.
|
|
528
|
+
const { gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded, workRootGuards } = await import("../../router/git-tools");
|
|
529
|
+
const started = performance.now();
|
|
530
|
+
const executable = gitExecutable(workRootGuards(cwd));
|
|
531
|
+
const trusted = await inheritedSafeDirectoryArgs(executable, 5_000);
|
|
532
|
+
const result = await spawnBounded(executable, [...hardeningArgs(), ...trusted, "worktree", "list", "--porcelain"], cwd, {
|
|
533
|
+
env: gitEnvironment(), timeoutMs: Math.max(1, 5_000 - (performance.now() - started)), maxBytes: 1 << 20,
|
|
534
|
+
});
|
|
535
|
+
if (result.code !== 0 || result.truncated) {
|
|
536
|
+
throw new Error(`git worktree list failed (exit ${String(result.code)}${result.truncated ? ", output truncated" : ""}): ${result.stderr.toString("utf8").trim()}`);
|
|
537
|
+
}
|
|
538
|
+
return result.output.toString("utf8");
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* The work root of a role dispatch (plan §2.2, handoff 8). `root` comes ONLY from `ClassifyResult.trace.routeLine.root` (never a
|
|
543
|
+
* re-parse of the prompt).
|
|
544
|
+
* - no `root=` → the session directory (canonical long form);
|
|
545
|
+
* - `root=` → its normalised TEXT is compared with the session directory and with every worktree of `git worktree list --porcelain`
|
|
546
|
+
* (run in the session directory) BEFORE any filesystem call on it; a match → the canonical long form of the matched entry;
|
|
547
|
+
* - anything else (no match, git unavailable, an entry that does not resolve) → `workRoot: null` with a note.
|
|
548
|
+
* Never throws.
|
|
549
|
+
*/
|
|
550
|
+
export async function resolveRoleWorkRoot(
|
|
551
|
+
input: { readonly root: string | null; readonly sessionDirectory: string },
|
|
552
|
+
deps: WorkRootDeps,
|
|
553
|
+
): Promise<WorkRootResolution> {
|
|
554
|
+
const canonical = (path: string): string | null => {
|
|
555
|
+
try {
|
|
556
|
+
const resolved = deps.realpath(path);
|
|
557
|
+
return typeof resolved === "string" && resolved !== "" ? resolved : null;
|
|
558
|
+
} catch {
|
|
559
|
+
return null;
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
if (input.root === null) {
|
|
563
|
+
const dir = canonical(input.sessionDirectory);
|
|
564
|
+
return dir === null
|
|
565
|
+
? { workRoot: null, requested: null, note: `the session directory ${input.sessionDirectory} could not be resolved: no work root` }
|
|
566
|
+
: { workRoot: dir, requested: null, note: null };
|
|
567
|
+
}
|
|
568
|
+
const want = normalizeRootText(input.root, deps.platform);
|
|
569
|
+
let match: string | undefined = normalizeRootText(input.sessionDirectory, deps.platform) === want ? input.sessionDirectory : undefined;
|
|
570
|
+
if (match === undefined) {
|
|
571
|
+
let listed: string[] = [];
|
|
572
|
+
try {
|
|
573
|
+
listed = parseWorktreeList(await deps.listWorktrees(input.sessionDirectory));
|
|
574
|
+
} catch {
|
|
575
|
+
listed = [];
|
|
576
|
+
}
|
|
577
|
+
match = listed.find((path) => normalizeRootText(path, deps.platform) === want);
|
|
578
|
+
}
|
|
579
|
+
const none = `root=${input.root} is neither the session directory nor a worktree listed by \`git worktree list --porcelain\`: no work root`;
|
|
580
|
+
if (match === undefined) return { workRoot: null, requested: input.root, note: none };
|
|
581
|
+
const resolved = canonical(match);
|
|
582
|
+
return resolved === null
|
|
583
|
+
? { workRoot: null, requested: input.root, note: `root=${input.root} does not resolve on disk: no work root` }
|
|
584
|
+
: { workRoot: resolved, requested: input.root, note: null };
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* S10/P-9 (agent-agnostic): the router's own verification gate will run deterministic checks for this dispatch — the call is a
|
|
589
|
+
* `task`/`subagent` (always, here), `enforcement.mode ≠ off` (env gate included), `verify.require ≠ never` (the condition of
|
|
590
|
+
* `verify/dispatch.shouldVerifyTask`), the router is not bypassed, and the prompt's `[acceptance]` block carries a machine check.
|
|
591
|
+
*/
|
|
592
|
+
export function roleRouterGate(input: {
|
|
593
|
+
readonly cfg: RouterConfig;
|
|
594
|
+
readonly bypassed: boolean;
|
|
595
|
+
/** `detectionOf(prompt)`: the depth of the prompt's own `[acceptance]` block. */
|
|
596
|
+
readonly acceptance: Detection;
|
|
597
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
598
|
+
/**
|
|
599
|
+
* QA-P21-1-2: the dispatch's verification is DEFERRED (`roleGateDeferred`): the gate does not run at the return, so the
|
|
600
|
+
* detection is never `deterministic` on its account. Absent = not deferred.
|
|
601
|
+
*/
|
|
602
|
+
readonly deferred?: boolean;
|
|
603
|
+
/**
|
|
604
|
+
* #84 P3.3 DF2-F1: the gate cannot run the checks in the dispatch's work root ({@link roleGateOutsideWorkRoot}), so the
|
|
605
|
+
* detection is never `deterministic` on its account. Absent = it can.
|
|
606
|
+
*/
|
|
607
|
+
readonly outsideWorkRoot?: boolean;
|
|
608
|
+
}): boolean {
|
|
609
|
+
if (input.deferred === true || input.acceptance !== "deterministic") return false;
|
|
610
|
+
return roleVerificationRuns(input);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/**
|
|
614
|
+
* #84 QA-G-B-7: the router's gate verifies this role dispatch at all — `enforcement.mode ≠ off` (env gate included), the router is
|
|
615
|
+
* not bypassed (`/bypass`), `verify.require ≠ never`, and the requested cwd is not outside the root the gate verifies in
|
|
616
|
+
* (`outsideWorkRoot`). When it does not, nothing checks the work: the dispatch's detection is `none` (`effectiveDetection`'s
|
|
617
|
+
* `verifies`), whatever its claim or `[acceptance]` block says. Fails toward "does not run" on any error.
|
|
618
|
+
*/
|
|
619
|
+
export function roleVerificationRuns(input: {
|
|
620
|
+
readonly cfg: RouterConfig;
|
|
621
|
+
readonly bypassed: boolean;
|
|
622
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
623
|
+
readonly outsideWorkRoot?: boolean;
|
|
624
|
+
}): boolean {
|
|
625
|
+
if (input.bypassed || input.outsideWorkRoot === true) return false;
|
|
626
|
+
let mode = "off";
|
|
627
|
+
try {
|
|
628
|
+
mode = resolveEnforcementMode({ config: input.cfg, env: { ...(input.env ?? process.env) } }).mode;
|
|
629
|
+
} catch {
|
|
630
|
+
mode = "off";
|
|
631
|
+
}
|
|
632
|
+
if (mode === "off") return false;
|
|
633
|
+
return (input.cfg.enforcement?.verify?.require ?? "whenDoDPresent") !== "never";
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* QA-P21-1-2: the dispatch's verification would be deferred, exactly as the native path decides it (index.ts `isDeferred` →
|
|
638
|
+
* verify/wiring.ts `isDeferred`): its `VERIFY:` directives resolve to `deferred` (the configured `defaultVerify` when the text has
|
|
639
|
+
* none; the text is `dispatchDirectiveText(prompt, description)`) AND its DoD carries a `testsPass` check. A deferred dispatch
|
|
640
|
+
* returns without the gate (`router_verify` runs it later), so the router's gate cannot back a `deterministic` detection.
|
|
641
|
+
* Fails toward "deferred" on any error (a weaker detection, never a stronger one). QA-P21-2 nit 3: nothing is deferred when
|
|
642
|
+
* `router_verify` is not registered (`verifyEnabled: false`, index.ts `routerVerifyEnabled`): the gate then runs at the return.
|
|
643
|
+
*/
|
|
644
|
+
export function roleGateDeferred(cfg: RouterConfig, prompt: string, description: string, opts: { readonly verifyEnabled?: boolean } = {}): boolean {
|
|
645
|
+
if (opts.verifyEnabled === false) return false;
|
|
646
|
+
try {
|
|
647
|
+
const text = prompt.trim() !== "" ? prompt : description; // verify/wiring.ts dispatchDirectiveText
|
|
648
|
+
const budget = resolveVerifyBudget(cfg);
|
|
649
|
+
const directives = parseVerifyDirectives(text, {
|
|
650
|
+
defaultVerify: budget.defaultVerify, captureWaitMs: budget.captureWaitMs, baselineTimeoutMs: budget.baselineTimeoutMs,
|
|
651
|
+
});
|
|
652
|
+
if (directives.mode !== "deferred") return false;
|
|
653
|
+
return buildDelegationDoD({ prompt, description }).checks.some((check) => check.kind === "testsPass");
|
|
654
|
+
} catch {
|
|
655
|
+
return true;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* #84 P3.3 DF2-F1: the router's gate verifies a role dispatch in its work root (index.ts `verificationScopeOf` → gate
|
|
661
|
+
* `Delegation.workRoot`). It cannot when the dispatch has no validated work root (`workRoot: null`), or when the requested cwd —
|
|
662
|
+
* the call's `cwd` argument, else the `[acceptance]` block's `cwd:` (`requestedVerificationCwd`, the after-hook's order, nit 3) —
|
|
663
|
+
* lies outside that root by P2.3's rule (`verificationScope`; the gate refuses it: unverifiable). Then the router's gate cannot
|
|
664
|
+
* back a `deterministic` detection. `workRoot` is the GRANT's root (QA-P33F1-1-1: a resume keeps the child's bound root). Fails
|
|
665
|
+
* toward "outside" on any error (a weaker detection, never a stronger one).
|
|
666
|
+
*
|
|
667
|
+
* What the decision row records is decided HERE, at dispatch: a gate that later reports the delegation unverifiable for a reason
|
|
668
|
+
* only the return shows (every change outside the work root, a timeout, a verifier error) does not rewrite the row — its verdict
|
|
669
|
+
* carries the caveat (`[router ⚠ UNVERIFIED …]`) and is never accepted as verified.
|
|
670
|
+
*/
|
|
671
|
+
export function roleGateOutsideWorkRoot(workRoot: string | null, prompt: string, description: string, argsCwd?: unknown): boolean {
|
|
672
|
+
if (workRoot === null) return true;
|
|
673
|
+
try {
|
|
674
|
+
return verificationScope(requestedVerificationCwd(argsCwd, buildDelegationDoD({ prompt, description }).cwd), workRoot).outside;
|
|
675
|
+
} catch {
|
|
676
|
+
return true;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
/** QA-P33F1-1-1 / 1-3: where the gate verifies a role dispatch — the grant's work root, else the canonical session directory. */
|
|
681
|
+
function verifyRootOf(grant: DispatchGrant, sessionDirectory: string, realpath: (path: string) => string): string {
|
|
682
|
+
if (grant.workRoot !== null) return grant.workRoot;
|
|
683
|
+
try {
|
|
684
|
+
const real = realpath(sessionDirectory);
|
|
685
|
+
return typeof real === "string" && real !== "" ? real : sessionDirectory;
|
|
686
|
+
} catch {
|
|
687
|
+
return sessionDirectory;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/** The tier above `current` on `order`, up to the role's `ceiling`; null at (or above) the ceiling or when either is not on the order. */
|
|
692
|
+
export function nextRoleTier(order: readonly string[], ceiling: string, current: string | null): string | null {
|
|
693
|
+
if (current === null) return null;
|
|
694
|
+
const at = order.indexOf(current);
|
|
695
|
+
const top = order.indexOf(ceiling);
|
|
696
|
+
if (at < 0 || top < 0 || at >= top) return null;
|
|
697
|
+
return order[at + 1] ?? null;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* P-8 (handoff 39), QA-P21-2-2: the role-aware escalation hint after a verification FAIL — resume the SAME child with the findings;
|
|
702
|
+
* the router itself raises it to the next tier of the role's range ({@link roleEscalationAfterFail} records the raise, the next
|
|
703
|
+
* resume applies it). The orchestrator sets neither `model` nor a `tier=` pin, and never names a tier agent. Pure.
|
|
704
|
+
*/
|
|
705
|
+
export function roleEscalationHint(input: {
|
|
706
|
+
readonly agent: string;
|
|
707
|
+
readonly childSessionID: string | null;
|
|
708
|
+
readonly currentTier: string | null;
|
|
709
|
+
readonly nextTier: string | null;
|
|
710
|
+
}): string {
|
|
711
|
+
const task = input.childSessionID === null ? "the same sessionID" : `the same sessionID ("${input.childSessionID}")`;
|
|
712
|
+
if (input.nextTier === null) {
|
|
713
|
+
const top = input.currentTier === null ? "" : ` (it already runs on its highest tier, ${input.currentTier})`;
|
|
714
|
+
return `NEXT: resume ${task} with @${input.agent} and the findings${top}; set neither \`model\` nor \`tier=\`; do not start a new task and do not treat the prior result as complete.`;
|
|
715
|
+
}
|
|
716
|
+
const from = input.currentTier === null ? "" : ` from ${input.currentTier}`;
|
|
717
|
+
return `NEXT: resume ${task} with @${input.agent} and the findings; the router raises it to ${input.nextTier}${from}; set neither \`model\` nor \`tier=\`; do not start a new task.`;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/** The child's role, running tier and next tier of its role range, from the dispatch registry; null when it is not a role child. */
|
|
721
|
+
function escalationOf(cfg: RouterConfig, childSessionID: string): { agent: string; current: string | null; next: string | null } | null {
|
|
722
|
+
const record = lookupDispatch(childSessionID);
|
|
723
|
+
if (record === undefined) return null;
|
|
724
|
+
const spec = resolveRoles(cfg, "v2").get(record.agent);
|
|
725
|
+
if (spec === undefined) return null;
|
|
726
|
+
const current = record.tier ?? null;
|
|
727
|
+
return { agent: record.agent, current, next: nextRoleTier(roleTierOrder(cfg), spec.tierRange.ceiling, current) };
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* {@link roleEscalationHint} for a child the router registered: its role and running tier from the dispatch registry, the next
|
|
732
|
+
* tier from the role's range on `roleTierOrder(cfg)`. `null` when the child is not a role dispatch of roles mode. Records nothing.
|
|
733
|
+
*/
|
|
734
|
+
export function roleEscalationHintFor(cfg: RouterConfig, childSessionID: string): string | null {
|
|
735
|
+
const e = escalationOf(cfg, childSessionID);
|
|
736
|
+
return e === null ? null : roleEscalationHint({ agent: e.agent, childSessionID, currentTier: e.current, nextTier: e.next });
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/** QA-P21-2-2: pending raises, child → the parent that may consume it and the tier (bounded, oldest out; 30 min TTL). */
|
|
740
|
+
export const MAX_RESUME_RAISES = 1000;
|
|
741
|
+
export const RESUME_RAISE_TTL_MS = 30 * 60 * 1000;
|
|
742
|
+
const resumeRaises = new Map<string, { readonly parentSessionID: string; readonly tier: string; readonly at: number }>();
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* QA-P21-2-2 ("the router raises the tier"): the hint emitted after a verification FAIL of a role child, AND the raise it promises:
|
|
746
|
+
* the next tier of the role's range is recorded for the child, consumed once by `parentSessionID`'s next resume of that child,
|
|
747
|
+
* which applies it as a raise-only floor. Nothing is recorded at the ceiling. `null` when the child is not a role child.
|
|
748
|
+
*/
|
|
749
|
+
export function roleEscalationAfterFail(cfg: RouterConfig, childSessionID: string, parentSessionID: string): string | null {
|
|
750
|
+
const e = escalationOf(cfg, childSessionID);
|
|
751
|
+
if (e === null) return null;
|
|
752
|
+
if (e.next !== null && parentSessionID !== "") {
|
|
753
|
+
resumeRaises.delete(childSessionID);
|
|
754
|
+
resumeRaises.set(childSessionID, { parentSessionID, tier: e.next, at: Date.now() });
|
|
755
|
+
while (resumeRaises.size > MAX_RESUME_RAISES) resumeRaises.delete(resumeRaises.keys().next().value as string);
|
|
756
|
+
}
|
|
757
|
+
return roleEscalationHint({ agent: e.agent, childSessionID, currentTier: e.current, nextTier: e.next });
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** The raise recorded for this parent's resume of the child (not consumed), or null. */
|
|
761
|
+
export function pendingResumeRaise(childSessionID: string, parentSessionID: string): string | null {
|
|
762
|
+
const raise = resumeRaises.get(childSessionID);
|
|
763
|
+
if (raise === undefined) return null;
|
|
764
|
+
if (Date.now() - raise.at >= RESUME_RAISE_TTL_MS) {
|
|
765
|
+
resumeRaises.delete(childSessionID);
|
|
766
|
+
return null;
|
|
767
|
+
}
|
|
768
|
+
return raise.parentSessionID === parentSessionID ? raise.tier : null;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** `prompt` with `line` as its LAST line (every byte of `prompt` kept). */
|
|
772
|
+
function withLastLine(prompt: string, line: string): string {
|
|
773
|
+
if (prompt === "") return line;
|
|
774
|
+
return prompt.endsWith("\n") ? `${prompt}${line}` : `${prompt}\n${line}`;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** The catalog's variant ids of `model`; `null` when the catalog does not know the model (then nothing is dropped). */
|
|
778
|
+
function catalogVariantIds(catalog: RolePrepared["catalog"], model: string): string[] | null {
|
|
779
|
+
let entry: ReturnType<RolePrepared["catalog"]["entry"]>;
|
|
780
|
+
try {
|
|
781
|
+
entry = catalog.entry(model);
|
|
782
|
+
} catch {
|
|
783
|
+
return null;
|
|
784
|
+
}
|
|
785
|
+
if (entry === undefined) return null;
|
|
786
|
+
const variants = Array.isArray(entry.variants) ? entry.variants : [];
|
|
787
|
+
return variants.flatMap((v) => (v !== null && v !== undefined && typeof v.id === "string" ? [v.id] : []));
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* An explicit caller `model` on a role dispatch: kept when it is a rung of the window (inside the bounds); above the ceiling →
|
|
792
|
+
* clamped to the ceiling's rung (the pin rule of `tierBounds`); anything else (below the floor, unknown) → lifted to the floor's
|
|
793
|
+
* rung. On a resume it never moves below what the kernel decided (the running rung).
|
|
794
|
+
*/
|
|
795
|
+
function placeCallerModel(
|
|
796
|
+
ladder: RoleLadder,
|
|
797
|
+
ref: string,
|
|
798
|
+
decided: Candidate,
|
|
799
|
+
resumed: boolean,
|
|
800
|
+
): { readonly candidate: Candidate; readonly code: string } {
|
|
801
|
+
const parts = splitModelRef(ref);
|
|
802
|
+
const model = parts === null ? ref : `${parts.provider}/${parts.model}`;
|
|
803
|
+
const variant = parts === null ? null : parts.variant;
|
|
804
|
+
const cands = ladder.candidates;
|
|
805
|
+
const inside = cands.find((c) => c.model === model && (variant === null || normalizeVariant(c.variant) === normalizeVariant(variant)));
|
|
806
|
+
if (inside !== undefined) {
|
|
807
|
+
if (resumed && inside.rank < decided.rank) return { candidate: decided, code: "kept:caller-model:resume" };
|
|
808
|
+
return { candidate: inside, code: "kept:caller-model" };
|
|
809
|
+
}
|
|
810
|
+
const firsts = ladder.tiers.flatMap((t) => (t.first === null ? [] : [t.first]));
|
|
811
|
+
const floor = cands[firsts[0] ?? 0] ?? decided;
|
|
812
|
+
const ceiling = cands[firsts[firsts.length - 1] ?? 0] ?? decided;
|
|
813
|
+
const rank = capabilityRank(ladder, { model, variant }, null);
|
|
814
|
+
const placed = rank !== null && ladder.ceilingRank !== null && rank > ladder.ceilingRank
|
|
815
|
+
? { candidate: ceiling, code: "clamp:caller-model:ceiling" }
|
|
816
|
+
: { candidate: floor, code: "lift:caller-model:floor" };
|
|
817
|
+
return resumed && placed.candidate.rank < decided.rank ? { candidate: decided, code: "kept:caller-model:resume" } : placed;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/** QA-P21-2-2: the note of a resume raised after a verification FAIL (`raise:verification-fail:<tier>`). */
|
|
821
|
+
export const RESUME_RAISE_NOTE = "raise:verification-fail:";
|
|
822
|
+
/** QA-G-B-1: the note of a resume that carries the `[acceptance]` block of the dispatch it resumes (appended to its prompt). */
|
|
823
|
+
export const CARRIED_ACCEPTANCE_NOTE = "acceptance carried from the resumed dispatch";
|
|
824
|
+
|
|
825
|
+
/** The higher of two tiers on `order` (unknown or null ones ignored); null when neither is on it. */
|
|
826
|
+
function higherTier(order: readonly string[], a: string | null, b: string | null): string | null {
|
|
827
|
+
const ia = a === null ? -1 : order.indexOf(a);
|
|
828
|
+
const ib = b === null ? -1 : order.indexOf(b);
|
|
829
|
+
if (ia < 0 && ib < 0) return a ?? b; // let tierBounds report an unknown floorTier as before
|
|
830
|
+
return ia >= ib ? a : b;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* QA-P21-2-1: the grant of a resume of an EXACTLY bound child: what the child holds (its bound grant) plus the actions widened for
|
|
835
|
+
* this resume. Only adds; `router_run` and `edit` stay withheld from a child bound without a work root (I9, QA-G-B-2). The work root
|
|
836
|
+
* is the bound one — QA-G-B N-b: a child bound without one keeps none, whatever root the resume's own route line names (the child
|
|
837
|
+
* cannot touch it: binding.ts holds its enforced grant), so the verification root, the outside-root check and the classification
|
|
838
|
+
* never use it.
|
|
839
|
+
*/
|
|
840
|
+
function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
|
|
841
|
+
const root = boundGrant.workRoot;
|
|
842
|
+
const actions = new Set<AuthorityAction>([...boundGrant.actions, ...widened]);
|
|
843
|
+
if (boundGrant.workRoot === null) {
|
|
844
|
+
// QA-G-B-2 (R7 null-root contract, I3): a child bound without a validated work root gets no run and no write, whatever root the
|
|
845
|
+
// resume's own route line names — as binding.ts `widen` (the enforced grant) refuses them.
|
|
846
|
+
actions.delete("router_run");
|
|
847
|
+
actions.delete("edit");
|
|
848
|
+
}
|
|
849
|
+
return { actions, notes: [...boundGrant.notes], workRoot: root };
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
/** verify/dod.ts `OPEN_TAG_RE` / `CLOSE_TAG_RE`: the lines that open and close an `[acceptance]` block. */
|
|
853
|
+
const ACCEPTANCE_OPEN_LINE = /^\s*\[(acceptance|dod)\]\s*$/i;
|
|
854
|
+
const ACCEPTANCE_CLOSE_LINE = /^\s*\[\/(acceptance|dod)\]\s*$/i;
|
|
855
|
+
/** A whole-line `VERIFY:` / `VERIFY_WAIT:` directive (verify/directives.ts). */
|
|
856
|
+
const VERIFY_DIRECTIVE_LINE = /^\s*VERIFY(?:_WAIT)?\s*:/i;
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* #84 QA-G-B-1: what a role dispatch's verification is built from — its first `[acceptance]` block, found as verify/dod.ts
|
|
860
|
+
* `parseAcceptanceBlock` finds it (verbatim lines; null without a closed block), and its whole-line `VERIFY:` / `VERIFY_WAIT:`
|
|
861
|
+
* directives outside that block.
|
|
862
|
+
*/
|
|
863
|
+
export function verificationParts(prompt: string): { readonly block: string | null; readonly directives: readonly string[] } {
|
|
864
|
+
const lines = prompt.split(/\r?\n/);
|
|
865
|
+
const open = lines.findIndex((line) => ACCEPTANCE_OPEN_LINE.test(line));
|
|
866
|
+
const close = open < 0 ? -1 : lines.findIndex((line, i) => i > open && ACCEPTANCE_CLOSE_LINE.test(line));
|
|
867
|
+
const inBlock = (i: number): boolean => close >= 0 && i >= open && i <= close;
|
|
868
|
+
return {
|
|
869
|
+
block: close < 0 ? null : lines.slice(open, close + 1).join("\n"),
|
|
870
|
+
directives: lines.flatMap((line, i) => (!inBlock(i) && VERIFY_DIRECTIVE_LINE.test(line) ? [line.trim()] : [])),
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** QA-G-B-2-1: the block has a check judged on the change set (testsPass, lintClean). Fails toward "it has". */
|
|
875
|
+
function carriedChecksChangeSet(block: string): boolean {
|
|
876
|
+
try {
|
|
877
|
+
return buildDelegationDoD({ prompt: block }).checks.some((check) => check.kind === "testsPass" || check.kind === "lintClean");
|
|
878
|
+
} catch {
|
|
879
|
+
return true;
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** QA-G-B-2-1: the reason a carried acceptance's testsPass/lintClean that ran no process is unverifiable (DeterministicDeps). */
|
|
884
|
+
export const CARRIED_NO_PROCESS_REASON =
|
|
885
|
+
"a carried acceptance re-checked no earlier change of the child: a check that runs no process verifies nothing here";
|
|
886
|
+
/** QA-G-B-2-1: the reference of a carried acceptance whose introducing attempt was never gated (no failure can be excused). */
|
|
887
|
+
export const CARRIED_NO_REFERENCE: ReferenceState = Object.freeze({
|
|
888
|
+
kind: "none" as const, reason: "the attempt that introduced this carried acceptance was not verified at its return",
|
|
889
|
+
});
|
|
890
|
+
/** Bound on the files a carried baseline keeps; beyond it the cumulative change set is "unavailable" (fails safe). */
|
|
891
|
+
export const MAX_CARRIED_CHANGES = 2000;
|
|
892
|
+
|
|
893
|
+
/** What a gate prepares for one attempt (`PreparedVerification` of verify/wiring.ts, structurally). */
|
|
894
|
+
export interface RoleAttemptChanges {
|
|
895
|
+
readonly changedFiles: ChangedFile[];
|
|
896
|
+
readonly changeBaseline: "available" | "unavailable";
|
|
897
|
+
readonly reference: ReferenceState;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** The union of two change sets, keyed by path (separators unified, case folded on win32); `newer` wins. */
|
|
901
|
+
function unionChanges(older: readonly ChangedFile[] | "unavailable", newer: readonly ChangedFile[] | "unavailable"): ChangedFile[] | "unavailable" {
|
|
902
|
+
if (older === "unavailable" || newer === "unavailable") return "unavailable";
|
|
903
|
+
const key = (path: string): string => (process.platform === "win32" ? path.replace(/\//g, "\\").toLowerCase() : path);
|
|
904
|
+
const all = new Map<string, ChangedFile>();
|
|
905
|
+
for (const file of [...older, ...newer]) all.set(key(file.path), { ...file });
|
|
906
|
+
return all.size > MAX_CARRIED_CHANGES ? "unavailable" : [...all.values()];
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* #84 QA-G-B-2-1: the change set and reference a role child's gate judges this attempt on, and the bookkeeping of its carried
|
|
911
|
+
* verification (the dispatch registry's `CarriedVerification.baseline`). Called by the after-hook once the attempt's own change
|
|
912
|
+
* set is prepared:
|
|
913
|
+
* - an attempt under its OWN block (a fresh dispatch, or a resume naming a new block) starts the lineage: its reference and change
|
|
914
|
+
* set become the baseline; it is judged on them, as before;
|
|
915
|
+
* - a CARRIED attempt (`carried`: the resume re-checks the block of an earlier attempt) is judged on the union of every change the
|
|
916
|
+
* child made since the attempt that introduced the block (and that attempt's reference: what it broke is never pre-existing);
|
|
917
|
+
* without such a baseline (that attempt was never gated) the change set is unavailable and no failure can be excused.
|
|
918
|
+
* Not a role child with an acceptance on record: `prepared` unchanged, nothing recorded.
|
|
919
|
+
*/
|
|
920
|
+
export function roleAttemptVerification<T extends RoleAttemptChanges>(childSessionID: string, prepared: T, opts: { readonly carried: boolean }): T {
|
|
921
|
+
const verification = lookupDispatch(childSessionID)?.verification;
|
|
922
|
+
if (verification === undefined) return prepared;
|
|
923
|
+
const own: readonly ChangedFile[] | "unavailable" = prepared.changeBaseline === "available" ? prepared.changedFiles : "unavailable";
|
|
924
|
+
if (!opts.carried) {
|
|
925
|
+
updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: prepared.reference, changed: own } });
|
|
926
|
+
return prepared;
|
|
927
|
+
}
|
|
928
|
+
const baseline = verification.baseline;
|
|
929
|
+
if (baseline === undefined) return { ...prepared, changeBaseline: "unavailable", reference: CARRIED_NO_REFERENCE };
|
|
930
|
+
const changed = unionChanges(baseline.changed, own);
|
|
931
|
+
updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: baseline.reference, changed } });
|
|
932
|
+
return {
|
|
933
|
+
...prepared,
|
|
934
|
+
changedFiles: changed === "unavailable" ? prepared.changedFiles : changed,
|
|
935
|
+
changeBaseline: changed === "unavailable" ? "unavailable" : "available",
|
|
936
|
+
reference: baseline.reference,
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* #84 QA-G-B-1 (I2, §2.3): the task facts a role RESUME is decided with. A resume prompt ("continue", "address the findings") is not
|
|
942
|
+
* the task: the class, confidence, source and needs come from the dispatch it resumes (the registry's record; its needs widened by
|
|
943
|
+
* the resume's own), and risk/scope are the max of that record and the resume's effective facts (its classification and route line,
|
|
944
|
+
* raise-only). Without a record the resume's own facts. Values outside the classifier's vocabularies fall back to the resume's.
|
|
945
|
+
*/
|
|
946
|
+
function resumeFactsOf(original: DispatchRecord["facts"] | undefined, current: TaskFacts): TaskFacts {
|
|
947
|
+
if (original === undefined) return current;
|
|
948
|
+
const member = <T extends string>(values: readonly T[], value: unknown): value is T => typeof value === "string" && (values as readonly string[]).includes(value);
|
|
949
|
+
const higher = <T extends string>(order: readonly T[], a: unknown, b: T): T => (member(order, a) && order.indexOf(a) > order.indexOf(b) ? a : b);
|
|
950
|
+
const needs = Array.isArray(original.needs) ? original.needs : [];
|
|
951
|
+
return {
|
|
952
|
+
class: member(TASK_CLASSES, original.class) ? original.class : current.class,
|
|
953
|
+
risk: higher(RISKS, original.risk, current.risk),
|
|
954
|
+
scope: higher(SCOPES, original.scope, current.scope),
|
|
955
|
+
needs: NEEDS.filter((need) => needs.includes(need) || current.needs.includes(need)),
|
|
956
|
+
confidence: typeof original.confidence === "number" && Number.isFinite(original.confidence) ? original.confidence : current.confidence,
|
|
957
|
+
source: member(FACT_SOURCES, original.source) ? original.source : current.source,
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
/**
|
|
962
|
+
* #84 QA-G-B-3 (2), a dynamic role's needs (fixed roles, and a dispatch without a route line, unchanged):
|
|
963
|
+
* - the route line names `needs=` → that list plus the route class's implied needs (`network` ⇒ `shell`) are authoritative;
|
|
964
|
+
* - the route line names only `class=` → the needs the text itself names (`textNeeds`, never a class's implied ones) plus the
|
|
965
|
+
* route class's implied needs: the class the route line replaced takes its implied needs with it (DF-2: "a new file" made the
|
|
966
|
+
* rules class `implement`, whose `edit` outlived `class=other`).
|
|
967
|
+
* The result is intersected with `facts.needs`, which already holds the route line's needs (`applyRouteLine` merges them
|
|
968
|
+
* first, with the route class's implied needs): so a `needs=` list REPLACES the needs the text implies — a listed need the text
|
|
969
|
+
* never names is kept (QA-G-C-2-1), the text's other needs are dropped. Only the role max bounds the grant (`grantFor`).
|
|
970
|
+
*/
|
|
971
|
+
function roleNeedsOf(facts: TaskFacts, line: RouteLine | null, spec: RoleSpec, textNeeds: ReadonlySet<Need>): TaskFacts {
|
|
972
|
+
if (spec.authority.mode === "fixed" || line === null || (line.needs === undefined && line.class === undefined)) return facts;
|
|
973
|
+
const keep = new Set<Need>([...(line.needs ?? textNeeds), ...CLASS_IMPLIED_NEEDS[facts.class]]);
|
|
974
|
+
if (keep.has("network")) keep.add("shell");
|
|
975
|
+
const needs = NEEDS.filter((need) => keep.has(need) && facts.needs.includes(need));
|
|
976
|
+
return needs.length === facts.needs.length ? facts : { ...facts, needs };
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/** QA-P21-1-1: the note of a delegate's role dispatch (unparsed, floor rung of the unknown-binding window). */
|
|
980
|
+
export const DELEGATE_DISPATCH_NOTE =
|
|
981
|
+
"delegate dispatch: the prompt is not routed (a delegate never pins or steers); the floor rung of the role's local-only window is dispatched";
|
|
982
|
+
/** QA-P21-1-5: the reason code of a route-line pin that wins over an explicit caller `model`. */
|
|
983
|
+
export const PIN_OVER_CALLER_REASON = "pin:over-caller-model";
|
|
984
|
+
/** QA-P21-1-6: no window rung present in the host catalog at or above the floor (the role dispatch is refused). */
|
|
985
|
+
export const VARIANT_NO_CANDIDATE_REASON = "variant:no-catalog-candidate";
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* QA-P21-1-6: what is dispatched for the picked rung given the host catalog. Its variant exists (or the catalog does not know the
|
|
989
|
+
* model) → the rung as is. Otherwise the bare model, at its OWN capability rank (`capabilityRank(ladder, { model, variant: null })`),
|
|
990
|
+
* when that rank reaches the window floor; else the next window rung present in the catalog at or above the floor; `null` when
|
|
991
|
+
* there is none (the caller refuses).
|
|
992
|
+
*/
|
|
993
|
+
function placeInCatalog(
|
|
994
|
+
ladder: RoleLadder,
|
|
995
|
+
picked: Candidate,
|
|
996
|
+
catalog: RolePrepared["catalog"],
|
|
997
|
+
): { readonly candidate: Candidate; readonly variant: string | null; readonly dropped: string | null } | null {
|
|
998
|
+
const variantOf = (c: Pick<Candidate, "variant">): string | null => (normalizeVariant(c.variant) === "default" ? null : normalizeVariant(c.variant));
|
|
999
|
+
const present = (c: Candidate): boolean => {
|
|
1000
|
+
const v = variantOf(c);
|
|
1001
|
+
if (v === null) return true;
|
|
1002
|
+
const ids = catalogVariantIds(catalog, c.model);
|
|
1003
|
+
return ids === null || ids.includes(v);
|
|
1004
|
+
};
|
|
1005
|
+
if (present(picked)) return { candidate: picked, variant: variantOf(picked), dropped: null };
|
|
1006
|
+
const wanted = variantOf(picked);
|
|
1007
|
+
const floorRank = ladder.floorRank;
|
|
1008
|
+
const bareRank = capabilityRank(ladder, { model: picked.model, variant: null }, null);
|
|
1009
|
+
if (bareRank !== null && (floorRank === null || bareRank >= floorRank)) {
|
|
1010
|
+
return {
|
|
1011
|
+
candidate: { ...picked, variant: null, rank: bareRank },
|
|
1012
|
+
variant: null,
|
|
1013
|
+
dropped: `variant ${wanted} of ${picked.model} is not in the host catalog: dispatched on the tier model without a variant (capability rank ${bareRank})`,
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
const at = ladder.candidates.indexOf(picked);
|
|
1017
|
+
const next = ladder.candidates.slice(at < 0 ? 0 : at + 1).find((c) => present(c) && (floorRank === null || c.rank >= floorRank));
|
|
1018
|
+
if (next === undefined) return null;
|
|
1019
|
+
return {
|
|
1020
|
+
candidate: next,
|
|
1021
|
+
variant: variantOf(next),
|
|
1022
|
+
dropped: `variant ${wanted} of ${picked.model} is not in the host catalog and the bare model ranks below the window floor: dispatched on ${refOf(next.model, variantOf(next))}`,
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/** Test-only: forget which calls were handled. */
|
|
1027
|
+
export function resetDispatchRouting(): void {
|
|
1028
|
+
handledCalls.clear();
|
|
1029
|
+
subagentAnnotations.clear();
|
|
1030
|
+
routedRoles.clear();
|
|
1031
|
+
strippedRoots.clear();
|
|
1032
|
+
resumeRaises.clear();
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
1036
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
function describeError(error: unknown): string {
|
|
1040
|
+
return error instanceof Error ? error.message : String(error);
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
function str(value: unknown): string | null {
|
|
1044
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** The child session a finished `subagent` call names (`result.output.sessionID`, else `result.metadata.sessionID`; spike S1). */
|
|
1048
|
+
export function childSessionOf(result: unknown): string | null {
|
|
1049
|
+
if (!isRecord(result)) return null;
|
|
1050
|
+
const output = result.output;
|
|
1051
|
+
const fromOutput = isRecord(output) ? str(output.sessionID) : null;
|
|
1052
|
+
if (fromOutput !== null) return fromOutput;
|
|
1053
|
+
return isRecord(result.metadata) ? str(result.metadata.sessionID) : null;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
interface SessionView {
|
|
1057
|
+
readonly parentID: string | null;
|
|
1058
|
+
readonly agent: string | null;
|
|
1059
|
+
readonly model: string | null;
|
|
1060
|
+
readonly directory: string | null;
|
|
1061
|
+
readonly rules: ReturnType<typeof sessionRulesOf>;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
function readSession(raw: unknown): SessionView {
|
|
1065
|
+
const session = isRecord(raw) ? raw : {};
|
|
1066
|
+
const location = isRecord(session.location) ? session.location : {};
|
|
1067
|
+
return {
|
|
1068
|
+
parentID: str(session.parentID),
|
|
1069
|
+
agent: str(session.agent),
|
|
1070
|
+
model: agentModelRef(session.model),
|
|
1071
|
+
directory: str(location.directory),
|
|
1072
|
+
rules: sessionRulesOf(session),
|
|
1073
|
+
};
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** The row's `facts` (1.3's structural view of `TaskFacts`). */
|
|
1077
|
+
function factsOf(facts: TaskFacts): DecisionRow["facts"] {
|
|
1078
|
+
return { class: facts.class, risk: facts.risk, scope: facts.scope, needs: [...facts.needs], confidence: facts.confidence, source: facts.source };
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTrace {
|
|
1082
|
+
const { routeLines, backend, backendSkipped } = result.trace;
|
|
1083
|
+
return {
|
|
1084
|
+
routeLines: { count: routeLines.count, conflict: routeLines.conflict, edgeOnly: routeLines.edgeOnly },
|
|
1085
|
+
backend: backend === null
|
|
1086
|
+
? null
|
|
1087
|
+
: {
|
|
1088
|
+
id: backend.id,
|
|
1089
|
+
status: backend.status,
|
|
1090
|
+
latencyMs: backend.latencyMs,
|
|
1091
|
+
...(backend.label === undefined ? {} : { label: backend.label }),
|
|
1092
|
+
...(backend.rejected === true ? { rejected: true as const } : {}),
|
|
1093
|
+
...(backend.disagrees === true ? { disagrees: true as const } : {}),
|
|
1094
|
+
},
|
|
1095
|
+
...(backendSkipped === undefined ? {} : { backendSkipped }),
|
|
1096
|
+
...(argmin === null ? {} : { argmin }),
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function choiceOf(cls: string, dispatch: ChosenDispatch): RouteChoice {
|
|
1101
|
+
const key = candidateKey(cls, dispatch);
|
|
1102
|
+
return { key, agent: dispatch.agent.id, origin: dispatch.agent.origin, model: dispatch.model, variant: normalizeVariant(dispatch.variant) };
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/** `provider/model[#variant]`. */
|
|
1106
|
+
function refOf(model: string, variant: string | null): string {
|
|
1107
|
+
return variant === null || variant === "" || variant === "default" ? model : `${model}#${variant}`;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
function depthOf(detection: string): DetectionDepth {
|
|
1111
|
+
return detection === "deterministic" || detection === "grader" ? detection : "none";
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/**
|
|
1115
|
+
* The row's reason for the kernel's decision: its reason CODE, then the kernel's text without the leading word the text carries itself
|
|
1116
|
+
* (`kept: …`, `switched: …`), so a row reads `switched: C(best)=…` and `kept:best-is-chosen: the chosen dispatch …`, not `switched: switched: …` /
|
|
1117
|
+
* `kept:best-is-chosen: kept: …` (QA-3.2-12). The code stays the first token: `routing:stats` reads `kept:evidence` and `lift:floor` by prefix.
|
|
1118
|
+
*/
|
|
1119
|
+
function reasonText(decision: Pick<Decision, "reasonCode" | "reason">): string {
|
|
1120
|
+
return `${decision.reasonCode}: ${decision.reason.replace(/^(?:kept|switched): /, "")}`;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** A pick the engine cannot resolve to a model: logged as kept, never priced (1.4 handoff). */
|
|
1124
|
+
function unresolvedChoice(cls: string, agent: string, routerIds: readonly string[]): RouteChoice {
|
|
1125
|
+
const origin = classifyAgentOrigin(agent, routerIds);
|
|
1126
|
+
return { key: makeKey(cls, { origin, id: agent }, "", "", null), agent, origin, model: "unknown/unknown", variant: "default" };
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
/** What the host runs for a committed call: agent, `provider/model` and variant. */
|
|
1130
|
+
interface RanDispatch {
|
|
1131
|
+
readonly agent: string;
|
|
1132
|
+
readonly model: string;
|
|
1133
|
+
readonly variant: string | null;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/** Same `provider/model` (a `#variant` suffix split off) and the same normalized variant. */
|
|
1137
|
+
function sameModelVariant(a: { readonly model: string; readonly variant: string | null }, b: { readonly model: string; readonly variant: string | null }): boolean {
|
|
1138
|
+
const left = splitModelRef(a.model);
|
|
1139
|
+
const right = splitModelRef(b.model);
|
|
1140
|
+
const modelOf = (ref: ReturnType<typeof splitModelRef>, raw: string): string => (ref === null ? raw : `${ref.provider}/${ref.model}`);
|
|
1141
|
+
return modelOf(left, a.model) === modelOf(right, b.model)
|
|
1142
|
+
&& normalizeVariant(a.variant ?? left?.variant ?? null) === normalizeVariant(b.variant ?? right?.variant ?? null);
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* What the host will run for a committed call: the final input's agent and `model` win over what the engine decided (the legacy hook
|
|
1147
|
+
* runs after the engine); a model the final input leaves out is the engine's (same agent) or the resolved one (another agent). `null`
|
|
1148
|
+
* when it cannot be told (an unparseable `model`, an agent that resolves to no model).
|
|
1149
|
+
*/
|
|
1150
|
+
function ranOf(
|
|
1151
|
+
d: Pick<Decided, "resolve">,
|
|
1152
|
+
decidedFinal: NonNullable<Decided["final"]>,
|
|
1153
|
+
final: Readonly<Record<string, unknown>>,
|
|
1154
|
+
): RanDispatch | null {
|
|
1155
|
+
const agent = str(final.agent) ?? decidedFinal.agent;
|
|
1156
|
+
const ref = str(final.model);
|
|
1157
|
+
if (ref !== null) {
|
|
1158
|
+
const parts = splitModelRef(ref);
|
|
1159
|
+
return parts === null ? null : { agent, model: `${parts.provider}/${parts.model}`, variant: parts.variant };
|
|
1160
|
+
}
|
|
1161
|
+
if (agent === decidedFinal.agent) return { agent, model: decidedFinal.model, variant: decidedFinal.variant };
|
|
1162
|
+
const resolved = d.resolve(agent);
|
|
1163
|
+
return resolved === null ? null : { agent, model: resolved.model, variant: resolved.variant };
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
1167
|
+
const now = deps.now ?? (() => Date.now());
|
|
1168
|
+
const instanceNonce = randomBytes(8).toString("hex");
|
|
1169
|
+
/** Between `route()` and `commit()`. */
|
|
1170
|
+
const decided = new Map<string, Decided>();
|
|
1171
|
+
/** Committed dispatches, in insertion order, until their call ends. */
|
|
1172
|
+
const entries = new Map<string, Entry>();
|
|
1173
|
+
/**
|
|
1174
|
+
* QA-2.2-R2-7: children registered under a dispatch by a heuristic claim that the dispatch's own result then disowned (child →
|
|
1175
|
+
* the wrong dispatch's decision). They stay registered (their steps keep being counted, under the wrong facts) until the
|
|
1176
|
+
* result of the dispatch that really started them takes them over.
|
|
1177
|
+
*/
|
|
1178
|
+
const misclaimed = new Map<string, string>();
|
|
1179
|
+
/** QA-P21-1-11: role children whose observed binding has been recorded (once per child; bounded). */
|
|
1180
|
+
const notedBindings = new Set<string>();
|
|
1181
|
+
let sequence = 0;
|
|
1182
|
+
|
|
1183
|
+
const trim = <T>(map: Map<string, T>, limit: number): void => {
|
|
1184
|
+
while (map.size > limit) map.delete(map.keys().next().value as string);
|
|
1185
|
+
};
|
|
1186
|
+
|
|
1187
|
+
const sweep = (t: number): void => {
|
|
1188
|
+
for (const [callID, entry] of entries) {
|
|
1189
|
+
if (t - entry.at >= ENTRY_TTL_MS) entries.delete(callID);
|
|
1190
|
+
}
|
|
1191
|
+
trim(entries, MAX_PENDING);
|
|
1192
|
+
};
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* QA-2.2-R2-1: the call of a resume ended without a result (the host rejected it after the hooks ran). Its registration was
|
|
1196
|
+
* made for an execution that never started: drop it, and put back what the registry held for the child before, so a live
|
|
1197
|
+
* child keeps its facts and its attempt id (what the registry had observed of the execution cannot be restored).
|
|
1198
|
+
*/
|
|
1199
|
+
const undoResume = (entry: Entry): void => {
|
|
1200
|
+
if (entry.state !== "resumed" || entry.resumeID === undefined) return;
|
|
1201
|
+
if (lookupDispatch(entry.resumeID)?.decisionID !== entry.input.decisionID) return; // someone registered it since: theirs
|
|
1202
|
+
const before = entry.previous;
|
|
1203
|
+
if (before === undefined) {
|
|
1204
|
+
forgetDispatch(entry.resumeID);
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
register(entry.resumeID, {
|
|
1208
|
+
facts: before.facts, agent: before.agent, model: before.model, variant: before.variant, tier: before.tier, acceptance: before.acceptance,
|
|
1209
|
+
parentSessionID: before.parentSessionID, attemptId: before.attemptId, decisionID: before.decisionID, step: before.step,
|
|
1210
|
+
outcomes: before.outcomes, picked: before.picked, keepExecution: true,
|
|
1211
|
+
...(before.verification === undefined ? {} : { verification: before.verification }),
|
|
1212
|
+
});
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
const claimable = (entry: Entry, t: number): boolean => entry.state === "waiting" && t - entry.at < PENDING_TTL_MS;
|
|
1216
|
+
|
|
1217
|
+
const register = (childSessionID: string, input: DispatchInput): void => {
|
|
1218
|
+
try {
|
|
1219
|
+
rememberDispatch(childSessionID, input, now());
|
|
1220
|
+
} catch (error) {
|
|
1221
|
+
deps.logger.warn("[router] routing: the dispatch could not be registered for ingestion", { error: describeError(error) });
|
|
1222
|
+
}
|
|
1223
|
+
};
|
|
1224
|
+
|
|
1225
|
+
/**
|
|
1226
|
+
* The orchestrator's pick lifted to `floorTier` (handoff 1.4, QA-1.4-17): `enforce` starts the dispatch on
|
|
1227
|
+
* `max(pick, floor)`, so the row prices what runs. Only router tiers have a rank; a host agent is never lifted. The floor
|
|
1228
|
+
* tier must be startable by the parent AND cover the task's needs (QA-2.2-7): a lift must not send a shell task to an
|
|
1229
|
+
* agent without a shell.
|
|
1230
|
+
*/
|
|
1231
|
+
const floorLift = (prepared: Prepared, chosen: ChosenDispatch, infos: readonly HostAgentInfo[] | null, facts: TaskFacts): ChosenDispatch | null => {
|
|
1232
|
+
const floorRank = floorRankOf(prepared.cfg);
|
|
1233
|
+
if (floorRank === null || chosen.agent.origin !== "router") return null;
|
|
1234
|
+
const rank = tierRankOf(prepared.cfg, chosen.agent.id);
|
|
1235
|
+
if (rank === null || rank >= floorRank) return null;
|
|
1236
|
+
const floorTier = escalateLadder(prepared.cfg)[floorRank];
|
|
1237
|
+
if (floorTier === undefined) return null;
|
|
1238
|
+
const lifted = resolveChosen({ cfg: prepared.cfg, agents: infos, agent: floorTier });
|
|
1239
|
+
const info = infos?.find((agent) => agent.id === floorTier);
|
|
1240
|
+
if (lifted === null || info === undefined) return null;
|
|
1241
|
+
if (!info.permitted || info.mode === "primary" || info.hidden) return null;
|
|
1242
|
+
return coversNeeds(info.grants, facts.needs) ? lifted : null;
|
|
1243
|
+
};
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* A30 as amended (QA-2.4-R3-1): the host switches a resumed child to the agent the resume NAMES when it differs from the one the child
|
|
1247
|
+
* runs (`switchAgent` in the host's subagent tool: the child's model becomes that agent's). An orchestrator that resumes a child
|
|
1248
|
+
* with its own original pick of a child the router moved (floor lift, evidence switch) would move it back below where the router put
|
|
1249
|
+
* it. What the child runs, when that is the case: the resume names the pick the child was dispatched under, the child runs another
|
|
1250
|
+
* agent, and it is this orchestrator's child.
|
|
1251
|
+
*/
|
|
1252
|
+
const runningAfterRouter = (resumeID: string, parentSessionID: string, named: string): { agent: string; model: string; variant: string | null } | null => {
|
|
1253
|
+
const record = lookupDispatch(resumeID);
|
|
1254
|
+
if (record === undefined || record.parentSessionID !== parentSessionID) return null;
|
|
1255
|
+
if (record.picked === null || record.picked !== named || record.agent === named || record.model === null) return null;
|
|
1256
|
+
return { agent: record.agent, model: record.model, variant: record.variant };
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
/**
|
|
1260
|
+
* A34 (QA-G-B3): may the A30 rewrite send this resume to the agent the child runs? Only when that agent is still startable by the
|
|
1261
|
+
* parent and its EVALUATED permissions cover the resume's own `needs` (A11: the resume may ask for more than the first dispatch did),
|
|
1262
|
+
* and, on high-risk work without detection (D9 never-down), when it is not below the named pick's capability rank — nor the pick's own
|
|
1263
|
+
* model on a lower variant at that rank. Unknown agent info or an unknown capability is a refusal: the resume is then sent as named,
|
|
1264
|
+
* which is the orchestrator's own pick and so never a move down. `null` = the rewrite is allowed.
|
|
1265
|
+
*/
|
|
1266
|
+
const runningRefusal = (
|
|
1267
|
+
running: { readonly agent: string; readonly model: string; readonly variant: string | null },
|
|
1268
|
+
named: ChosenDispatch,
|
|
1269
|
+
namedRank: number | null,
|
|
1270
|
+
ladder: Ladder,
|
|
1271
|
+
infos: readonly HostAgentInfo[] | null,
|
|
1272
|
+
facts: TaskFacts,
|
|
1273
|
+
detection: Detection,
|
|
1274
|
+
): "needs" | "never-down" | null => {
|
|
1275
|
+
const info = infos?.find((candidate) => candidate.id === running.agent);
|
|
1276
|
+
if (info === undefined || !info.permitted || info.mode === "primary" || info.hidden || !coversNeeds(info.grants, facts.needs)) return "needs";
|
|
1277
|
+
if (facts.risk !== "high" || detection !== "none") return null;
|
|
1278
|
+
const pickRank = capabilityRank(ladder, named, namedRank);
|
|
1279
|
+
const runRank = capabilityRank(ladder, running, null);
|
|
1280
|
+
if (pickRank === null || runRank === null || runRank < pickRank) return "never-down";
|
|
1281
|
+
return runRank === pickRank && lowerEffortOnSameModel(running, named) ? "never-down" : null;
|
|
1282
|
+
};
|
|
1283
|
+
|
|
1284
|
+
const decideAndRecord = async (call: RouteCall, prepared: Prepared, session: SessionView, view: AgentView | null): Promise<RouteOutcome> => {
|
|
1285
|
+
const { args } = call;
|
|
1286
|
+
const agent = str(args.agent);
|
|
1287
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : null;
|
|
1288
|
+
if (agent === null || prompt === null) return UNTOUCHED;
|
|
1289
|
+
const mode = prepared.settings.engine;
|
|
1290
|
+
const infos = view === null ? null : view.infos;
|
|
1291
|
+
const routerIds = routerTierIds(prepared.cfg);
|
|
1292
|
+
|
|
1293
|
+
const result = await classify(
|
|
1294
|
+
{ description: typeof args.description === "string" ? args.description : "", prompt, cwd: session.directory ?? deps.directory },
|
|
1295
|
+
deps.runtime.classifyDeps(prepared),
|
|
1296
|
+
);
|
|
1297
|
+
const facts = result.facts;
|
|
1298
|
+
// A34 (QA-G-B2): the weaker of the route line's `d=` claim and the prompt's own `[acceptance]` block. Detection is the only
|
|
1299
|
+
// field a route line could use to WEAKEN a safety rule (D9 never-down holds for `d == none`), so a claim never raises it.
|
|
1300
|
+
const detection = weakerDetection(result.detection, detectionOf(prompt));
|
|
1301
|
+
const pin = result.pin;
|
|
1302
|
+
// `classify` removes only the first-line route line and returns every other byte unchanged (probe, QA-2.2-5).
|
|
1303
|
+
const stripped = result.stripped !== prompt ? result.stripped : undefined;
|
|
1304
|
+
const strippedRoot = stripped === undefined ? undefined : result.trace.routeLine?.root;
|
|
1305
|
+
if (typeof strippedRoot === "string" && strippedRoot !== "") rememberStrippedRoot(call.callID, strippedRoot);
|
|
1306
|
+
const callModel = str(args.model) ?? call.tierModel ?? null;
|
|
1307
|
+
const resumeID = str(args.sessionID);
|
|
1308
|
+
const decisionID = `${call.sessionID}:${safeNow(now)}:${instanceNonce}:${++sequence}`;
|
|
1309
|
+
|
|
1310
|
+
const chosen = resolveChosen({ cfg: prepared.cfg, agents: infos, agent, model: callModel, parentModel: session.model });
|
|
1311
|
+
let decision: Decision | null = null;
|
|
1312
|
+
let argmin: RouteChoice | null = null; // A27: the cheapest option the evidence filter removed, when it did
|
|
1313
|
+
let row: Pick<DecisionRow, "chosen" | "best" | "switched" | "pinned" | "unit" | "costs" | "confidence" | "reason">;
|
|
1314
|
+
let final: { agent: string; model: string; variant: string | null } | null = null;
|
|
1315
|
+
let outcome: RouteOutcome = { mode, ...(stripped === undefined ? {} : { prompt: stripped }), decisionID };
|
|
1316
|
+
// A34 (QA-G-B8): the pick's capability rank for the row, and how to rank what the host is finally handed (at `commit`).
|
|
1317
|
+
let pickCapability: number | null = null;
|
|
1318
|
+
let capabilityOf: (ran: RanDispatch) => number | null = () => null;
|
|
1319
|
+
|
|
1320
|
+
if (chosen === null) {
|
|
1321
|
+
row = {
|
|
1322
|
+
chosen: unresolvedChoice(facts.class, agent, routerIds),
|
|
1323
|
+
best: null, switched: false, pinned: pin, unit: "ratio", costs: {}, confidence: 0,
|
|
1324
|
+
reason: "kept:unresolved: the dispatched agent resolves to no model, so nothing could be priced",
|
|
1325
|
+
};
|
|
1326
|
+
} else {
|
|
1327
|
+
const ladder = buildLadder({
|
|
1328
|
+
cfg: prepared.cfg,
|
|
1329
|
+
routing: prepared.routing,
|
|
1330
|
+
facts,
|
|
1331
|
+
agents: infos,
|
|
1332
|
+
pricing: (model) => prepared.catalog.pricing(model),
|
|
1333
|
+
parentModel: session.model,
|
|
1334
|
+
logger: deps.logger,
|
|
1335
|
+
session: prepared.session,
|
|
1336
|
+
});
|
|
1337
|
+
decision = decide({
|
|
1338
|
+
facts, chosen, ladder, detection, pin, routing: prepared.routing, store: prepared.store, floorRank: floorRankOf(prepared.cfg),
|
|
1339
|
+
});
|
|
1340
|
+
argmin = decision.argmin !== null && decision.argmin.key !== decision.best?.key ? decision.argmin : null;
|
|
1341
|
+
const pickRank = decision.pickRank ?? capabilityRank(ladder, chosen, null);
|
|
1342
|
+
pickCapability = pickRank;
|
|
1343
|
+
capabilityOf = (ran) => {
|
|
1344
|
+
// The pick itself ranks as the pick (its candidate rank included); anything else by its model, never below its candidate rank.
|
|
1345
|
+
if (ran.agent === agent && sameModelVariant(ran, chosen)) return pickRank;
|
|
1346
|
+
const candidate = ladder.candidates.find((c) => c.agent.id === ran.agent && sameModelVariant(c, ran));
|
|
1347
|
+
return capabilityRank(ladder, ran, candidate?.rank ?? null);
|
|
1348
|
+
};
|
|
1349
|
+
// A30 (QA-2.4-R2-3): a dispatch that resumes an existing child (`task_id`/`sessionID`) is never switched by the engine, in any mode:
|
|
1350
|
+
// the kernel's decision is still logged (best, costs, its own reason), but `switched` is false and the reason code is `kept:resume`.
|
|
1351
|
+
const resuming = resumeID !== null;
|
|
1352
|
+
// QA-2.4-R3-1 (A30 amended): the router never moves a child from where it runs. A resume that repeats the orchestrator's original
|
|
1353
|
+
// pick of a child the router moved is sent to the agent/model the child runs (`enforce`; the other modes only say so in the row).
|
|
1354
|
+
const moved = resumeID === null ? null : runningAfterRouter(resumeID, call.sessionID, agent);
|
|
1355
|
+
// A34 (QA-G-B3): the rewrite must neither send the resume to an agent that cannot do the resumed work (needs, permission) nor move
|
|
1356
|
+
// it below the named pick on high-risk work without detection (D9 never-down). Refused: the resume is sent as named (and floor-lifted).
|
|
1357
|
+
const refusal = moved === null || decision.pinned
|
|
1358
|
+
? null
|
|
1359
|
+
: runningRefusal(moved, chosen, decision.pickRank, ladder, infos, facts, detection);
|
|
1360
|
+
const running = refusal === null ? moved : null;
|
|
1361
|
+
row = {
|
|
1362
|
+
chosen: decision.chosen, best: decision.best, switched: resuming ? false : decision.switched, pinned: decision.pinned,
|
|
1363
|
+
unit: decision.unit, costs: { ...decision.costs }, confidence: decision.confidence,
|
|
1364
|
+
reason: moved !== null
|
|
1365
|
+
? decision.pinned
|
|
1366
|
+
// A pinned resume is sent as named (`kept:resume:pinned`): it was NOT rewritten, so the row must not claim it was.
|
|
1367
|
+
? `${RESUME_PINNED_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; pinned, so it is sent as named and NOT rewritten (the host moves the child to @${agent}); engine decision: ${reasonText(decision)}`
|
|
1368
|
+
: refusal === "needs"
|
|
1369
|
+
? `${RESUME_NAMED_NEEDS_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; @${moved.agent} is not startable or its permissions do not cover needs [${facts.needs.join(",")}], so it is sent as named and NOT rewritten (the host moves the child to @${agent}) (A34); engine decision: ${reasonText(decision)}`
|
|
1370
|
+
: refusal === "never-down"
|
|
1371
|
+
? `${RESUME_NAMED_NEVER_DOWN_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; @${moved.agent} is below the pick's capability on high-risk work without detection (D9 never down), so it is sent as named and NOT rewritten (the host moves the child to @${agent}) (A34); engine decision: ${reasonText(decision)}`
|
|
1372
|
+
: `${RESUME_RUNNING_REASON}: the resume names @${agent}, the orchestrator's own pick for a child the router moved to @${moved.agent}; ${mode === "enforce" ? "sent to @" + moved.agent + " so the host does not switch it back (A30)" : "would be sent to @" + moved.agent + " (not applied in " + mode + ") so the host does not switch it back (A30)"}; engine decision: ${reasonText(decision)}`
|
|
1373
|
+
: resuming
|
|
1374
|
+
? `${RESUME_REASON}: a dispatch that resumes an existing child is never switched by the engine (A30); engine decision: ${reasonText(decision)}`
|
|
1375
|
+
: reasonText(decision),
|
|
1376
|
+
};
|
|
1377
|
+
final = { agent, model: chosen.model, variant: chosen.variant };
|
|
1378
|
+
|
|
1379
|
+
if (mode === "enforce" && !decision.pinned && running !== null) {
|
|
1380
|
+
outcome = { ...outcome, agent: running.agent, model: refOf(running.model, running.variant) };
|
|
1381
|
+
final = { agent: running.agent, model: running.model, variant: running.variant };
|
|
1382
|
+
} else if (mode === "enforce" && !decision.pinned && resuming) {
|
|
1383
|
+
// A resume naming an agent other than the one the child runs, and other than the pick it was dispatched under, is the
|
|
1384
|
+
// orchestrator's choice: honoured, never below the floor. Without a record of the child nothing is known to move.
|
|
1385
|
+
const record = lookupDispatch(resumeID);
|
|
1386
|
+
const lifted = record !== undefined && record.parentSessionID === call.sessionID && record.agent !== agent ? floorLift(prepared, chosen, infos, facts) : null;
|
|
1387
|
+
if (lifted !== null) {
|
|
1388
|
+
outcome = { ...outcome, agent: lifted.agent.id, model: refOf(lifted.model, lifted.variant) };
|
|
1389
|
+
final = { agent: lifted.agent.id, model: lifted.model, variant: lifted.variant };
|
|
1390
|
+
row = {
|
|
1391
|
+
...row,
|
|
1392
|
+
best: choiceOf(facts.class, lifted),
|
|
1393
|
+
switched: true,
|
|
1394
|
+
reason: `${FLOOR_LIFT_REASON}: resume lifted from @${agent} to @${lifted.agent.id} by enforcement.escalate.floorTier (the child runs @${record?.agent ?? "?"}); engine decision: ${row.reason}`,
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
} else if (mode === "enforce" && !decision.pinned) {
|
|
1398
|
+
if (decision.switched && decision.target !== null) {
|
|
1399
|
+
const target = decision.target;
|
|
1400
|
+
outcome = { ...outcome, agent: target.agent.id, model: refOf(target.model, target.variant) };
|
|
1401
|
+
final = { agent: target.agent.id, model: target.model, variant: target.variant };
|
|
1402
|
+
} else {
|
|
1403
|
+
const lifted = floorLift(prepared, chosen, infos, facts);
|
|
1404
|
+
if (lifted !== null) {
|
|
1405
|
+
outcome = { ...outcome, agent: lifted.agent.id, model: refOf(lifted.model, lifted.variant) };
|
|
1406
|
+
final = { agent: lifted.agent.id, model: lifted.model, variant: lifted.variant };
|
|
1407
|
+
row = {
|
|
1408
|
+
...row,
|
|
1409
|
+
best: choiceOf(facts.class, lifted),
|
|
1410
|
+
switched: true,
|
|
1411
|
+
// Its own reason code (QA-2.2-7): a floor lift is policy, not an evidence-based switch; D17 does not count it.
|
|
1412
|
+
reason: `${FLOOR_LIFT_REASON}: dispatch lifted from @${agent} to @${lifted.agent.id} by enforcement.escalate.floorTier; engine decision: ${row.reason}`,
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
const decisionRow: DecisionRow = {
|
|
1420
|
+
v: LOG_ROW_VERSION,
|
|
1421
|
+
ts: new Date(safeNow(now)).toISOString(),
|
|
1422
|
+
sessionID: call.sessionID,
|
|
1423
|
+
kind: "decision",
|
|
1424
|
+
decisionID,
|
|
1425
|
+
mode,
|
|
1426
|
+
childSessionID: resumeID,
|
|
1427
|
+
facts: factsOf(facts),
|
|
1428
|
+
...row,
|
|
1429
|
+
step: "dispatch",
|
|
1430
|
+
resume: resumeID !== null,
|
|
1431
|
+
trace: traceOf(result, argmin),
|
|
1432
|
+
// A34 (QA-G-B8): the detection decided with, and the route line's claim when the prompt did not back it.
|
|
1433
|
+
detection: {
|
|
1434
|
+
effective: detection,
|
|
1435
|
+
...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
|
|
1436
|
+
},
|
|
1437
|
+
capability: { pick: pickCapability, dispatched: null }, // `dispatched` is filled in by `commit()` from the final input
|
|
1438
|
+
};
|
|
1439
|
+
|
|
1440
|
+
// QA-G-A2: the row waits for `commit()`, so a call whose hook chain rejects it (`onCallFinished`) never writes one.
|
|
1441
|
+
decided.set(call.callID, {
|
|
1442
|
+
parentSessionID: call.sessionID,
|
|
1443
|
+
decisionID,
|
|
1444
|
+
facts: factsOf(facts),
|
|
1445
|
+
acceptance: depthOf(detection),
|
|
1446
|
+
description: typeof args.description === "string" && args.description !== "" ? args.description : null,
|
|
1447
|
+
row: decisionRow,
|
|
1448
|
+
enqueue: (logged) => prepared.enqueue(logged),
|
|
1449
|
+
capabilityOf,
|
|
1450
|
+
final,
|
|
1451
|
+
routerIds,
|
|
1452
|
+
resolve: (target) => resolveChosen({ cfg: prepared.cfg, agents: infos, agent: target, parentModel: session.model }),
|
|
1453
|
+
picked: agent,
|
|
1454
|
+
at: now(),
|
|
1455
|
+
});
|
|
1456
|
+
trim(decided, MAX_PENDING);
|
|
1457
|
+
return outcome;
|
|
1458
|
+
};
|
|
1459
|
+
|
|
1460
|
+
// -------------------------------------------------------------------------
|
|
1461
|
+
// #84 P2.1 (T2.1.2): the role path. Tier dispatches never reach it (I1).
|
|
1462
|
+
// -------------------------------------------------------------------------
|
|
1463
|
+
|
|
1464
|
+
const workRootDeps: WorkRootDeps = {
|
|
1465
|
+
listWorktrees: deps.listWorktrees ?? gitWorktreeList,
|
|
1466
|
+
realpath: deps.realpath ?? ((path: string) => realpathSync.native(path)),
|
|
1467
|
+
platform: deps.platform ?? process.platform,
|
|
1468
|
+
};
|
|
1469
|
+
|
|
1470
|
+
/**
|
|
1471
|
+
* The rung a resumed child runs on: the dispatch registry's record (its `tier` is the role tier the router registered), else the
|
|
1472
|
+
* child session's own model; unknown → a model off every ladder, which the kernel lifts to the window ceiling (never below).
|
|
1473
|
+
*/
|
|
1474
|
+
const runningRungOf = async (resumeID: string): Promise<{ tier: string | null; model: string; variant: string | null }> => {
|
|
1475
|
+
const record = lookupDispatch(resumeID);
|
|
1476
|
+
if (record !== undefined && record.model !== null) return { tier: record.tier ?? null, model: record.model, variant: record.variant ?? null };
|
|
1477
|
+
try {
|
|
1478
|
+
const ref = readSession(await deps.getSession(resumeID)).model;
|
|
1479
|
+
const parts = ref === null ? null : splitModelRef(ref);
|
|
1480
|
+
if (parts !== null) return { tier: null, model: `${parts.provider}/${parts.model}`, variant: parts.variant };
|
|
1481
|
+
} catch {
|
|
1482
|
+
// unknown: fail closed below
|
|
1483
|
+
}
|
|
1484
|
+
return { tier: null, model: "unknown/unknown", variant: null };
|
|
1485
|
+
};
|
|
1486
|
+
|
|
1487
|
+
/** `null`: not a role dispatch (tiers mode, a tier or host agent). A role agent whose preparation fails is refused. */
|
|
1488
|
+
const prepareRole = async (agent: string, cfg: RouterConfig | undefined): Promise<RolePrepared | null> => {
|
|
1489
|
+
const prepareRoles = deps.runtime.prepareRoles;
|
|
1490
|
+
if (prepareRoles === undefined) return null;
|
|
1491
|
+
// QA-P21-1-8 / QA-P21-2-4: not started in roles mode, or this role agent was not registered: the tier path, as today.
|
|
1492
|
+
if (deps.rolesEnabled !== undefined && !deps.rolesEnabled(agent)) return null;
|
|
1493
|
+
|
|
1494
|
+
try {
|
|
1495
|
+
return await prepareRoles.call(deps.runtime, agent, cfg);
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
// `prepareRoles` throws only once it knows `agent` is a role agent (fail closed).
|
|
1498
|
+
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.failed(describeError(error)));
|
|
1499
|
+
}
|
|
1500
|
+
};
|
|
1501
|
+
|
|
1502
|
+
const decideRoleDispatch = async (call: RouteCall, rp: RolePrepared, session: SessionView): Promise<RouteOutcome> => {
|
|
1503
|
+
const { args } = call;
|
|
1504
|
+
const agent = rp.spec.agent;
|
|
1505
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : null;
|
|
1506
|
+
if (prompt === null) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noPrompt);
|
|
1507
|
+
const description = typeof args.description === "string" ? args.description : "";
|
|
1508
|
+
const sessionDirectory = session.directory ?? deps.directory;
|
|
1509
|
+
const resumeID = str(args.sessionID);
|
|
1510
|
+
const resumed = resumeID !== null;
|
|
1511
|
+
|
|
1512
|
+
// 1. the route line, from a rules-only pass (never the backend); a malformed first route line refuses the dispatch (handoff 4).
|
|
1513
|
+
const lined = await classify({ description, prompt, cwd: sessionDirectory }, { ...rp.classifyDeps, backend: null });
|
|
1514
|
+
if (lined.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
|
|
1515
|
+
|
|
1516
|
+
// 2. work root: `root=` from the trace only, text-compared with `git worktree list --porcelain` before any filesystem call.
|
|
1517
|
+
const root = await resolveRoleWorkRoot({ root: lined.trace.routeLine?.root ?? null, sessionDirectory }, workRootDeps);
|
|
1518
|
+
const bound = resumeID === null ? undefined : currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) });
|
|
1519
|
+
|
|
1520
|
+
// 3. classify in the dispatch's own root (QA-G-B-3 (1)): an absolute path inside it is no `external_dir`. A resume of an exactly
|
|
1521
|
+
// bound child is classified in its bound root (QA-P33F1-1-1); without a `root=` (the work root is the session directory) or a
|
|
1522
|
+
// validated one, in the session directory as the host names it.
|
|
1523
|
+
const requestedRoot = root.requested !== null ? root.workRoot : null;
|
|
1524
|
+
const classifyCwd = (bound?.kind === "exact" ? bound.grant.workRoot : null) ?? requestedRoot ?? sessionDirectory;
|
|
1525
|
+
const result = await classify({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
|
|
1526
|
+
if (result.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
|
|
1527
|
+
const routeLine = result.trace.routeLine;
|
|
1528
|
+
// QA-G-B-3 (2): a dynamic role's route line decides its needs (narrow-only). QA-G-B-1: a resume is decided on the facts of the
|
|
1529
|
+
// dispatch it resumes (class, confidence, needs; risk/scope the max with its own, raise-only).
|
|
1530
|
+
const matches = classifyNeedMatches({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
|
|
1531
|
+
const original = resumeID === null ? undefined : lookupDispatch(resumeID);
|
|
1532
|
+
const ownFacts = effectiveFactsOf({ facts: roleNeedsOf(result.facts, routeLine, rp.spec, new Set(matches.map((m) => m.need))), trace: result.trace });
|
|
1533
|
+
const taskFacts = resumeFactsOf(original?.facts, ownFacts);
|
|
1534
|
+
const classified: ClassifyResult = { ...result, facts: taskFacts };
|
|
1535
|
+
// QA-G-B-3 (3): why each need could be there (before any narrowing), for the decision row's trace.
|
|
1536
|
+
const needTerms = [
|
|
1537
|
+
...matches.map((m) => `${m.need}:${m.term}`),
|
|
1538
|
+
...(routeLine?.needs ?? []).map((need) => `${need}:route-line`),
|
|
1539
|
+
// the implied needs of the rules' class and of the final class (the route line's, or the backend's)
|
|
1540
|
+
...[...new Set([result.trace.rules.class, result.facts.class])].flatMap((cls) => CLASS_IMPLIED_NEEDS[cls].map((need) => `${need}:class=${cls}`)),
|
|
1541
|
+
...(original === undefined ? [] : original.facts.needs.map((need) => `${need}:resumed-dispatch`)),
|
|
1542
|
+
];
|
|
1543
|
+
|
|
1544
|
+
// 4. grant (widened actions of a resume recompute the floor, handoff 36). QA-P21-2-1: a resume of an EXACTLY bound child keeps
|
|
1545
|
+
// what that child holds (its bound grant) plus the widened actions — the resume prompt alone ("continue") would lose them.
|
|
1546
|
+
const grant: DispatchGrant = bound?.kind === "exact" ? resumedGrant(bound.grant, call.widened ?? [])
|
|
1547
|
+
: grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine);
|
|
1548
|
+
|
|
1549
|
+
// 5. effective detection (S10/P-9, A34; handoff 5): never `result.detection` as is. QA-G-B-1: a resume that names no
|
|
1550
|
+
// `[acceptance]` block of its own carries the one of the dispatch it resumes (and its `VERIFY:` lines, when it names none), so
|
|
1551
|
+
// the floor and the router's gate see the same acceptance as that dispatch — the block is appended to the resume's prompt.
|
|
1552
|
+
const own = verificationParts(prompt);
|
|
1553
|
+
const carried = resumed && own.block === null ? original?.verification ?? null : null;
|
|
1554
|
+
const carriedText = carried === null ? null : [...(own.directives.length === 0 ? carried.directives : []), carried.block].join("\n");
|
|
1555
|
+
const verifyPrompt = carriedText === null ? prompt : withLastLine(prompt, carriedText);
|
|
1556
|
+
// QA-G-B N-a: the `d=` claim travels with the block it was made for (a resume's own route line names its own).
|
|
1557
|
+
const claim = result.detection ?? (carried === null ? null : carried.claim ?? null);
|
|
1558
|
+
const verification: CarriedVerification | null = own.block !== null
|
|
1559
|
+
? { block: own.block, directives: own.directives, ...(result.detection == null ? {} : { claim: result.detection }) }
|
|
1560
|
+
: carried === null ? null : {
|
|
1561
|
+
block: carried.block, directives: own.directives.length > 0 ? own.directives : carried.directives,
|
|
1562
|
+
...(claim === null ? {} : { claim }),
|
|
1563
|
+
// QA-G-B-2-1: the same lineage — judged against the baseline of the attempt that introduced the block.
|
|
1564
|
+
...(carried.baseline === undefined ? {} : { baseline: carried.baseline }),
|
|
1565
|
+
};
|
|
1566
|
+
const acceptance = detectionOf(verifyPrompt);
|
|
1567
|
+
const bypassed = deps.isBypassed?.(call.sessionID) === true;
|
|
1568
|
+
const env = deps.env === undefined ? {} : { env: deps.env };
|
|
1569
|
+
const verifyRoot = verifyRootOf(grant, sessionDirectory, workRootDeps.realpath);
|
|
1570
|
+
const routerGate = roleRouterGate({
|
|
1571
|
+
cfg: rp.cfg, bypassed, acceptance, ...env,
|
|
1572
|
+
// QA-P21-1-2, QA-P21-2 nit 3. QA-G-B-2-1: a carried acceptance is never deferred (its gate runs at the return); its change-set
|
|
1573
|
+
// checks (testsPass, lintClean) can cover the child's earlier attempts only once the attempt that introduced the block was
|
|
1574
|
+
// gated with a known change set (its baseline) — until then the gate cannot back `deterministic`.
|
|
1575
|
+
deferred: carried === null
|
|
1576
|
+
? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
|
|
1577
|
+
: (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block),
|
|
1578
|
+
outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd), // DF2-F1, QA-P33F1-1-1, nit 3
|
|
1579
|
+
});
|
|
1580
|
+
// QA-G-B-7: the gate verifies nothing at all (enforcement off, /bypass, `require: never`, a cwd outside the root it verifies in)
|
|
1581
|
+
// → detection `none`.
|
|
1582
|
+
const verifies = roleVerificationRuns({
|
|
1583
|
+
cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd),
|
|
1584
|
+
});
|
|
1585
|
+
const detection = effectiveDetection({ routerGate, claim, acceptance, verifies });
|
|
1586
|
+
|
|
1587
|
+
// 6. bounds on the one role tier order (handoff 9); a resume passes the child's running tier. QA-P21-2-2: the raise recorded
|
|
1588
|
+
// after a verification FAIL of this child (for this parent) is a raise-only floor, like `floorTier`; consumed on success.
|
|
1589
|
+
const running = resumeID === null ? null : await runningRungOf(resumeID);
|
|
1590
|
+
const tiers = roleTierOrder(rp.cfg, rp.session);
|
|
1591
|
+
const raised = resumeID === null ? null : pendingResumeRaise(resumeID, call.sessionID);
|
|
1592
|
+
const floorTier = higherTier(tiers, rp.cfg.enforcement?.escalate?.floorTier ?? null, raised);
|
|
1593
|
+
const bounds = tierBounds(rp.spec, grant, classified, detection, {
|
|
1594
|
+
floorTier,
|
|
1595
|
+
runningTier: running?.tier ?? null,
|
|
1596
|
+
pinTier: routeLine?.tier ?? null,
|
|
1597
|
+
tiers,
|
|
1598
|
+
});
|
|
1599
|
+
|
|
1600
|
+
// 7. kernel (handoff 10: kernel.ts / ladders.ts); `dispatch === null` refuses, never a fallback (handoff 6).
|
|
1601
|
+
const ladder = buildRoleLadder({
|
|
1602
|
+
cfg: rp.cfg, facts: taskFacts, role: agent, window: bounds, pricing: (model) => rp.catalog.pricing(model), logger: deps.logger, session: rp.session,
|
|
1603
|
+
});
|
|
1604
|
+
const decisionID = `${call.sessionID}:${safeNow(now)}:${instanceNonce}:${++sequence}`;
|
|
1605
|
+
const rd = decideRole({
|
|
1606
|
+
classified, ladder, detection, engine: rp.engine, routing: rp.routing, store: rp.store,
|
|
1607
|
+
resume: running === null ? null : { model: running.model, variant: running.variant },
|
|
1608
|
+
exploration: { rate: rp.exploration, decisionID },
|
|
1609
|
+
});
|
|
1610
|
+
if (rd.dispatch === null) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, rd.reasons));
|
|
1611
|
+
|
|
1612
|
+
// 8. an explicit caller `model` is kept only inside the bounds, and never over a route-line pin (QA-P21-1-5: the pinned rung,
|
|
1613
|
+
// raised to the running rung on a resume, wins); then the host catalog decides whether the variant exists.
|
|
1614
|
+
const notes: string[] = [...(root.note === null ? [] : [root.note]), ...grant.notes];
|
|
1615
|
+
if (carried !== null) notes.push(CARRIED_ACCEPTANCE_NOTE);
|
|
1616
|
+
// #84 P2.3 (T2.3.3): the row of a resume records the authority it widens (the actions new to this child's grant).
|
|
1617
|
+
const widenedNow = (call.widened ?? []).filter((action) => grant.actions.has(action) && bound?.grant.actions.has(action) !== true);
|
|
1618
|
+
if (widenedNow.length > 0) notes.push(BINDING_NOTES.widened(widenedNow));
|
|
1619
|
+
if (raised !== null) notes.push(`${RESUME_RAISE_NOTE}${raised}`);
|
|
1620
|
+
const callerRef = str(args.model);
|
|
1621
|
+
const placed = callerRef === null
|
|
1622
|
+
? null
|
|
1623
|
+
: bounds.pinned !== null
|
|
1624
|
+
? { candidate: rd.dispatch, code: PIN_OVER_CALLER_REASON }
|
|
1625
|
+
: placeCallerModel(ladder, callerRef, rd.dispatch, resumed);
|
|
1626
|
+
const picked: Candidate = placed === null ? rd.dispatch : placed.candidate;
|
|
1627
|
+
// QA-G-B nit N1: an explicit caller `model` that wins over an exploration draw makes the dispatch no exploration (a route-line
|
|
1628
|
+
// pin over the caller keeps the kernel's pick, so its draw stands).
|
|
1629
|
+
const explored = rd.explore && (placed === null || placed.code === PIN_OVER_CALLER_REASON);
|
|
1630
|
+
const variantPlace = placeInCatalog(ladder, picked, rp.catalog);
|
|
1631
|
+
if (variantPlace === null) {
|
|
1632
|
+
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, [...rd.reasons, VARIANT_NO_CANDIDATE_REASON]));
|
|
1633
|
+
}
|
|
1634
|
+
const { candidate: dispatch, variant: finalVariant, dropped } = variantPlace;
|
|
1635
|
+
if (dropped !== null) notes.push(dropped);
|
|
1636
|
+
const model = refOf(dispatch.model, finalVariant);
|
|
1637
|
+
const tier = dispatch.tier;
|
|
1638
|
+
|
|
1639
|
+
// 9. binding markers (a fresh dispatch only; handoff 31): nonce at the END of the description, nonce line LAST in the prompt.
|
|
1640
|
+
// QA-G-B-1: a resume's carried verification is appended instead (it has no nonce).
|
|
1641
|
+
const nonce = resumed ? null : newDispatchNonce();
|
|
1642
|
+
const outPrompt = nonce !== null ? withLastLine(result.stripped, noncePromptLine(nonce))
|
|
1643
|
+
: carriedText === null ? result.stripped : withLastLine(result.stripped, carriedText);
|
|
1644
|
+
const outDescription = nonce === null ? null : `${description}${nonceTitleSuffix(nonce)}`;
|
|
1645
|
+
const routeBudget = routeLine?.budget ?? null;
|
|
1646
|
+
const budget = roleGuardProfile(rp.spec, tier, routeBudget).budget;
|
|
1647
|
+
|
|
1648
|
+
// 10. the decision row with the role extension (no row when the engine is static).
|
|
1649
|
+
const decision = rd.decision;
|
|
1650
|
+
const facts = taskFacts;
|
|
1651
|
+
const cls = facts.class;
|
|
1652
|
+
const ran: ChosenDispatch = { agent: { origin: "role", id: agent }, model: dispatch.model, variant: finalVariant };
|
|
1653
|
+
let row: DecisionRow | null = null;
|
|
1654
|
+
const mode = rp.engine;
|
|
1655
|
+
if (mode !== "static" && rp.enqueue !== null) {
|
|
1656
|
+
// QA-P21-1-6: switched/chosen follow the kernel's decision; a variant the catalog lacks only changes what is dispatched.
|
|
1657
|
+
const applied = mode === "enforce" && rd.switched && placed === null;
|
|
1658
|
+
const wouldSwitch = mode !== "enforce" && !resumed && decision.switched && placed === null;
|
|
1659
|
+
const argmin = decision.argmin !== null && decision.argmin.key !== decision.best?.key ? decision.argmin : null;
|
|
1660
|
+
const head = resumed
|
|
1661
|
+
? `${RESUME_REASON}: a role dispatch that resumes a child is never switched or explored (A30); engine decision: ${reasonText(decision)}`
|
|
1662
|
+
: explored
|
|
1663
|
+
? `explore: exploration draw (propensity ${rd.propensity}); engine decision: ${reasonText(decision)}`
|
|
1664
|
+
: placed !== null
|
|
1665
|
+
? `${placed.code}: the call named model ${callerRef}; engine decision: ${reasonText(decision)}`
|
|
1666
|
+
: reasonText(decision);
|
|
1667
|
+
const extra = [...rd.reasons, ...notes];
|
|
1668
|
+
// QA-P21-1-11: a fresh dispatch has no binding yet (its child binds later; `noteBinding` writes the observed kind then).
|
|
1669
|
+
// A resume records the child's current binding.
|
|
1670
|
+
const binding = resumed ? currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) })?.kind : undefined;
|
|
1671
|
+
row = {
|
|
1672
|
+
v: LOG_ROW_VERSION,
|
|
1673
|
+
ts: new Date(safeNow(now)).toISOString(),
|
|
1674
|
+
sessionID: call.sessionID,
|
|
1675
|
+
kind: "decision",
|
|
1676
|
+
decisionID,
|
|
1677
|
+
mode,
|
|
1678
|
+
childSessionID: resumeID,
|
|
1679
|
+
facts: factsOf(facts),
|
|
1680
|
+
chosen: applied && rd.base !== null ? choiceOf(cls, rd.base) : choiceOf(cls, ran),
|
|
1681
|
+
best: decision.best,
|
|
1682
|
+
switched: applied || wouldSwitch,
|
|
1683
|
+
pinned: decision.pinned,
|
|
1684
|
+
unit: decision.unit,
|
|
1685
|
+
costs: { ...decision.costs },
|
|
1686
|
+
confidence: decision.confidence,
|
|
1687
|
+
reason: `${head}; role @${agent} on ${tier} in ${bounds.floor}..${bounds.ceiling}${extra.length > 0 ? ` [${extra.join("; ")}]` : ""}`,
|
|
1688
|
+
step: "dispatch",
|
|
1689
|
+
resume: resumed,
|
|
1690
|
+
trace: { ...traceOf(result, argmin), needTerms }, // QA-G-B-3 (3)
|
|
1691
|
+
detection: {
|
|
1692
|
+
effective: detection,
|
|
1693
|
+
...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
|
|
1694
|
+
},
|
|
1695
|
+
capability: { pick: rd.base?.rank ?? null, dispatched: dispatch.rank },
|
|
1696
|
+
role: agent,
|
|
1697
|
+
tier,
|
|
1698
|
+
grant: [...grant.actions].sort(),
|
|
1699
|
+
boundsReasons: [...bounds.reasons],
|
|
1700
|
+
explore: explored,
|
|
1701
|
+
propensity: rd.propensity,
|
|
1702
|
+
...(binding === undefined ? {} : { binding }),
|
|
1703
|
+
};
|
|
1704
|
+
}
|
|
1705
|
+
const logged = row === null ? null : decisionID;
|
|
1706
|
+
|
|
1707
|
+
const routed: RoleRouted = {
|
|
1708
|
+
callID: call.callID,
|
|
1709
|
+
parentSessionID: call.sessionID,
|
|
1710
|
+
agent,
|
|
1711
|
+
tier,
|
|
1712
|
+
model,
|
|
1713
|
+
window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: bounds.pinned },
|
|
1714
|
+
grant,
|
|
1715
|
+
workRoot: root.workRoot,
|
|
1716
|
+
verifyRoot,
|
|
1717
|
+
requestedRoot: root.requested,
|
|
1718
|
+
notes,
|
|
1719
|
+
detection,
|
|
1720
|
+
budget,
|
|
1721
|
+
routeBudget,
|
|
1722
|
+
nonce,
|
|
1723
|
+
decisionID: logged,
|
|
1724
|
+
resumeID,
|
|
1725
|
+
nextTier: nextRoleTier(tiers, rp.spec.tierRange.ceiling, tier),
|
|
1726
|
+
class: cls,
|
|
1727
|
+
...(carried !== null ? { carried: true as const } : {}), // QA-G-B-2-1
|
|
1728
|
+
};
|
|
1729
|
+
rememberRoutedRole(routed);
|
|
1730
|
+
if (raised !== null && resumeID !== null) resumeRaises.delete(resumeID); // QA-P21-2-2: consumed once, by a routed resume
|
|
1731
|
+
|
|
1732
|
+
decided.set(call.callID, {
|
|
1733
|
+
parentSessionID: call.sessionID,
|
|
1734
|
+
decisionID,
|
|
1735
|
+
facts: factsOf(facts),
|
|
1736
|
+
acceptance: depthOf(detection),
|
|
1737
|
+
description: outDescription ?? (description !== "" ? description : null),
|
|
1738
|
+
row,
|
|
1739
|
+
enqueue: rp.enqueue ?? (() => {}),
|
|
1740
|
+
capabilityOf: (r) => (r.agent === agent && sameModelVariant(r, ran) ? dispatch.rank : null),
|
|
1741
|
+
final: { agent, model: dispatch.model, variant: finalVariant },
|
|
1742
|
+
routerIds: routerTierIds(rp.cfg),
|
|
1743
|
+
resolve: (target) => resolveChosen({ cfg: rp.cfg, agents: null, agent: target, parentModel: session.model }),
|
|
1744
|
+
picked: agent,
|
|
1745
|
+
at: now(),
|
|
1746
|
+
role: {
|
|
1747
|
+
tier,
|
|
1748
|
+
outcomes: mode !== "static",
|
|
1749
|
+
pending: nonce === null ? null : { nonce, grant, budget, description: outDescription ?? description, decisionID: logged },
|
|
1750
|
+
verification,
|
|
1751
|
+
},
|
|
1752
|
+
});
|
|
1753
|
+
trim(decided, MAX_PENDING);
|
|
1754
|
+
return {
|
|
1755
|
+
mode,
|
|
1756
|
+
...(outPrompt !== prompt ? { prompt: outPrompt } : {}),
|
|
1757
|
+
model,
|
|
1758
|
+
...(logged === null ? {} : { decisionID: logged }),
|
|
1759
|
+
...(outDescription === null ? {} : { description: outDescription }),
|
|
1760
|
+
role: routed,
|
|
1761
|
+
};
|
|
1762
|
+
};
|
|
1763
|
+
|
|
1764
|
+
/**
|
|
1765
|
+
* QA-P21-1-1: a role dispatch made by a session that has a parent (a delegate). Its prompt is never parsed (no route line, pin
|
|
1766
|
+
* or steering) and nothing is registered for it (no nonce, no pending entry, no row: its child binds `unknown`), but it never
|
|
1767
|
+
* runs on a model of its own choosing (I2): any caller `model` is replaced by the FLOOR rung of the window computed on the
|
|
1768
|
+
* unknown-binding grant (role max ∩ local, I9) — on a resume never below the child's running tier — and, as a routed role
|
|
1769
|
+
* dispatch, it is forced to the foreground (P-5).
|
|
1770
|
+
*/
|
|
1771
|
+
const decideDelegateRoleDispatch = (call: RouteCall, rp: RolePrepared, session: SessionView): RouteOutcome => {
|
|
1772
|
+
const agent = rp.spec.agent;
|
|
1773
|
+
const max = new Set<AuthorityAction>(roleMaxActions(rp.spec) ?? []);
|
|
1774
|
+
const grant: DispatchGrant = { actions: new Set(LOCAL_ACTIONS.filter((a) => max.has(a))), notes: [DELEGATE_DISPATCH_NOTE], workRoot: null };
|
|
1775
|
+
const facts: TaskFacts = { class: "other", risk: "low", scope: "single", needs: [], confidence: 0, source: "rules" };
|
|
1776
|
+
const detection = effectiveDetection({ routerGate: false, claim: null, acceptance: null });
|
|
1777
|
+
const tiers = roleTierOrder(rp.cfg, rp.session);
|
|
1778
|
+
const resumeID = str(call.args.sessionID);
|
|
1779
|
+
const runningTier = resumeID === null ? null : lookupDispatch(resumeID)?.tier ?? null;
|
|
1780
|
+
const bounds = tierBounds(rp.spec, grant, { facts, trace: { rules: facts, routeLine: null } }, detection, {
|
|
1781
|
+
floorTier: rp.cfg.enforcement?.escalate?.floorTier ?? null, runningTier, pinTier: null, tiers,
|
|
1782
|
+
});
|
|
1783
|
+
const ladder = buildRoleLadder({
|
|
1784
|
+
cfg: rp.cfg, facts, role: agent, window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: null },
|
|
1785
|
+
pricing: (model) => rp.catalog.pricing(model), logger: deps.logger, session: rp.session,
|
|
1786
|
+
});
|
|
1787
|
+
const first = ladder.tiers.find((t) => t.tier === bounds.floor)?.first ?? ladder.tiers.find((t) => t.first !== null)?.first ?? null;
|
|
1788
|
+
const rung = first === null ? undefined : ladder.candidates[first];
|
|
1789
|
+
const placed = rung === undefined ? null : placeInCatalog(ladder, rung, rp.catalog);
|
|
1790
|
+
if (placed === null) {
|
|
1791
|
+
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.noCandidate(bounds.floor, bounds.ceiling, rung === undefined ? ["window:no-candidates"] : [VARIANT_NO_CANDIDATE_REASON]));
|
|
1792
|
+
}
|
|
1793
|
+
const tier = placed.candidate.tier;
|
|
1794
|
+
const model = refOf(placed.candidate.model, placed.variant);
|
|
1795
|
+
const routed: RoleRouted = {
|
|
1796
|
+
callID: call.callID,
|
|
1797
|
+
parentSessionID: call.sessionID,
|
|
1798
|
+
agent,
|
|
1799
|
+
tier,
|
|
1800
|
+
model,
|
|
1801
|
+
window: { floor: bounds.floor, ceiling: bounds.ceiling, pinned: null },
|
|
1802
|
+
grant,
|
|
1803
|
+
workRoot: null,
|
|
1804
|
+
verifyRoot: verifyRootOf(grant, session.directory ?? deps.directory, workRootDeps.realpath),
|
|
1805
|
+
requestedRoot: null,
|
|
1806
|
+
notes: [DELEGATE_DISPATCH_NOTE, ...(placed.dropped === null ? [] : [placed.dropped])],
|
|
1807
|
+
detection,
|
|
1808
|
+
budget: roleGuardProfile(rp.spec, tier, null).budget,
|
|
1809
|
+
routeBudget: null,
|
|
1810
|
+
nonce: null,
|
|
1811
|
+
decisionID: null,
|
|
1812
|
+
resumeID,
|
|
1813
|
+
nextTier: nextRoleTier(tiers, rp.spec.tierRange.ceiling, tier),
|
|
1814
|
+
class: null,
|
|
1815
|
+
delegate: true, // QA-G-A1-2: the adapter never consumes an authority request on this path
|
|
1816
|
+
};
|
|
1817
|
+
rememberRoutedRole(routed);
|
|
1818
|
+
return { mode: rp.engine, model, role: routed };
|
|
1819
|
+
};
|
|
1820
|
+
|
|
1821
|
+
/** A role dispatch, from `route()`: claimed like a tier call (A3); only the orchestrator's own dispatch is routed. */
|
|
1822
|
+
const routeRoleCall = async (call: RouteCall, callKey: string, rp: RolePrepared): Promise<RouteOutcome> => {
|
|
1823
|
+
const agent = rp.spec.agent;
|
|
1824
|
+
if (handledCalls.has(callKey)) return UNTOUCHED; // A3: another instance already acted on this call
|
|
1825
|
+
let session: SessionView;
|
|
1826
|
+
try {
|
|
1827
|
+
session = readSession(await deps.getSession(call.sessionID));
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.session(describeError(error)));
|
|
1830
|
+
}
|
|
1831
|
+
if (!claimCall(callKey)) return UNTOUCHED;
|
|
1832
|
+
try {
|
|
1833
|
+
// QA-P21-1-1: a delegate's dispatch is never parsed (it must not pin or steer), but it runs on the router's floor rung of
|
|
1834
|
+
// the unknown-binding window, in the foreground — never on a model the delegate names (I2).
|
|
1835
|
+
if (session.parentID !== null) return decideDelegateRoleDispatch(call, rp, session);
|
|
1836
|
+
return await decideRoleDispatch(call, rp, session);
|
|
1837
|
+
} catch (error) {
|
|
1838
|
+
if (error instanceof RoleDispatchRefusal) throw error;
|
|
1839
|
+
throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.failed(describeError(error)));
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
|
|
1843
|
+
return {
|
|
1844
|
+
async route(call): Promise<RouteOutcome> {
|
|
1845
|
+
try {
|
|
1846
|
+
const agent = str(call.args.agent);
|
|
1847
|
+
const callKey = `${call.sessionID}\u0000${call.callID}`;
|
|
1848
|
+
// QA-2.2-1 / QA-INT-1: a call the delegate runner announced is the runner's alone. Only a call that carries the runner's own
|
|
1849
|
+
// description can be one (an orchestrator dispatch with the same agent and prompt never spends the runner's mark); if the
|
|
1850
|
+
// prompt is not the announced one (rewritten by another plugin) a runner-titled call still finds its mark by session and
|
|
1851
|
+
// agent. The call is then marked handled, so no other instance of this process (A3) routes it either.
|
|
1852
|
+
if (agent !== null && typeof call.args.prompt === "string"
|
|
1853
|
+
&& call.args.description === runnerDescription(agent === deps.graderAgent ? undefined : agent)) {
|
|
1854
|
+
const exact = consumeRunnerDispatch({ parentSessionID: call.sessionID, agent, prompt: call.args.prompt });
|
|
1855
|
+
if (exact || consumeRunnerDispatchLoose({ parentSessionID: call.sessionID, agent })) {
|
|
1856
|
+
if (!exact) deps.logger.warn("[router] routing: a runner call arrived with another prompt than the one it announced (rewritten by another plugin?); it was left alone", { agent });
|
|
1857
|
+
claimCall(callKey);
|
|
1858
|
+
return UNTOUCHED;
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
if (agent === null || agent === deps.graderAgent) return UNTOUCHED;
|
|
1862
|
+
// #84 P2.1: a role agent of roles mode (v2) takes the role path in EVERY engine mode; tiers mode gets `null` before any host call.
|
|
1863
|
+
const role = await prepareRole(agent, call.cfg);
|
|
1864
|
+
if (role !== null) return await routeRoleCall(call, callKey, role);
|
|
1865
|
+
const prepared = await deps.runtime.prepare(call.cfg);
|
|
1866
|
+
if (prepared === null) return UNTOUCHED; // static: nothing touched
|
|
1867
|
+
if (handledCalls.has(callKey)) return UNTOUCHED; // A3 (QA-2.2-12): another instance already acted on this call
|
|
1868
|
+
let session: SessionView;
|
|
1869
|
+
try {
|
|
1870
|
+
session = readSession(await deps.getSession(call.sessionID));
|
|
1871
|
+
} catch (error) {
|
|
1872
|
+
deps.logger.warn("[router] routing: the dispatching session is unavailable; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
|
|
1873
|
+
return UNTOUCHED;
|
|
1874
|
+
}
|
|
1875
|
+
// QA-G-A6: only the session location receives tool hooks on measured hosts. Never defer to an instance that
|
|
1876
|
+
// may receive no hook; the process-wide call claim below remains the single-writer guard.
|
|
1877
|
+
if (!claimCall(callKey)) return UNTOUCHED;
|
|
1878
|
+
// Only an orchestrator's own prompt is parsed (QA focus: a delegate must not be able to pin or steer).
|
|
1879
|
+
if (session.parentID !== null) return UNTOUCHED;
|
|
1880
|
+
const view = await deps.runtime.agents(session.agent ?? call.agent, session.rules);
|
|
1881
|
+
return await decideAndRecord(call, prepared, session, view);
|
|
1882
|
+
} catch (error) {
|
|
1883
|
+
if (error instanceof RoleDispatchRefusal) throw error; // #84 P2.1: the host must refuse the role dispatch
|
|
1884
|
+
deps.logger.warn("[router] routing: the engine failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
|
|
1885
|
+
return UNTOUCHED;
|
|
1886
|
+
}
|
|
1887
|
+
},
|
|
1888
|
+
|
|
1889
|
+
commit(callID, input): void {
|
|
1890
|
+
try {
|
|
1891
|
+
const d = decided.get(callID);
|
|
1892
|
+
if (d === undefined) return;
|
|
1893
|
+
decided.delete(callID);
|
|
1894
|
+
const final = isRecord(input) ? input : {};
|
|
1895
|
+
// The agent and model the host will run, after the legacy hook: they win over what the engine decided.
|
|
1896
|
+
const ran = d.final === null ? null : ranOf(d, d.final, final);
|
|
1897
|
+
// QA-G-A2: the hook chain let the call through, so the dispatch runs: its decision row is written now (never for a rejected call).
|
|
1898
|
+
let written: DecisionRow | null = null;
|
|
1899
|
+
try {
|
|
1900
|
+
// A34 (QA-G-B8): the capability of what really runs, after the legacy hook.
|
|
1901
|
+
const dispatched = ran === null ? null : d.capabilityOf(ran);
|
|
1902
|
+
if (d.row !== null) {
|
|
1903
|
+
written = { ...d.row, capability: { pick: d.row.capability?.pick ?? null, dispatched } };
|
|
1904
|
+
d.enqueue(written);
|
|
1905
|
+
}
|
|
1906
|
+
} catch (error) {
|
|
1907
|
+
deps.logger.warn("[router] routing: the decision row could not be queued", { error: describeError(error) });
|
|
1908
|
+
}
|
|
1909
|
+
// #84 P2.1: a fresh role dispatch registers its pending binding entry from the input the host will execute (handoff 31).
|
|
1910
|
+
const rolePending = d.role !== undefined && d.role.pending !== null && str(final.sessionID) === null;
|
|
1911
|
+
if (rolePending && d.role !== undefined && d.role.pending !== null) {
|
|
1912
|
+
try {
|
|
1913
|
+
registerPending({
|
|
1914
|
+
parentSessionID: d.parentSessionID,
|
|
1915
|
+
callID,
|
|
1916
|
+
agent: str(final.agent) ?? d.picked,
|
|
1917
|
+
description: str(final.description) ?? d.role.pending.description,
|
|
1918
|
+
nonce: d.role.pending.nonce,
|
|
1919
|
+
grant: d.role.pending.grant,
|
|
1920
|
+
budget: d.role.pending.budget,
|
|
1921
|
+
decisionID: d.role.pending.decisionID,
|
|
1922
|
+
registeredAt: Date.now(), // the binding registry's own clock
|
|
1923
|
+
});
|
|
1924
|
+
} catch (error) {
|
|
1925
|
+
deps.logger.warn("[router] routing: the role dispatch could not be registered for binding", { error: describeError(error) });
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
if (ran === null) return; // nothing to record a step against
|
|
1929
|
+
const { agent, model, variant } = ran;
|
|
1930
|
+
const resumeID = str(final.sessionID);
|
|
1931
|
+
// QA-2.2-R2-1: remember what the registry held for a resumed child, in case the host then rejects the resume.
|
|
1932
|
+
const previous = resumeID === null ? undefined : lookupDispatch(resumeID);
|
|
1933
|
+
// QA-G-B-1: a role resume never overwrites the class the child was dispatched under, so an attempt raised after a FAIL is
|
|
1934
|
+
// recorded (and scored) under the original class.
|
|
1935
|
+
const facts = d.role !== undefined && previous !== undefined ? { ...d.facts, class: previous.facts.class } : d.facts;
|
|
1936
|
+
const dispatched: DispatchInput = {
|
|
1937
|
+
facts,
|
|
1938
|
+
agent,
|
|
1939
|
+
model,
|
|
1940
|
+
variant,
|
|
1941
|
+
tier: d.role !== undefined && agent === d.picked ? d.role.tier : classifyAgentOrigin(agent, d.routerIds) === "router" ? agent : null,
|
|
1942
|
+
acceptance: d.acceptance,
|
|
1943
|
+
parentSessionID: d.parentSessionID,
|
|
1944
|
+
decisionID: d.decisionID,
|
|
1945
|
+
step: "dispatch",
|
|
1946
|
+
picked: d.picked,
|
|
1947
|
+
...(d.role !== undefined && !d.role.outcomes ? { outcomes: false } : {}),
|
|
1948
|
+
...(d.role?.verification == null ? {} : { verification: d.role.verification }),
|
|
1949
|
+
};
|
|
1950
|
+
const t = now();
|
|
1951
|
+
sweep(t);
|
|
1952
|
+
const entry: Entry = {
|
|
1953
|
+
callID, parentSessionID: d.parentSessionID, agent, description: d.description, input: dispatched, at: t,
|
|
1954
|
+
state: resumeID === null ? "waiting" : "resumed",
|
|
1955
|
+
...(resumeID === null ? {} : { resumeID }),
|
|
1956
|
+
...(previous === undefined ? {} : { previous }),
|
|
1957
|
+
...(rolePending ? { rolePending: true as const } : {}),
|
|
1958
|
+
...(d.role !== undefined && written !== null ? { roleRow: { row: written, enqueue: d.enqueue } } : {}),
|
|
1959
|
+
};
|
|
1960
|
+
if (resumeID !== null) register(resumeID, dispatched);
|
|
1961
|
+
entries.delete(callID);
|
|
1962
|
+
entries.set(callID, entry);
|
|
1963
|
+
trim(entries, MAX_PENDING);
|
|
1964
|
+
} catch (error) {
|
|
1965
|
+
deps.logger.warn("[router] routing: the dispatch could not be committed for ingestion", { error: describeError(error) });
|
|
1966
|
+
}
|
|
1967
|
+
},
|
|
1968
|
+
|
|
1969
|
+
onSessionCreated(created): void {
|
|
1970
|
+
try {
|
|
1971
|
+
const sessionID = str(created.sessionID);
|
|
1972
|
+
const parentID = str(created.parentID);
|
|
1973
|
+
if (sessionID === null || parentID === null || entries.size === 0) return;
|
|
1974
|
+
// The runner registers its own children (and titles them `Router …`): never take one for an orchestrator dispatch.
|
|
1975
|
+
if (lookupDispatch(sessionID) !== undefined) return;
|
|
1976
|
+
const title = str(created.title);
|
|
1977
|
+
if (title !== null && RUNNER_CHILD_TITLE.test(title)) return;
|
|
1978
|
+
const t = now();
|
|
1979
|
+
sweep(t);
|
|
1980
|
+
const agent = str(created.agent);
|
|
1981
|
+
const mine = [...entries.values()].filter((entry) => entry.parentSessionID === parentID && claimable(entry, t));
|
|
1982
|
+
const sameAgent = agent === null ? mine : mine.filter((entry) => entry.agent === agent);
|
|
1983
|
+
if (sameAgent.length === 0) return;
|
|
1984
|
+
const claimed = (title === null ? undefined : sameAgent.find((entry) => entry.description === title)) ?? sameAgent[0];
|
|
1985
|
+
if (claimed === undefined) return;
|
|
1986
|
+
claimed.state = "claimed";
|
|
1987
|
+
claimed.claimedChild = sessionID;
|
|
1988
|
+
register(sessionID, claimed.input);
|
|
1989
|
+
} catch (error) {
|
|
1990
|
+
deps.logger.warn("[router] routing: a new child session could not be matched to its dispatch", { error: describeError(error) });
|
|
1991
|
+
}
|
|
1992
|
+
},
|
|
1993
|
+
|
|
1994
|
+
onCallResult(callID, childSessionID): void {
|
|
1995
|
+
try {
|
|
1996
|
+
decided.delete(callID);
|
|
1997
|
+
const entry = entries.get(callID);
|
|
1998
|
+
entries.delete(callID);
|
|
1999
|
+
if (entry === undefined) return;
|
|
2000
|
+
if (childSessionID === null) {
|
|
2001
|
+
undoResume(entry); // the call ended without a result: a resume the host rejected leaves the child as it was
|
|
2002
|
+
return;
|
|
2003
|
+
}
|
|
2004
|
+
if (entry.state === "resumed") return;
|
|
2005
|
+
// Still waiting (the event was missed, or the claim expired), or claimed for a different child: the result is the truth.
|
|
2006
|
+
// The same execution, corrected or completed: keep what the registry has seen of it (QA-2.3-1a).
|
|
2007
|
+
misclaimed.delete(childSessionID); // a child this dispatch really started is no longer anyone's wrong claim
|
|
2008
|
+
if (lookupDispatch(childSessionID)?.decisionID !== entry.input.decisionID) register(childSessionID, { ...entry.input, keepExecution: true });
|
|
2009
|
+
if (entry.state === "claimed" && entry.claimedChild !== undefined && entry.claimedChild !== childSessionID
|
|
2010
|
+
&& lookupDispatch(entry.claimedChild)?.decisionID === entry.input.decisionID) {
|
|
2011
|
+
// A wrong claim: that child belongs to another dispatch. It stays registered (its steps keep being counted) and is marked;
|
|
2012
|
+
// the result of the dispatch that really started it takes it over (R2-7).
|
|
2013
|
+
misclaimed.set(entry.claimedChild, entry.input.decisionID ?? "");
|
|
2014
|
+
trim(misclaimed, MAX_PENDING);
|
|
2015
|
+
}
|
|
2016
|
+
} catch (error) {
|
|
2017
|
+
deps.logger.warn("[router] routing: the child of a finished dispatch could not be registered", { error: describeError(error) });
|
|
2018
|
+
}
|
|
2019
|
+
},
|
|
2020
|
+
|
|
2021
|
+
onCallFinished(callID): void {
|
|
2022
|
+
decided.delete(callID);
|
|
2023
|
+
const entry = entries.get(callID);
|
|
2024
|
+
entries.delete(callID);
|
|
2025
|
+
if (entry !== undefined) undoResume(entry);
|
|
2026
|
+
// #84 P2.1: a rejected role call leaves no pending binding entry and no routed record behind.
|
|
2027
|
+
routedRoles.delete(callID);
|
|
2028
|
+
strippedRoots.delete(callID);
|
|
2029
|
+
if (entry?.rolePending === true) {
|
|
2030
|
+
try {
|
|
2031
|
+
evictCall(entry.parentSessionID, callID);
|
|
2032
|
+
} catch (error) {
|
|
2033
|
+
deps.logger.warn("[router] routing: a rejected role dispatch could not be evicted from the binding registry", { error: describeError(error) });
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
},
|
|
2037
|
+
|
|
2038
|
+
noteBinding(childSessionID, binding): void {
|
|
2039
|
+
try {
|
|
2040
|
+
if (notedBindings.has(childSessionID)) return;
|
|
2041
|
+
const decisionID = binding.decisionID ?? lookupDispatch(childSessionID)?.decisionID ?? null;
|
|
2042
|
+
const entry = [...entries.values()].find((e) => e.roleRow !== undefined
|
|
2043
|
+
&& ((decisionID !== null && e.input.decisionID === decisionID) || e.claimedChild === childSessionID || e.resumeID === childSessionID));
|
|
2044
|
+
if (entry?.roleRow === undefined) return;
|
|
2045
|
+
notedBindings.add(childSessionID);
|
|
2046
|
+
while (notedBindings.size > MAX_HANDLED_CALLS) notedBindings.delete(notedBindings.values().next().value as string);
|
|
2047
|
+
const { row, enqueue } = entry.roleRow;
|
|
2048
|
+
enqueue({
|
|
2049
|
+
v: LOG_ROW_VERSION,
|
|
2050
|
+
kind: "decision",
|
|
2051
|
+
ts: new Date(safeNow(now)).toISOString(),
|
|
2052
|
+
sessionID: row.sessionID,
|
|
2053
|
+
decisionID: row.decisionID,
|
|
2054
|
+
mode: row.mode,
|
|
2055
|
+
childSessionID,
|
|
2056
|
+
facts: row.facts,
|
|
2057
|
+
chosen: row.chosen,
|
|
2058
|
+
best: null,
|
|
2059
|
+
switched: false,
|
|
2060
|
+
pinned: false,
|
|
2061
|
+
unit: row.unit,
|
|
2062
|
+
costs: {},
|
|
2063
|
+
confidence: row.confidence,
|
|
2064
|
+
reason: `${ANNOTATION_REASON}binding:${binding.kind}`,
|
|
2065
|
+
step: row.step,
|
|
2066
|
+
resume: row.resume,
|
|
2067
|
+
...(row.role === undefined ? {} : { role: row.role }),
|
|
2068
|
+
...(row.tier === undefined ? {} : { tier: row.tier }),
|
|
2069
|
+
binding: binding.kind,
|
|
2070
|
+
});
|
|
2071
|
+
} catch (error) {
|
|
2072
|
+
deps.logger.warn("[router] routing: the binding of a role child could not be recorded", { error: describeError(error) });
|
|
2073
|
+
}
|
|
2074
|
+
},
|
|
2075
|
+
|
|
2076
|
+
misclaimedCount: () => misclaimed.size,
|
|
2077
|
+
|
|
2078
|
+
dispose(): void {
|
|
2079
|
+
},
|
|
2080
|
+
|
|
2081
|
+
pendingCount(): number {
|
|
2082
|
+
const t = now();
|
|
2083
|
+
let count = 0;
|
|
2084
|
+
for (const entry of entries.values()) if (claimable(entry, t)) count += 1;
|
|
2085
|
+
return count;
|
|
2086
|
+
},
|
|
2087
|
+
};
|
|
2088
|
+
}
|