opencode-model-router 2.7.0 → 2.9.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 +583 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/approvals.ts +354 -0
- package/src/commands/output.ts +34 -1
- package/src/compat/background.ts +2439 -0
- package/src/compat/child-session.ts +6 -0
- package/src/compat/turn-state.ts +215 -0
- package/src/compat/v2-client.ts +136 -17
- package/src/compat/v2-hooks.ts +2853 -109
- package/src/compat/v2-observations.ts +328 -0
- package/src/executor/capacity.ts +362 -0
- package/src/executor/child-guards.ts +40 -0
- package/src/executor/command.ts +265 -0
- package/src/executor/compile/edges.ts +809 -0
- package/src/executor/compile/estimate.ts +158 -0
- package/src/executor/compile/footprint.ts +829 -0
- package/src/executor/compile/index.ts +1080 -0
- package/src/executor/compile/parse.ts +1492 -0
- package/src/executor/compile/residue.ts +706 -0
- package/src/executor/compile/validate.ts +280 -0
- package/src/executor/create.ts +672 -0
- package/src/executor/expand.ts +551 -0
- package/src/executor/git.ts +1214 -0
- package/src/executor/host-preamble.ts +17 -0
- package/src/executor/instructions.ts +35 -0
- package/src/executor/integrate/bisect.ts +73 -0
- package/src/executor/integrate/checks.ts +1086 -0
- package/src/executor/integrate/land.ts +177 -0
- package/src/executor/integrate/phase-suite.ts +407 -0
- package/src/executor/integrate/queue.ts +3083 -0
- package/src/executor/integrate/run-resolver.ts +19 -0
- package/src/executor/launch.ts +652 -0
- package/src/executor/ledger.ts +2208 -0
- package/src/executor/observations.ts +212 -0
- package/src/executor/paths.ts +159 -0
- package/src/executor/platform.ts +39 -0
- package/src/executor/process-identity.ts +19 -0
- package/src/executor/qa-loop.ts +470 -0
- package/src/executor/recovery.ts +403 -0
- package/src/executor/runtime.ts +6233 -0
- package/src/executor/schedule.ts +246 -0
- package/src/executor/slots/env.ts +145 -0
- package/src/executor/slots/pool.ts +1564 -0
- package/src/executor/slots/provision.ts +853 -0
- package/src/executor/tool.ts +534 -0
- package/src/executor/types.ts +2064 -0
- package/src/executor/unattended.ts +488 -0
- package/src/guard/store.ts +3 -1
- package/src/index.ts +1789 -288
- package/src/router/config.ts +823 -26
- package/src/router/dispatch-header.ts +95 -2
- package/src/router/git-tools.ts +266 -19
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +44 -10
- package/src/router/role-agents.ts +334 -20
- package/src/router/roles-config.ts +93 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- package/src/router/sessions.ts +11 -0
- package/src/router/tool-paths.ts +308 -0
- package/src/router/work-roots.ts +86 -0
- package/src/routing/advisor/findings.ts +25 -5
- package/src/routing/classify/index.ts +7 -1
- package/src/routing/classify/route-line.ts +96 -5
- package/src/routing/classify/rules.ts +11 -0
- package/src/routing/classify/types.ts +26 -0
- package/src/routing/commands/stats.ts +2 -2
- package/src/routing/outcomes/durations.ts +225 -0
- package/src/routing/outcomes/index.ts +59 -2
- package/src/routing/outcomes/persist.ts +409 -0
- package/src/routing/outcomes/signals.ts +17 -0
- package/src/routing/outcomes/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/admission.ts +1028 -0
- package/src/routing/roles/approvals.ts +957 -0
- package/src/routing/roles/binding.ts +116 -13
- package/src/routing/roles/check-placement.ts +112 -0
- package/src/routing/roles/git-root.ts +500 -0
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +30 -3
- package/src/routing/roles/read-set.ts +325 -0
- package/src/routing/roles/work-root.ts +12 -2
- package/src/routing/wire/dispatch.ts +697 -30
- package/src/routing/wire/hint.ts +56 -8
- package/src/routing/wire/working-set.ts +58 -0
- package/src/util/linear-trim.ts +32 -0
- package/src/v2.ts +94 -49
- package/src/verify/batch.ts +7 -2
- package/src/verify/branch.ts +141 -0
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +268 -17
- package/src/verify/dispatch.ts +348 -37
- package/src/verify/dod.ts +46 -0
- package/src/verify/edges.ts +817 -0
- package/src/verify/exec.ts +52 -9
- package/src/verify/gate.ts +349 -16
- package/src/verify/git-top.ts +43 -0
- package/src/verify/head.ts +107 -0
- package/src/verify/pending.ts +1846 -18
- package/src/verify/perimeter.ts +1186 -0
- package/src/verify/pin.ts +109 -0
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +297 -8
- package/src/verify/risk.ts +16 -3
- package/src/verify/runner.ts +706 -32
- package/src/verify/tree.ts +372 -16
- package/src/verify/types.ts +66 -2
- package/src/verify/wiring.ts +1594 -46
|
@@ -48,25 +48,36 @@ import {
|
|
|
48
48
|
import { buildRoleLadder, roleTierOrder, routerTierIds } from "../engine/ladders";
|
|
49
49
|
import { decideRole } from "../engine/kernel";
|
|
50
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";
|
|
51
|
+
import { CLASS_BASE_RISK, CLASS_IMPLIED_NEEDS, FACT_SOURCES, NEEDS, RISKS, SCOPES, TASK_CLASSES, classify, classifyNeedMatches, classifyRiskTerm } from "../classify";
|
|
52
52
|
import type { ClassifyResult, Detection, Need, RouteLine, TaskFacts } from "../classify/types";
|
|
53
|
-
import { resolveVerifyBudget, type RouterConfig } from "../../router/config";
|
|
53
|
+
import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig } from "../../router/config";
|
|
54
54
|
import { resolveEnforcementMode } from "../../router/enforcement";
|
|
55
55
|
import { roleGuardProfile } from "../../router/guard-profile";
|
|
56
56
|
import { resolveRoles, type AuthorityAction, type RoleSpec } from "../../router/roles";
|
|
57
57
|
import { parseVerifyDirectives } from "../../verify/directives";
|
|
58
58
|
import { buildDelegationDoD } from "../../verify/dispatch";
|
|
59
59
|
import { requestedVerificationCwd, verificationScope } from "../roles/work-root";
|
|
60
|
+
import { resolveCheckPlacements } from "../roles/check-placement";
|
|
61
|
+
import { createRepoProbe, displaySafe, readSetPredicate } from "../roles/read-set";
|
|
60
62
|
import { effectiveDetection, effectiveFactsOf, grantFor, tierBounds, type DispatchGrant, type EffectiveDetection } from "../roles/policy";
|
|
61
63
|
import {
|
|
62
64
|
BINDING_NOTES, LOCAL_ACTIONS, currentBinding, evictCall, newDispatchNonce, noncePromptLine, nonceTitleSuffix, registerPending, type Binding,
|
|
63
65
|
} from "../roles/binding";
|
|
64
66
|
import { realpathSync } from "node:fs";
|
|
67
|
+
import { dirname } from "node:path";
|
|
68
|
+
// Static, not `await import`: dynamic imports made a bundle split src/router/config.ts into a chunk where its tiers.json lookup
|
|
69
|
+
// fails. admission.ts imports this module back; both sides use the other only inside functions.
|
|
70
|
+
import {
|
|
71
|
+
createAdmission, defaultAdmissionDeps, gitShowToplevel, type Admission, type AdmissionConfig, type AdmissionService, type RepoLocation,
|
|
72
|
+
} from "../roles/admission";
|
|
73
|
+
import { buildRoleDispatchHeader, stripDispatchHeader } from "../../router/dispatch-header";
|
|
74
|
+
import { addToWorkingSet, dropFromWorkingSets, workingSetOf } from "./working-set";
|
|
65
75
|
import {
|
|
66
76
|
consumeRunnerDispatch, consumeRunnerDispatchLoose, forgetDispatch, lookupDispatch, rememberDispatch, runnerDescription,
|
|
67
77
|
updateDispatchVerification, type CarriedVerification, type DetectionDepth, type DispatchInput, type DispatchRecord,
|
|
68
78
|
} from "../../router/sessions";
|
|
69
|
-
import type { ChangedFile } from "../../verify/dispatch";
|
|
79
|
+
import type { ChangedFile, TreeSnapshot } from "../../verify/dispatch";
|
|
80
|
+
import { branchSwitchReason, branchSwitched } from "../../verify/branch";
|
|
70
81
|
import type { ReferenceState } from "../../verify/types";
|
|
71
82
|
import { randomBytes } from "node:crypto";
|
|
72
83
|
import {
|
|
@@ -89,6 +100,138 @@ import {
|
|
|
89
100
|
} from "../outcomes/types";
|
|
90
101
|
import { agentModelRef, type AgentView } from "./host-info";
|
|
91
102
|
import { sessionRulesOf, type EngineRuntime, type Prepared, type RolePrepared, type WireLogger } from "./runtime";
|
|
103
|
+
import {
|
|
104
|
+
applyApproval, inspectCandidate, isApprovalValid, readApprovals, validApprovals, type ApprovalsEnv, type CandidateIdentity,
|
|
105
|
+
} from "../roles/approvals";
|
|
106
|
+
import { DEFAULT_REPO_APPROVAL_DAYS } from "../../router/roles-config";
|
|
107
|
+
|
|
108
|
+
// ── Cross-repo Phase 4: repositories approved with `/router approve` (docs/design/cross-repo-phase4-plan.md) ────────────────
|
|
109
|
+
|
|
110
|
+
/** The approval part of a D15 refusal waits at most this long for `inspectCandidate`; then the note stays as it is (SD-P4-8). */
|
|
111
|
+
export const APPROVAL_NOTE_TIMEOUT_MS = 8_000;
|
|
112
|
+
|
|
113
|
+
export interface ApprovalNoteOptions {
|
|
114
|
+
/** `routing.repoExclude`. */
|
|
115
|
+
readonly exclude?: readonly string[];
|
|
116
|
+
/** The approvals store environment (tests: an injected directory). */
|
|
117
|
+
readonly env?: ApprovalsEnv;
|
|
118
|
+
/** Default {@link inspectCandidate}; tests inject a fake. */
|
|
119
|
+
readonly inspect?: typeof inspectCandidate;
|
|
120
|
+
/** Default {@link APPROVAL_NOTE_TIMEOUT_MS}. */
|
|
121
|
+
readonly timeoutMs?: number;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The details of an approvable candidate, every field from git (`inspectCandidate`) and through `displaySafe` (SD-P4-8, -9). */
|
|
125
|
+
function approvalDetails(identity: CandidateIdentity): string {
|
|
126
|
+
const where = displaySafe(identity.path);
|
|
127
|
+
const head = displaySafe(identity.head).slice(0, 7) || "unknown";
|
|
128
|
+
const at = identity.branch === "(detached)" ? `detached at ${head}` : `branch ${displaySafe(identity.branch)} at ${head}`;
|
|
129
|
+
const command = /\s/.test(where) ? `/router approve "${where}"` : `/router approve ${where}`;
|
|
130
|
+
return `${where} is a git repository outside routing.repoParents (origin ${displaySafe(identity.origin)}, ${at}). `
|
|
131
|
+
+ `Only the user can approve it: ask the user to run ${command}, then dispatch again.`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Cross-repo Phase 4 (SD-P4-8, -9): the text appended to the D15 refusal of a dispatch whose admission refusal carries
|
|
136
|
+
* `approvable` (admission's canonical candidate). Built only from what `inspectCandidate` reports about that candidate — never
|
|
137
|
+
* from the dispatch text: its path, origin (credentials stripped), branch (or detached) at the short head, and the command the
|
|
138
|
+
* user types; or, when `inspectCandidate` names a problem, why no approval can be requested. Undefined — the note stays as it
|
|
139
|
+
* is — when the inspection throws or takes longer than {@link APPROVAL_NOTE_TIMEOUT_MS}. Never throws.
|
|
140
|
+
*/
|
|
141
|
+
export async function approvalNote(approvable: string, opts: ApprovalNoteOptions = {}): Promise<string | undefined> {
|
|
142
|
+
const inspect = opts.inspect ?? inspectCandidate;
|
|
143
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
144
|
+
try {
|
|
145
|
+
const timedOut = new Promise<undefined>((resolve) => {
|
|
146
|
+
timer = setTimeout(() => resolve(undefined), opts.timeoutMs ?? APPROVAL_NOTE_TIMEOUT_MS);
|
|
147
|
+
});
|
|
148
|
+
const inspected = inspect(approvable, { exclude: opts.exclude ?? [], ...(opts.env === undefined ? {} : { env: opts.env }) });
|
|
149
|
+
const found = await Promise.race([inspected, timedOut]);
|
|
150
|
+
if (found === undefined) return undefined;
|
|
151
|
+
if (typeof found === "string") {
|
|
152
|
+
const problem = found.trim().replace(/\.+$/, "");
|
|
153
|
+
return problem === "" ? undefined : `No approval can be requested for ${displaySafe(approvable)}: it ${displaySafe(problem)}.`;
|
|
154
|
+
}
|
|
155
|
+
return approvalDetails(found);
|
|
156
|
+
} catch {
|
|
157
|
+
return undefined;
|
|
158
|
+
} finally {
|
|
159
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Cross-repo Phase 4 (SD-P4-7): records the use of the approval `approvalPath` after a binding it backs — fire and forget: the
|
|
165
|
+
* entry's roots come from the store (read without git), `applyApproval` `touch` writes at most once per hour per path, only while
|
|
166
|
+
* the entry still has those roots and is valid, and never throws. Nothing here can fail the dispatch.
|
|
167
|
+
*/
|
|
168
|
+
export function touchApproval(approvalPath: string, days: number, env: ApprovalsEnv = {}): void {
|
|
169
|
+
try {
|
|
170
|
+
const entry = readApprovals(env).approvals.find((candidate) => candidate.path === approvalPath);
|
|
171
|
+
if (entry === undefined) return;
|
|
172
|
+
void applyApproval({ kind: "touch", path: entry.path, roots: entry.roots, days }, env).catch(() => undefined);
|
|
173
|
+
} catch {
|
|
174
|
+
// a failed touch never fails the dispatch
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Phase 4 QA (m2): why a binding backed by the approved path `approval` no longer binds, or undefined while that approval applies:
|
|
180
|
+
* read from the store without git (`readApprovals` + `isApprovalValid` with `days`); revoked, expired and an unreadable store
|
|
181
|
+
* (fail closed) all lapse.
|
|
182
|
+
*/
|
|
183
|
+
export function lapsedApprovalReason(
|
|
184
|
+
approval: string,
|
|
185
|
+
days: number,
|
|
186
|
+
env: ApprovalsEnv = {},
|
|
187
|
+
platform: NodeJS.Platform = process.platform,
|
|
188
|
+
): string | undefined {
|
|
189
|
+
let valid = false;
|
|
190
|
+
try {
|
|
191
|
+
const now = (env.now ?? Date.now)();
|
|
192
|
+
const key = normalizeRootText(approval, platform);
|
|
193
|
+
valid = readApprovals(env).approvals.some((entry) => normalizeRootText(entry.path, platform) === key && isApprovalValid(entry, days, now));
|
|
194
|
+
} catch {
|
|
195
|
+
valid = false;
|
|
196
|
+
}
|
|
197
|
+
return valid ? undefined : `approval for ${approval} was revoked or expired: no work root. Only the user can approve it again (/router approve ${approval}).`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Cross-repo Phase 4 (SD-P4-12): `locations` (a working set) without the entries backed by an approval that no longer applies
|
|
202
|
+
* (revoked, expired, or an unreadable store: fail closed), read from the store without git. The lapsed approvals are dropped from
|
|
203
|
+
* every working set too (`dropFromWorkingSets`), so the read set shrinks with them. No store I/O when no entry is backed by an
|
|
204
|
+
* approval.
|
|
205
|
+
*/
|
|
206
|
+
export function pruneLapsedApprovals(
|
|
207
|
+
locations: readonly RepoLocation[],
|
|
208
|
+
days: number,
|
|
209
|
+
env: ApprovalsEnv = {},
|
|
210
|
+
platform: NodeJS.Platform = process.platform,
|
|
211
|
+
): readonly RepoLocation[] {
|
|
212
|
+
if (!locations.some((location) => location.approval !== undefined)) return locations;
|
|
213
|
+
let valid: ReadonlySet<string>;
|
|
214
|
+
try {
|
|
215
|
+
const now = (env.now ?? Date.now)();
|
|
216
|
+
valid = new Set(readApprovals(env).approvals.filter((entry) => isApprovalValid(entry, days, now)).map((entry) => normalizeRootText(entry.path, platform)));
|
|
217
|
+
} catch {
|
|
218
|
+
valid = new Set();
|
|
219
|
+
}
|
|
220
|
+
const lapsed = new Set<string>();
|
|
221
|
+
const kept = locations.filter((location) => {
|
|
222
|
+
if (location.approval === undefined || valid.has(normalizeRootText(location.approval, platform))) return true;
|
|
223
|
+
lapsed.add(location.approval);
|
|
224
|
+
return false;
|
|
225
|
+
});
|
|
226
|
+
for (const approval of lapsed) {
|
|
227
|
+
try {
|
|
228
|
+
dropFromWorkingSets(approval, platform);
|
|
229
|
+
} catch {
|
|
230
|
+
// the entries are left out of `known` above in any case
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return kept;
|
|
234
|
+
}
|
|
92
235
|
|
|
93
236
|
/** A fresh dispatch can be claimed by a `session.created` event for at most this long. */
|
|
94
237
|
export const PENDING_TTL_MS = 120_000;
|
|
@@ -159,9 +302,11 @@ export interface RoleRouted {
|
|
|
159
302
|
readonly verifyRoot: string;
|
|
160
303
|
/** The route line's `root=` as written, or null. */
|
|
161
304
|
readonly requestedRoot: string | null;
|
|
162
|
-
/**
|
|
305
|
+
/** Grant and catalog notes (decision-row / diagnostic text; they are not shown in the dispatch header or the parent result). */
|
|
163
306
|
readonly notes: readonly string[];
|
|
164
307
|
readonly detection: EffectiveDetection;
|
|
308
|
+
/** The bounds reason includes `gated:authority`: gating lowered the final floor compared with strict. Absent otherwise. */
|
|
309
|
+
readonly gated?: true;
|
|
165
310
|
/** The dispatch's total call budget (`roleGuardProfile(spec, tier, routeLine.budget).budget`). */
|
|
166
311
|
readonly budget: number;
|
|
167
312
|
/** The route line's `budget=`, or null (pass it to `roleGuardProfile`, handoff 27). */
|
|
@@ -191,7 +336,7 @@ export interface RoleRouted {
|
|
|
191
336
|
|
|
192
337
|
/**
|
|
193
338
|
* #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
|
|
339
|
+
* route it, or a declared `repo=` / `branch=` / `root=` target the router refused — Q9). `route()` THROWS it — the one exception to "never throws" — so the adapter's `execute.before` fails the call with this
|
|
195
340
|
* message and the host never runs the child. It never falls back to a tier agent (QA-P12-1-5).
|
|
196
341
|
*/
|
|
197
342
|
export class RoleDispatchRefusal extends Error {
|
|
@@ -214,6 +359,8 @@ export const ROLE_REFUSALS = {
|
|
|
214
359
|
`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
360
|
failed: (detail: string): string => `the router could not route it (${detail}); retry, or dispatch a tier agent explicitly`,
|
|
216
361
|
session: (detail: string): string => `the dispatching session is unavailable (${detail}); retry`,
|
|
362
|
+
staleResume: (child: string): string =>
|
|
363
|
+
`resume refused: session ${child} belongs to a role dispatch this OpenCode process no longer tracks (lost in a restart, or already finished), so it would run unbound: local actions only, no work root. Dispatch a fresh task (same prompt and route line); do not resume this session.`,
|
|
217
364
|
} as const;
|
|
218
365
|
|
|
219
366
|
const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
|
|
@@ -224,6 +371,15 @@ const UNTOUCHED: RouteOutcome = Object.freeze({ mode: "static" });
|
|
|
224
371
|
*/
|
|
225
372
|
const RUNNER_CHILD_TITLE = /^Router (?:.+ delegation|result verification)$/;
|
|
226
373
|
|
|
374
|
+
/** Phase 2.1: the routing facts of one dispatch that the background and timing policy needs (`DispatchRouter.decisionOf`). */
|
|
375
|
+
export interface DispatchDecisionInfo {
|
|
376
|
+
readonly role: string | undefined;
|
|
377
|
+
readonly class: string;
|
|
378
|
+
readonly scope: string;
|
|
379
|
+
readonly tier: string | undefined;
|
|
380
|
+
readonly model: string | undefined;
|
|
381
|
+
}
|
|
382
|
+
|
|
227
383
|
export interface DispatchRouter {
|
|
228
384
|
/**
|
|
229
385
|
* Decide one `subagent` call. Writes and registers nothing: `commit` writes its decision row and registers it. Never throws, except
|
|
@@ -247,6 +403,12 @@ export interface DispatchRouter {
|
|
|
247
403
|
* row; nothing when the engine writes no rows or the dispatch is unknown. Never throws.
|
|
248
404
|
*/
|
|
249
405
|
noteBinding(childSessionID: string, binding: Pick<Binding, "kind" | "decisionID">): void;
|
|
406
|
+
/**
|
|
407
|
+
* Phase 2.1: what `route()` decided for a call, for the background and timing policy. Valid from `route()` until the call's result
|
|
408
|
+
* (`onCallResult`) or end (`onCallFinished`). `role` is the role agent (absent for a tier dispatch); `class` and `scope` are
|
|
409
|
+
* `"unknown"` when the engine knows none (`engine: static`). Undefined for a call `route()` did not act on. Never throws.
|
|
410
|
+
*/
|
|
411
|
+
decisionOf(callID: string): DispatchDecisionInfo | undefined;
|
|
250
412
|
/** Dispatches still waiting to be claimed (diagnostics, tests). */
|
|
251
413
|
pendingCount(): number;
|
|
252
414
|
/** Children registered by a wrong heuristic claim and not yet taken over by their own dispatch (diagnostics, tests). */
|
|
@@ -256,6 +418,19 @@ export interface DispatchRouter {
|
|
|
256
418
|
}
|
|
257
419
|
|
|
258
420
|
export interface DispatchRouterDeps {
|
|
421
|
+
/**
|
|
422
|
+
* Cross-repo (P1.4): builds the admission of a resolved `{ repoParents, repoDepth, repoExclude }` (once per triple); default
|
|
423
|
+
* `createAdmission` (`roles/admission.ts`). Tests inject a fake.
|
|
424
|
+
*/
|
|
425
|
+
readonly createAdmission?: (config: AdmissionConfig) => Pick<AdmissionService, "admit" | "resolve">;
|
|
426
|
+
/**
|
|
427
|
+
* Cross-repo Phase 4: the approvals store environment of the dispatch bind path (the D15 approval note, `touch` after an
|
|
428
|
+
* approval-backed binding, pruning lapsed approvals from the working set). Default: the real store. Tests inject a directory
|
|
429
|
+
* and a clock.
|
|
430
|
+
*/
|
|
431
|
+
readonly approvalsEnv?: ApprovalsEnv;
|
|
432
|
+
/** Cross-repo Phase 4 (SD-P4-8): `inspectCandidate` for the D15 approval note; tests inject a fake. */
|
|
433
|
+
readonly inspectCandidate?: typeof inspectCandidate;
|
|
259
434
|
readonly runtime: EngineRuntime;
|
|
260
435
|
/** `ctx.session.get({ sessionID })`. */
|
|
261
436
|
readonly getSession: (sessionID: string) => Promise<unknown>;
|
|
@@ -270,6 +445,11 @@ export interface DispatchRouterDeps {
|
|
|
270
445
|
* {@link gitWorktreeList} (the hardened spawn, 5 s timeout). Injected by tests.
|
|
271
446
|
*/
|
|
272
447
|
readonly listWorktrees?: (cwd: string) => Promise<string>;
|
|
448
|
+
/**
|
|
449
|
+
* Cross-repo QA round 2: hardened `git rev-parse --show-toplevel` in `cwd` (default `gitShowToplevel`, `roles/admission.ts`), used
|
|
450
|
+
* to check that the session directory belongs to the bound worktree before it stays the work root. Injected by tests.
|
|
451
|
+
*/
|
|
452
|
+
readonly showToplevel?: (cwd: string) => Promise<string | undefined>;
|
|
273
453
|
/** #84 P2.1: canonical long form of an existing path (default `realpathSync.native`). Only called on an already matched root. */
|
|
274
454
|
readonly realpath?: (path: string) => string;
|
|
275
455
|
/** #84 P2.1: path rules of the work-root comparison (default `process.platform`). */
|
|
@@ -365,7 +545,7 @@ function claimCall(key: string): boolean {
|
|
|
365
545
|
}
|
|
366
546
|
|
|
367
547
|
/** Bound on children with pending subagent-result annotations (oldest dropped first). */
|
|
368
|
-
export const MAX_ANNOTATED_CHILDREN =
|
|
548
|
+
export const MAX_ANNOTATED_CHILDREN = 1024 /* >= MAX_LIVE_ATTEMPTS: background children collect annotations for hours */;
|
|
369
549
|
/** Bound on annotations kept per child (oldest dropped first). */
|
|
370
550
|
export const MAX_ANNOTATIONS_PER_CHILD = 8;
|
|
371
551
|
|
|
@@ -506,8 +686,31 @@ export interface WorkRootResolution {
|
|
|
506
686
|
readonly workRoot: string | null;
|
|
507
687
|
/** The route line's `root=` as written, or null. */
|
|
508
688
|
readonly requested: string | null;
|
|
509
|
-
/** Why there is no work root
|
|
689
|
+
/** Why there is no work root; null when resolved. A dispatch that declared `repo=`/`branch=`/`root=` is refused with this note (Q9). */
|
|
510
690
|
readonly note: string | null;
|
|
691
|
+
/** Cross-repo (P1.4): where the work root lies, when admission bound it. */
|
|
692
|
+
readonly location?: RepoLocation;
|
|
693
|
+
/**
|
|
694
|
+
* Cross-repo Phase 4 (SD-P4-8): the canonical candidate of an admission refusal that a human could approve with
|
|
695
|
+
* `/router approve` (admission's `approvable`). Set only with `workRoot: null`; the dispatch bind path turns it into a note.
|
|
696
|
+
*/
|
|
697
|
+
readonly approvable?: string;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Cross-repo (P1.4): what admission needs to bind a role dispatch's work root. Without `admission`, `resolveRoleWorkRoot` is
|
|
702
|
+
* today's text match (invariant I9).
|
|
703
|
+
*/
|
|
704
|
+
export interface WorkRootAdmissionInput {
|
|
705
|
+
/** The route line's `repo=`, as written. */
|
|
706
|
+
readonly repo?: string | null | undefined;
|
|
707
|
+
/** The route line's `branch=`, as written. */
|
|
708
|
+
readonly branch?: string | null | undefined;
|
|
709
|
+
readonly admission?: Pick<AdmissionService, "admit" | "resolve"> | undefined;
|
|
710
|
+
/** The session repository; the session directory when absent. */
|
|
711
|
+
readonly sessionRepository?: string | undefined;
|
|
712
|
+
/** Repositories whose worktrees are admissible by rule 2 (the session directory, the working set). */
|
|
713
|
+
readonly known?: readonly string[] | undefined;
|
|
511
714
|
}
|
|
512
715
|
|
|
513
716
|
export interface WorkRootDeps {
|
|
@@ -544,12 +747,15 @@ export async function gitWorktreeList(cwd: string): Promise<string> {
|
|
|
544
747
|
* - no `root=` → the session directory (canonical long form);
|
|
545
748
|
* - `root=` → its normalised TEXT is compared with the session directory and with every worktree of `git worktree list --porcelain`
|
|
546
749
|
* (run in the session directory) BEFORE any filesystem call on it; a match → the canonical long form of the matched entry;
|
|
750
|
+
* with an admission (cross-repo), any `root=` other than the session directory binds only through `admission.admit`
|
|
751
|
+
* (QA round 1, F1), and an admitted worktree binds only while its `realpath` still equals it (F8);
|
|
547
752
|
* - anything else (no match, git unavailable, an entry that does not resolve) → `workRoot: null` with a note.
|
|
548
753
|
* Never throws.
|
|
549
754
|
*/
|
|
550
755
|
export async function resolveRoleWorkRoot(
|
|
551
756
|
input: { readonly root: string | null; readonly sessionDirectory: string },
|
|
552
757
|
deps: WorkRootDeps,
|
|
758
|
+
cross?: WorkRootAdmissionInput,
|
|
553
759
|
): Promise<WorkRootResolution> {
|
|
554
760
|
const canonical = (path: string): string | null => {
|
|
555
761
|
try {
|
|
@@ -559,6 +765,39 @@ export async function resolveRoleWorkRoot(
|
|
|
559
765
|
return null;
|
|
560
766
|
}
|
|
561
767
|
};
|
|
768
|
+
// Cross-repo (P1.4): admission binds `repo=` / `branch=` (with or without `root=`), and a `root=` the text match below did not find.
|
|
769
|
+
const admission = cross?.admission;
|
|
770
|
+
const sessionRepository = cross?.sessionRepository ?? input.sessionDirectory;
|
|
771
|
+
const known = [...new Set([sessionRepository, ...(cross?.known ?? [])])];
|
|
772
|
+
const admitted = async (run: () => Promise<Admission>): Promise<WorkRootResolution> => {
|
|
773
|
+
let result: Admission;
|
|
774
|
+
try {
|
|
775
|
+
result = await run();
|
|
776
|
+
} catch (error) {
|
|
777
|
+
result = { ok: false, reason: `admission failed: ${describeError(error)}: no work root.` };
|
|
778
|
+
}
|
|
779
|
+
if (!result.ok) {
|
|
780
|
+
const approvable = result.approvable;
|
|
781
|
+
return approvable === undefined
|
|
782
|
+
? { workRoot: null, requested: input.root, note: result.reason }
|
|
783
|
+
: { workRoot: null, requested: input.root, note: result.reason, approvable };
|
|
784
|
+
}
|
|
785
|
+
const resolved = canonical(result.location.worktree);
|
|
786
|
+
if (resolved === null) return { workRoot: null, requested: input.root, note: `${result.location.worktree} does not resolve on disk: no work root` };
|
|
787
|
+
// QA round 1 (F8): the admitted worktree is canonical; one that now resolves elsewhere (a link swapped in since) binds nothing.
|
|
788
|
+
if (normalizeRootText(resolved, deps.platform) !== normalizeRootText(result.location.worktree, deps.platform)) {
|
|
789
|
+
return { workRoot: null, requested: input.root, note: `the admitted work root ${result.location.worktree} now resolves to ${resolved}: no work root` };
|
|
790
|
+
}
|
|
791
|
+
return { workRoot: resolved, requested: input.root, note: null, location: result.location };
|
|
792
|
+
};
|
|
793
|
+
const repo = cross?.repo?.trim() || undefined;
|
|
794
|
+
const branch = cross?.branch?.trim() || undefined;
|
|
795
|
+
if (admission !== undefined && (repo !== undefined || branch !== undefined)) {
|
|
796
|
+
return admitted(() => admission.resolve(
|
|
797
|
+
{ ...(input.root === null ? {} : { root: input.root }), ...(repo === undefined ? {} : { repo }), ...(branch === undefined ? {} : { branch }) },
|
|
798
|
+
{ sessionRepository, known },
|
|
799
|
+
));
|
|
800
|
+
}
|
|
562
801
|
if (input.root === null) {
|
|
563
802
|
const dir = canonical(input.sessionDirectory);
|
|
564
803
|
return dir === null
|
|
@@ -577,6 +816,12 @@ export async function resolveRoleWorkRoot(
|
|
|
577
816
|
match = listed.find((path) => normalizeRootText(path, deps.platform) === want);
|
|
578
817
|
}
|
|
579
818
|
const none = `root=${input.root} is neither the session directory nor a worktree listed by \`git worktree list --porcelain\`: no work root`;
|
|
819
|
+
// QA round 1 (F1): with an admission, a worktree the session repository lists is a work root only if admission admits it too
|
|
820
|
+
// (routing.repoExclude, links, parents); the session directory itself keeps today's match (I9).
|
|
821
|
+
if (admission !== undefined && match !== input.sessionDirectory) {
|
|
822
|
+
const root = input.root;
|
|
823
|
+
return admitted(() => admission.admit(root, known, sessionRepository));
|
|
824
|
+
}
|
|
580
825
|
if (match === undefined) return { workRoot: null, requested: input.root, note: none };
|
|
581
826
|
const resolved = canonical(match);
|
|
582
827
|
return resolved === null
|
|
@@ -636,7 +881,8 @@ export function roleVerificationRuns(input: {
|
|
|
636
881
|
/**
|
|
637
882
|
* QA-P21-1-2: the dispatch's verification would be deferred, exactly as the native path decides it (index.ts `isDeferred` →
|
|
638
883
|
* 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
|
|
884
|
+
* none; the text is `dispatchDirectiveText(prompt, description)`) AND its DoD carries a `testsPass` check (with or without
|
|
885
|
+
* per-check `cwd=`/`scope=` keys: the classification does not depend on where a check runs). A deferred dispatch
|
|
640
886
|
* returns without the gate (`router_verify` runs it later), so the router's gate cannot back a `deterministic` detection.
|
|
641
887
|
* Fails toward "deferred" on any error (a weaker detection, never a stronger one). QA-P21-2 nit 3: nothing is deferred when
|
|
642
888
|
* `router_verify` is not registered (`verifyEnabled: false`, index.ts `routerVerifyEnabled`): the gate then runs at the return.
|
|
@@ -668,10 +914,17 @@ export function roleGateDeferred(cfg: RouterConfig, prompt: string, description:
|
|
|
668
914
|
* only the return shows (every change outside the work root, a timeout, a verifier error) does not rewrite the row — its verdict
|
|
669
915
|
* carries the caveat (`[router ⚠ UNVERIFIED …]`) and is never accepted as verified.
|
|
670
916
|
*/
|
|
671
|
-
export function roleGateOutsideWorkRoot(
|
|
917
|
+
export function roleGateOutsideWorkRoot(
|
|
918
|
+
workRoot: string | null, prompt: string, description: string, argsCwd?: unknown, inReadSet?: (absPath: string) => boolean,
|
|
919
|
+
): boolean {
|
|
672
920
|
if (workRoot === null) return true;
|
|
673
921
|
try {
|
|
674
|
-
|
|
922
|
+
const dod = buildDelegationDoD({ prompt, description });
|
|
923
|
+
const scope = verificationScope(requestedVerificationCwd(argsCwd, dod.cwd), workRoot);
|
|
924
|
+
if (scope.outside) return true;
|
|
925
|
+
// P2.5 (SD4): a check's own `cwd=` / `scope=` must resolve too (inside W, or an absolute path in the read set R `inReadSet`);
|
|
926
|
+
// one that is refused makes the gate refuse the delegation, so the router's gate cannot back `deterministic`.
|
|
927
|
+
return resolveCheckPlacements(dod, scope, inReadSet === undefined ? {} : { inReadSet }).refused !== undefined;
|
|
675
928
|
} catch {
|
|
676
929
|
return true;
|
|
677
930
|
}
|
|
@@ -837,7 +1090,7 @@ function higherTier(order: readonly string[], a: string | null, b: string | null
|
|
|
837
1090
|
* cannot touch it: binding.ts holds its enforced grant), so the verification root, the outside-root check and the classification
|
|
838
1091
|
* never use it.
|
|
839
1092
|
*/
|
|
840
|
-
function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
|
|
1093
|
+
export function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityAction[]): DispatchGrant {
|
|
841
1094
|
const root = boundGrant.workRoot;
|
|
842
1095
|
const actions = new Set<AuthorityAction>([...boundGrant.actions, ...widened]);
|
|
843
1096
|
if (boundGrant.workRoot === null) {
|
|
@@ -846,7 +1099,9 @@ function resumedGrant(boundGrant: DispatchGrant, widened: readonly AuthorityActi
|
|
|
846
1099
|
actions.delete("router_run");
|
|
847
1100
|
actions.delete("edit");
|
|
848
1101
|
}
|
|
849
|
-
|
|
1102
|
+
// QA round 1 (F10): the location travels only with a validated work root, the bound one (binding.ts `locationOf`).
|
|
1103
|
+
const location = root !== null && root === boundGrant.workRoot && boundGrant.location !== undefined ? { location: boundGrant.location } : {};
|
|
1104
|
+
return { actions, notes: [...boundGrant.notes], workRoot: root, ...location };
|
|
850
1105
|
}
|
|
851
1106
|
|
|
852
1107
|
/** verify/dod.ts `OPEN_TAG_RE` / `CLOSE_TAG_RE`: the lines that open and close an `[acceptance]` block. */
|
|
@@ -895,6 +1150,19 @@ export interface RoleAttemptChanges {
|
|
|
895
1150
|
readonly changedFiles: ChangedFile[];
|
|
896
1151
|
readonly changeBaseline: "available" | "unavailable";
|
|
897
1152
|
readonly reference: ReferenceState;
|
|
1153
|
+
readonly snapshot?: Pick<TreeSnapshot, "cwd" | "root" | "head" | "branch"> | undefined;
|
|
1154
|
+
readonly branchSwitch?: string | undefined;
|
|
1155
|
+
readonly unattributedWriters?: string[] | undefined;
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** QA2 F3c: a "cannot confirm the branch" reason (an unreadable tree), as opposed to an observed switch. */
|
|
1159
|
+
function isUnconfirmedBranch(reason: string): boolean {
|
|
1160
|
+
return reason.startsWith("cannot confirm the branch of ");
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/** I5 (P0.3): the sorted union of two writer lists. */
|
|
1164
|
+
function unionWriters(older: readonly string[] | undefined, newer: readonly string[] | undefined): string[] {
|
|
1165
|
+
return [...new Set([...(older ?? []), ...(newer ?? [])])].sort();
|
|
898
1166
|
}
|
|
899
1167
|
|
|
900
1168
|
/** The union of two change sets, keyed by path (separators unified, case folded on win32); `newer` wins. */
|
|
@@ -921,19 +1189,50 @@ export function roleAttemptVerification<T extends RoleAttemptChanges>(childSessi
|
|
|
921
1189
|
const verification = lookupDispatch(childSessionID)?.verification;
|
|
922
1190
|
if (verification === undefined) return prepared;
|
|
923
1191
|
const own: readonly ChangedFile[] | "unavailable" = prepared.changeBaseline === "available" ? prepared.changedFiles : "unavailable";
|
|
1192
|
+
const now = prepared.snapshot;
|
|
924
1193
|
if (!opts.carried) {
|
|
925
|
-
|
|
1194
|
+
const tree = now === undefined ? {} : { tree: { head: now.head, ...(now.branch === undefined ? {} : { branch: now.branch }), root: now.root ?? now.cwd } };
|
|
1195
|
+
// QA2 F3c: an attempt that only could not confirm its branch is not a switch of the lineage (a later attempt with a
|
|
1196
|
+
// readable tree is judged on its own); only a real switch is recorded and inherited.
|
|
1197
|
+
const switched = prepared.branchSwitch === undefined || isUnconfirmedBranch(prepared.branchSwitch) ? {} : { switched: prepared.branchSwitch };
|
|
1198
|
+
const ownWriters = unionWriters(undefined, prepared.unattributedWriters);
|
|
1199
|
+
const writers = ownWriters.length === 0 ? {} : { writers: ownWriters };
|
|
1200
|
+
updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: prepared.reference, changed: own, ...tree, ...switched, ...writers } });
|
|
926
1201
|
return prepared;
|
|
927
1202
|
}
|
|
928
1203
|
const baseline = verification.baseline;
|
|
929
1204
|
if (baseline === undefined) return { ...prepared, changeBaseline: "unavailable", reference: CARRIED_NO_REFERENCE };
|
|
930
1205
|
const changed = unionChanges(baseline.changed, own);
|
|
931
|
-
|
|
1206
|
+
// I5 (P0.3): a write an earlier attempt made through a tool the router cannot observe is part of the carried change too.
|
|
1207
|
+
const lineageWriters = unionWriters(baseline.writers, prepared.unattributedWriters);
|
|
1208
|
+
// I7 across attempts. Precedence: a switch seen during this dispatch, then one inherited from an earlier attempt,
|
|
1209
|
+
// then a switch between the introducing attempt's tree and this one.
|
|
1210
|
+
const computedSwitch = prepared.branchSwitch !== undefined || baseline.switched !== undefined ? undefined
|
|
1211
|
+
: baseline.tree !== undefined && now !== undefined && branchSwitched(baseline.tree, now)
|
|
1212
|
+
? branchSwitchReason(now.root ?? now.cwd, baseline.tree, now, "since the attempt that introduced this acceptance") : undefined;
|
|
1213
|
+
// B3: the first switch the lineage finds is recorded, so every later carried attempt inherits it.
|
|
1214
|
+
const ownSwitch = prepared.branchSwitch !== undefined && !isUnconfirmedBranch(prepared.branchSwitch) ? prepared.branchSwitch : undefined;
|
|
1215
|
+
const recordedSwitch = baseline.switched ?? ownSwitch ?? computedSwitch;
|
|
1216
|
+
updateDispatchVerification(childSessionID, { ...verification, baseline: { reference: baseline.reference, changed,
|
|
1217
|
+
...(baseline.tree === undefined ? {} : { tree: baseline.tree }),
|
|
1218
|
+
...(recordedSwitch === undefined ? {} : { switched: recordedSwitch }),
|
|
1219
|
+
...(lineageWriters.length === 0 ? {} : { writers: lineageWriters }) } });
|
|
1220
|
+
const INHERITED_PREFIX = "in an earlier attempt of this acceptance: ";
|
|
1221
|
+
// B11: a switch inherited from an earlier attempt says so (once); one found by this attempt is returned as it is.
|
|
1222
|
+
const lineageSwitch = prepared.branchSwitch !== undefined ? undefined
|
|
1223
|
+
: baseline.switched !== undefined ? (baseline.switched.startsWith(INHERITED_PREFIX) ? baseline.switched : `${INHERITED_PREFIX}${baseline.switched}`)
|
|
1224
|
+
: computedSwitch !== undefined ? computedSwitch
|
|
1225
|
+
// B9: a recorded branch but no current snapshot: this attempt cannot be confirmed to be on it.
|
|
1226
|
+
: baseline.tree?.branch !== undefined && now === undefined
|
|
1227
|
+
? `cannot confirm the branch of ${baseline.tree.root ?? "the work root"}: the working tree could not be read for this carried attempt, so the checks could verify another branch. Send a fresh [acceptance] block, or re-dispatch.`
|
|
1228
|
+
: undefined;
|
|
932
1229
|
return {
|
|
933
1230
|
...prepared,
|
|
934
1231
|
changedFiles: changed === "unavailable" ? prepared.changedFiles : changed,
|
|
935
1232
|
changeBaseline: changed === "unavailable" ? "unavailable" : "available",
|
|
936
1233
|
reference: baseline.reference,
|
|
1234
|
+
...(lineageSwitch === undefined ? {} : { branchSwitch: lineageSwitch }),
|
|
1235
|
+
...(lineageWriters.length === 0 ? {} : { unattributedWriters: lineageWriters }),
|
|
937
1236
|
};
|
|
938
1237
|
}
|
|
939
1238
|
|
|
@@ -1078,7 +1377,7 @@ function factsOf(facts: TaskFacts): DecisionRow["facts"] {
|
|
|
1078
1377
|
return { class: facts.class, risk: facts.risk, scope: facts.scope, needs: [...facts.needs], confidence: facts.confidence, source: facts.source };
|
|
1079
1378
|
}
|
|
1080
1379
|
|
|
1081
|
-
function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTrace {
|
|
1380
|
+
function traceOf(result: ClassifyResult, argmin: RouteChoice | null, riskSources?: DecisionTrace["riskSources"]): DecisionTrace {
|
|
1082
1381
|
const { routeLines, backend, backendSkipped } = result.trace;
|
|
1083
1382
|
return {
|
|
1084
1383
|
routeLines: { count: routeLines.count, conflict: routeLines.conflict, edgeOnly: routeLines.edgeOnly },
|
|
@@ -1094,6 +1393,7 @@ function traceOf(result: ClassifyResult, argmin: RouteChoice | null): DecisionTr
|
|
|
1094
1393
|
},
|
|
1095
1394
|
...(backendSkipped === undefined ? {} : { backendSkipped }),
|
|
1096
1395
|
...(argmin === null ? {} : { argmin }),
|
|
1396
|
+
...(riskSources === undefined ? {} : { riskSources }),
|
|
1097
1397
|
};
|
|
1098
1398
|
}
|
|
1099
1399
|
|
|
@@ -1168,6 +1468,13 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1168
1468
|
const instanceNonce = randomBytes(8).toString("hex");
|
|
1169
1469
|
/** Between `route()` and `commit()`. */
|
|
1170
1470
|
const decided = new Map<string, Decided>();
|
|
1471
|
+
/** Phase 2.1: the routing facts of a routed call, until its result or end (`decisionOf`). Bounded like the other per-call maps. */
|
|
1472
|
+
const decisionInfos = new Map<string, DispatchDecisionInfo>();
|
|
1473
|
+
const noteDecision = (callID: string, info: DispatchDecisionInfo): void => {
|
|
1474
|
+
decisionInfos.delete(callID);
|
|
1475
|
+
decisionInfos.set(callID, info);
|
|
1476
|
+
while (decisionInfos.size > MAX_HANDLED_CALLS) decisionInfos.delete(decisionInfos.keys().next().value as string);
|
|
1477
|
+
};
|
|
1171
1478
|
/** Committed dispatches, in insertion order, until their call ends. */
|
|
1172
1479
|
const entries = new Map<string, Entry>();
|
|
1173
1480
|
/**
|
|
@@ -1467,6 +1774,228 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1467
1774
|
platform: deps.platform ?? process.platform,
|
|
1468
1775
|
};
|
|
1469
1776
|
|
|
1777
|
+
// QA round 2: the hardened `git rev-parse --show-toplevel` of admission; tests inject a fake.
|
|
1778
|
+
const showToplevel = async (cwd: string): Promise<string | undefined> =>
|
|
1779
|
+
deps.showToplevel !== undefined ? deps.showToplevel(cwd) : gitShowToplevel(cwd);
|
|
1780
|
+
|
|
1781
|
+
// Cross-repo P2.5: the read set R of this dispatch's role session beyond its work root, for the per-check `cwd=` roots the gate
|
|
1782
|
+
// places (the same inputs as the read guard: the dispatching session's working set, `routing.repoParents/Depth/Exclude`, one
|
|
1783
|
+
// cached probe). Undefined when R adds nothing, or on any error: only roots inside W are valid (fail closed).
|
|
1784
|
+
const readSetProbe = createRepoProbe();
|
|
1785
|
+
const readSetFor = (cfg: RouterConfig, orchestratorSessionID: string): ((absPath: string) => boolean) | undefined => {
|
|
1786
|
+
try {
|
|
1787
|
+
const routing = resolveRolesRouting(cfg, "v2");
|
|
1788
|
+
const inSet = readSetPredicate(
|
|
1789
|
+
{ parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude }, workingSetOf(orchestratorSessionID), readSetProbe,
|
|
1790
|
+
);
|
|
1791
|
+
return inSet === undefined ? undefined : (absPath) => inSet(absPath) !== undefined;
|
|
1792
|
+
} catch {
|
|
1793
|
+
return undefined;
|
|
1794
|
+
}
|
|
1795
|
+
};
|
|
1796
|
+
|
|
1797
|
+
/** The real admission; with an injected {@link DispatchRouterDeps.approvalsEnv}, its rule 3 reads that store (Phase 4). */
|
|
1798
|
+
const defaultAdmission = async (config: AdmissionConfig): Promise<Pick<AdmissionService, "admit" | "resolve">> => {
|
|
1799
|
+
const env = deps.approvalsEnv;
|
|
1800
|
+
if (env === undefined) return createAdmission(config);
|
|
1801
|
+
const days = config.approvalDays ?? DEFAULT_REPO_APPROVAL_DAYS;
|
|
1802
|
+
return createAdmission(config, { ...defaultAdmissionDeps({ approvalDays: days }), approvals: () => validApprovals(days, env) });
|
|
1803
|
+
};
|
|
1804
|
+
|
|
1805
|
+
// Cross-repo (P1.4): one admission per resolved `{ repoParents, repoDepth, repoExclude, repoApprovalDays }` (it caches its git
|
|
1806
|
+
// results for 5 s).
|
|
1807
|
+
let admissionMemo: { readonly key: string; readonly service: Pick<AdmissionService, "admit" | "resolve"> } | undefined;
|
|
1808
|
+
const admissionFor = async (config: AdmissionConfig): Promise<Pick<AdmissionService, "admit" | "resolve">> => {
|
|
1809
|
+
const key = JSON.stringify([config.parents, config.depth, config.exclude, config.approvalDays ?? null]);
|
|
1810
|
+
if (admissionMemo !== undefined && admissionMemo.key === key) return admissionMemo.service;
|
|
1811
|
+
const service = deps.createAdmission !== undefined ? deps.createAdmission(config) : await defaultAdmission(config);
|
|
1812
|
+
admissionMemo = { key, service };
|
|
1813
|
+
return service;
|
|
1814
|
+
};
|
|
1815
|
+
|
|
1816
|
+
/**
|
|
1817
|
+
* Cross-repo (P1.4): the admission input of a role dispatch. Undefined — today's text match, nothing else (I9) — unless roles mode
|
|
1818
|
+
* is active on v2 and `routing.repoParents` is set or the route line declares `repo=` / `branch=` (`branch=` alone needs no parent:
|
|
1819
|
+
* the session repository answers it). `known`: the session directory and the worktrees of the orchestrator's working set.
|
|
1820
|
+
*/
|
|
1821
|
+
const crossRepoOf = async (
|
|
1822
|
+
cfg: RouterConfig,
|
|
1823
|
+
orchestratorSessionID: string,
|
|
1824
|
+
sessionDirectory: string,
|
|
1825
|
+
line: Pick<RouteLine, "repo" | "branch"> | null | undefined,
|
|
1826
|
+
): Promise<WorkRootAdmissionInput | undefined> => {
|
|
1827
|
+
const routing = resolveRolesRouting(cfg, "v2");
|
|
1828
|
+
const repo = line?.repo ?? undefined;
|
|
1829
|
+
const branch = line?.branch ?? undefined;
|
|
1830
|
+
if (routing.delegation !== "roles") return undefined;
|
|
1831
|
+
if (routing.repoParents.length === 0 && repo === undefined && branch === undefined) return undefined;
|
|
1832
|
+
const admission = await admissionFor({
|
|
1833
|
+
parents: routing.repoParents,
|
|
1834
|
+
depth: routing.repoDepth,
|
|
1835
|
+
exclude: routing.repoExclude,
|
|
1836
|
+
approvalDays: routing.repoApprovalDays,
|
|
1837
|
+
});
|
|
1838
|
+
// Phase 4 (SD-P4-12): a working-set entry whose approval lapsed (revoked, expired) is dropped before it can admit by rule 2;
|
|
1839
|
+
// a store read without git, only with parents (I9) and only when an entry is backed by an approval. Phase 4 QA (M1): with the
|
|
1840
|
+
// parents emptied at runtime no approval applies (the store is not read), so an approval-backed entry is left out; admission's
|
|
1841
|
+
// rule 2 then admits only worktrees of the session repository.
|
|
1842
|
+
const workingSet = routing.repoParents.length === 0
|
|
1843
|
+
? workingSetOf(orchestratorSessionID).filter((location) => location.approval === undefined)
|
|
1844
|
+
: pruneLapsedApprovals(workingSetOf(orchestratorSessionID), routing.repoApprovalDays, deps.approvalsEnv, workRootDeps.platform);
|
|
1845
|
+
const known = [...new Set([sessionDirectory, ...workingSet.map((location) => location.worktree)])];
|
|
1846
|
+
return { repo, branch, admission, sessionRepository: sessionDirectory, known };
|
|
1847
|
+
};
|
|
1848
|
+
|
|
1849
|
+
/** `child` lies strictly below `parent` (text comparison, no filesystem call). */
|
|
1850
|
+
const strictlyWithin = (parent: string, child: string): boolean => {
|
|
1851
|
+
const platform = workRootDeps.platform;
|
|
1852
|
+
const p = normalizeRootText(parent, platform);
|
|
1853
|
+
const c = normalizeRootText(child, platform);
|
|
1854
|
+
const sep = platform === "win32" ? "\\" : "/";
|
|
1855
|
+
return c.length > p.length && c.startsWith(p.endsWith(sep) ? p : p + sep);
|
|
1856
|
+
};
|
|
1857
|
+
|
|
1858
|
+
/**
|
|
1859
|
+
* The work root of a role dispatch: {@link resolveRoleWorkRoot} plus the route-flow rules of the cross-repo QA (round 1).
|
|
1860
|
+
* - F3: a `repo=` / `branch=` / `root=` the route line declared but the parser rejected (invalid value, bare key, duplicate or
|
|
1861
|
+
* conflicting key) gives NO work root and a note, never the session directory (design §5).
|
|
1862
|
+
* - F6: a `root=` that is the session directory, with `branch=`, is accepted when the worktree on that branch contains it (the
|
|
1863
|
+
* session may have started in a subdirectory); and a worktree bound without `root=` that contains the session directory keeps
|
|
1864
|
+
* the session directory as the work root (the write root does not grow to the worktree's top level).
|
|
1865
|
+
*/
|
|
1866
|
+
const bindWorkRoot = async (
|
|
1867
|
+
cfg: RouterConfig,
|
|
1868
|
+
orchestratorSessionID: string,
|
|
1869
|
+
sessionDirectory: string,
|
|
1870
|
+
line: RouteLine | null | undefined,
|
|
1871
|
+
): Promise<WorkRootResolution> => {
|
|
1872
|
+
const declaredRoot = line?.root ?? null;
|
|
1873
|
+
const invalid = line?.invalidCrossRepo ?? [];
|
|
1874
|
+
if (invalid.length > 0) {
|
|
1875
|
+
const note = invalid
|
|
1876
|
+
.map(({ key, value }) => `${key}=${value} is not a valid ${key === "repo" ? "repository name" : key === "branch" ? "branch name" : "absolute work root"}: no work root. Fix the route line.`)
|
|
1877
|
+
.join(" ");
|
|
1878
|
+
return { workRoot: null, requested: declaredRoot, note };
|
|
1879
|
+
}
|
|
1880
|
+
const cross = await crossRepoOf(cfg, orchestratorSessionID, sessionDirectory, line);
|
|
1881
|
+
const first = await resolveRoleWorkRoot({ root: declaredRoot, sessionDirectory }, workRootDeps, cross);
|
|
1882
|
+
const canonicalSession = (): string | null => {
|
|
1883
|
+
try {
|
|
1884
|
+
const resolved = workRootDeps.realpath(sessionDirectory);
|
|
1885
|
+
return typeof resolved === "string" && resolved !== "" ? resolved : null;
|
|
1886
|
+
} catch {
|
|
1887
|
+
return null;
|
|
1888
|
+
}
|
|
1889
|
+
};
|
|
1890
|
+
const platform = workRootDeps.platform;
|
|
1891
|
+
/**
|
|
1892
|
+
* QA round 2: `worktree` holds the session directory — not merely by text: a worktree or repository NESTED inside `worktree`
|
|
1893
|
+
* (`.worktrees/`, `.claude/worktrees/`) lies below it too. Walking up from the canonical session directory to `worktree`, the
|
|
1894
|
+
* first directory that is itself a git top level (hardened `rev-parse --show-toplevel`, whose ceiling is the directory's parent,
|
|
1895
|
+
* so a plain subdirectory answers nothing) must be `worktree`; any other top level on the way, or anything unreadable, is "no".
|
|
1896
|
+
*/
|
|
1897
|
+
const sessionBelongsTo = async (worktree: string): Promise<boolean> => {
|
|
1898
|
+
if (!strictlyWithin(worktree, sessionDirectory)) return false;
|
|
1899
|
+
const start = canonicalSession();
|
|
1900
|
+
if (start === null) return false;
|
|
1901
|
+
try {
|
|
1902
|
+
const bound = normalizeRootText(workRootDeps.realpath(worktree), platform);
|
|
1903
|
+
let dir = start;
|
|
1904
|
+
for (let depth = 0; depth < 64; depth++) {
|
|
1905
|
+
const here = normalizeRootText(dir, platform);
|
|
1906
|
+
if (here === bound) return true;
|
|
1907
|
+
if (!strictlyWithin(bound, here)) return false;
|
|
1908
|
+
const top = await showToplevel(dir);
|
|
1909
|
+
if (top !== undefined && top !== "" && normalizeRootText(workRootDeps.realpath(top), platform) === here) return false;
|
|
1910
|
+
const parent = dirname(dir);
|
|
1911
|
+
if (parent === dir) return false;
|
|
1912
|
+
dir = parent;
|
|
1913
|
+
}
|
|
1914
|
+
return false;
|
|
1915
|
+
} catch {
|
|
1916
|
+
return false;
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
const atSession = declaredRoot !== null && line?.branch !== undefined && cross?.admission !== undefined
|
|
1920
|
+
&& normalizeRootText(declaredRoot, platform) === normalizeRootText(sessionDirectory, platform);
|
|
1921
|
+
if (atSession && first.workRoot === null) {
|
|
1922
|
+
// The session directory may be inside a worktree rather than its top level: bind by branch, then check it holds the session.
|
|
1923
|
+
const retry = await resolveRoleWorkRoot({ root: null, sessionDirectory }, workRootDeps, cross);
|
|
1924
|
+
const inside = retry.location !== undefined && retry.workRoot !== null && await sessionBelongsTo(retry.location.worktree);
|
|
1925
|
+
const dir = inside ? canonicalSession() : null;
|
|
1926
|
+
return dir === null ? first : { ...retry, workRoot: dir, requested: declaredRoot };
|
|
1927
|
+
}
|
|
1928
|
+
if (declaredRoot === null && first.workRoot !== null && first.location !== undefined && await sessionBelongsTo(first.location.worktree)) {
|
|
1929
|
+
const dir = canonicalSession();
|
|
1930
|
+
if (dir !== null) return { ...first, workRoot: dir };
|
|
1931
|
+
}
|
|
1932
|
+
return first;
|
|
1933
|
+
};
|
|
1934
|
+
|
|
1935
|
+
/**
|
|
1936
|
+
* Q9 (QA round 3): the target the route line of an EXACT resume declares is the child's bound root — by text only, no admission
|
|
1937
|
+
* and no filesystem call: a `root=` equal (normalised) to the bound work root or its worktree, a `repo=` equal to the bound
|
|
1938
|
+
* repository's name, a `branch=` equal to the bound branch. An invalid declaration, or a bound grant without a work root, never is.
|
|
1939
|
+
*/
|
|
1940
|
+
const declaresBoundRoot = (line: RouteLine | null | undefined, grant: DispatchGrant): boolean => {
|
|
1941
|
+
if (line === null || line === undefined) return true;
|
|
1942
|
+
if ((line.invalidCrossRepo?.length ?? 0) > 0 || grant.workRoot === null) return false;
|
|
1943
|
+
const platform = workRootDeps.platform;
|
|
1944
|
+
const location = grant.location;
|
|
1945
|
+
if (line.root !== undefined) {
|
|
1946
|
+
const declared = normalizeRootText(line.root, platform);
|
|
1947
|
+
const candidates = location === undefined ? [grant.workRoot] : [grant.workRoot, location.worktree];
|
|
1948
|
+
if (!candidates.some((candidate) => normalizeRootText(candidate, platform) === declared)) return false;
|
|
1949
|
+
}
|
|
1950
|
+
const sameName = (a: string, b: string): boolean => (platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b);
|
|
1951
|
+
if (line.repo !== undefined && (location === undefined || !sameName(location.name, line.repo))) return false;
|
|
1952
|
+
if (line.branch !== undefined && (location === undefined || location.branch !== line.branch.replace(/^refs\/heads\//, ""))) return false;
|
|
1953
|
+
return true;
|
|
1954
|
+
};
|
|
1955
|
+
|
|
1956
|
+
/**
|
|
1957
|
+
* D17 (cross-repo QA): the target an exact resume declares is the child's bound root. The text fast path ({@link declaresBoundRoot})
|
|
1958
|
+
* runs no admission and no filesystem call. When it does not match — `repo=<worktree directory>` (Q10: the location's name is the
|
|
1959
|
+
* repository's), a `root=` spelled through a junction / symlink / subst drive — the declaration is resolved exactly as a fresh
|
|
1960
|
+
* dispatch resolves it ({@link bindWorkRoot}) and accepted when the work root it binds is the child's bound work root or its
|
|
1961
|
+
* worktree (`normalizeRootText` of the realpath on both sides). So admission may now run on a resume, but only when the fast path
|
|
1962
|
+
* fails. Whatever the answer, the resume keeps the BOUND grant: the resolution is only compared, never adopted (no widening).
|
|
1963
|
+
*/
|
|
1964
|
+
const declaresBoundTarget = async (
|
|
1965
|
+
cfg: RouterConfig,
|
|
1966
|
+
orchestratorSessionID: string,
|
|
1967
|
+
sessionDirectory: string,
|
|
1968
|
+
line: RouteLine | null | undefined,
|
|
1969
|
+
grant: DispatchGrant,
|
|
1970
|
+
): Promise<boolean> => {
|
|
1971
|
+
if (declaresBoundRoot(line, grant)) return true;
|
|
1972
|
+
if (line === null || line === undefined || (line.invalidCrossRepo?.length ?? 0) > 0 || grant.workRoot === null) return false;
|
|
1973
|
+
const platform = workRootDeps.platform;
|
|
1974
|
+
const canonicalText = (path: string): string => {
|
|
1975
|
+
try {
|
|
1976
|
+
const real = workRootDeps.realpath(path);
|
|
1977
|
+
return normalizeRootText(typeof real === "string" && real !== "" ? real : path, platform);
|
|
1978
|
+
} catch {
|
|
1979
|
+
return normalizeRootText(path, platform);
|
|
1980
|
+
}
|
|
1981
|
+
};
|
|
1982
|
+
const resolved = await bindWorkRoot(cfg, orchestratorSessionID, sessionDirectory, line);
|
|
1983
|
+
if (resolved.workRoot === null) return false;
|
|
1984
|
+
const got = canonicalText(resolved.workRoot);
|
|
1985
|
+
const bound = grant.location === undefined ? [grant.workRoot] : [grant.workRoot, grant.location.worktree];
|
|
1986
|
+
return bound.some((candidate) => canonicalText(candidate) === got);
|
|
1987
|
+
};
|
|
1988
|
+
|
|
1989
|
+
/** Q9 (QA round 3): the refusal of an exact resume whose route line declares another target than the child's bound root. */
|
|
1990
|
+
const boundRootRefusal = (grant: DispatchGrant): string => {
|
|
1991
|
+
const where = grant.workRoot === null ? "no work root" : displaySafe(grant.workRoot);
|
|
1992
|
+
const location = grant.location;
|
|
1993
|
+
const detail = location === undefined
|
|
1994
|
+
? ""
|
|
1995
|
+
: ` (repository ${displaySafe(location.name)}, branch ${location.branch === null ? "(detached)" : displaySafe(location.branch)})`;
|
|
1996
|
+
return `this child is bound to ${where}${detail}; a resume cannot change its work root: dispatch a new child`;
|
|
1997
|
+
};
|
|
1998
|
+
|
|
1470
1999
|
/**
|
|
1471
2000
|
* The rung a resumed child runs on: the dispatch registry's record (its `tier` is the role tier the router registered), else the
|
|
1472
2001
|
* child session's own model; unknown → a model off every ladder, which the kernel lifts to the window ceiling (never below).
|
|
@@ -1514,13 +2043,53 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1514
2043
|
if (lined.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
|
|
1515
2044
|
|
|
1516
2045
|
// 2. work root: `root=` from the trace only, text-compared with `git worktree list --porcelain` before any filesystem call.
|
|
1517
|
-
|
|
2046
|
+
// Cross-repo (P1.4): `repo=` / `branch=`, and a `root=` the text match does not find, are bound through admission.
|
|
2047
|
+
const declaredLine = lined.trace.routeLine;
|
|
1518
2048
|
const bound = resumeID === null ? undefined : currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) });
|
|
2049
|
+
// Q9: a dispatch that DECLARED a target (`repo=` / `branch=` / `root=`, or an invalid `repo=` / `branch=` / `root=`) whose
|
|
2050
|
+
// binding was refused is refused with the note — it never runs in the session directory instead. A dispatch that declared
|
|
2051
|
+
// nothing is untouched.
|
|
2052
|
+
const declaredTarget = declaredLine !== null && declaredLine !== undefined
|
|
2053
|
+
&& (declaredLine.repo !== undefined || declaredLine.branch !== undefined || declaredLine.root !== undefined || (declaredLine.invalidCrossRepo?.length ?? 0) > 0);
|
|
2054
|
+
// A resume of an exactly bound child keeps the child's bound root: a target it declares must name that root — by text first (no
|
|
2055
|
+
// admission), else by the same resolution a fresh dispatch uses (D17) — else the resume is refused: a resume cannot move a child.
|
|
2056
|
+
const exactBound = bound?.kind === "exact" ? bound.grant : undefined;
|
|
2057
|
+
// Phase 4 QA (m2): a child bound through an approval resumes only while that approval applies (store read, no git): a revoked or
|
|
2058
|
+
// expired approval ends the binding, so the resume is refused and the lapsed location never rejoins the working set.
|
|
2059
|
+
const boundApproval = exactBound?.location?.approval;
|
|
2060
|
+
const lapsedApproval = boundApproval === undefined ? undefined
|
|
2061
|
+
: lapsedApprovalReason(boundApproval, resolveRolesRouting(rp.cfg, "v2").repoApprovalDays, deps.approvalsEnv, workRootDeps.platform);
|
|
2062
|
+
if (lapsedApproval !== undefined) throw new RoleDispatchRefusal(agent, displaySafe(`resume refused: ${lapsedApproval}`));
|
|
2063
|
+
if (declaredTarget && exactBound !== undefined && !await declaresBoundTarget(rp.cfg, call.sessionID, sessionDirectory, declaredLine, exactBound)) {
|
|
2064
|
+
throw new RoleDispatchRefusal(agent, boundRootRefusal(exactBound));
|
|
2065
|
+
}
|
|
2066
|
+
const root: WorkRootResolution = declaredTarget && exactBound !== undefined
|
|
2067
|
+
? {
|
|
2068
|
+
workRoot: exactBound.workRoot,
|
|
2069
|
+
requested: declaredLine?.root ?? null,
|
|
2070
|
+
note: null,
|
|
2071
|
+
...(exactBound.location === undefined ? {} : { location: exactBound.location }),
|
|
2072
|
+
}
|
|
2073
|
+
: await bindWorkRoot(rp.cfg, call.sessionID, sessionDirectory, declaredLine);
|
|
2074
|
+
// The note may echo route-line text and filesystem names: escaped before it reaches the orchestrator.
|
|
2075
|
+
if (declaredTarget && root.workRoot === null && root.note !== null && bound?.kind !== "exact") {
|
|
2076
|
+
// Phase 4 (SD-P4-8): a candidate a human could approve gets the details git reports about it (never the dispatch text).
|
|
2077
|
+
// Only here, on the dispatch bind path: `declaresBoundTarget` also runs `bindWorkRoot` but only compares, so no git there.
|
|
2078
|
+
const approval = root.approvable === undefined ? undefined : await approvalNote(root.approvable, {
|
|
2079
|
+
exclude: resolveRolesRouting(rp.cfg, "v2").repoExclude,
|
|
2080
|
+
...(deps.approvalsEnv === undefined ? {} : { env: deps.approvalsEnv }),
|
|
2081
|
+
...(deps.inspectCandidate === undefined ? {} : { inspect: deps.inspectCandidate }),
|
|
2082
|
+
});
|
|
2083
|
+
throw new RoleDispatchRefusal(agent, displaySafe(approval === undefined ? root.note : `${root.note} ${approval}`));
|
|
2084
|
+
}
|
|
2085
|
+
// Phase 4 (SD-P4-7): a fresh binding backed by an approval records its use (fire and forget, at most once per hour).
|
|
2086
|
+
const approvedBy = declaredTarget && exactBound !== undefined ? undefined : root.location?.approval;
|
|
2087
|
+
if (root.workRoot !== null && approvedBy !== undefined) touchApproval(approvedBy, resolveRolesRouting(rp.cfg, "v2").repoApprovalDays, deps.approvalsEnv);
|
|
1519
2088
|
|
|
1520
2089
|
// 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
2090
|
// 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
2091
|
// validated one, in the session directory as the host names it.
|
|
1523
|
-
const requestedRoot = root.requested !== null ? root.workRoot : null;
|
|
2092
|
+
const requestedRoot = root.requested !== null || root.location !== undefined ? root.workRoot : null;
|
|
1524
2093
|
const classifyCwd = (bound?.kind === "exact" ? bound.grant.workRoot : null) ?? requestedRoot ?? sessionDirectory;
|
|
1525
2094
|
const result = await classify({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
|
|
1526
2095
|
if (result.trace.routeLines.malformed === true) throw new RoleDispatchRefusal(agent, ROLE_REFUSALS.malformed);
|
|
@@ -1544,7 +2113,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1544
2113
|
// 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
2114
|
// what that child holds (its bound grant) plus the widened actions — the resume prompt alone ("continue") would lose them.
|
|
1546
2115
|
const grant: DispatchGrant = bound?.kind === "exact" ? resumedGrant(bound.grant, call.widened ?? [])
|
|
1547
|
-
: grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine);
|
|
2116
|
+
: grantFor(rp.spec, taskFacts, call.widened ?? [], root.workRoot, routeLine, root.location);
|
|
1548
2117
|
|
|
1549
2118
|
// 5. effective detection (S10/P-9, A34; handoff 5): never `result.detection` as is. QA-G-B-1: a resume that names no
|
|
1550
2119
|
// `[acceptance]` block of its own carries the one of the dispatch it resumes (and its `VERIFY:` lines, when it names none), so
|
|
@@ -1567,22 +2136,25 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1567
2136
|
const bypassed = deps.isBypassed?.(call.sessionID) === true;
|
|
1568
2137
|
const env = deps.env === undefined ? {} : { env: deps.env };
|
|
1569
2138
|
const verifyRoot = verifyRootOf(grant, sessionDirectory, workRootDeps.realpath);
|
|
2139
|
+
const inReadSet = readSetFor(rp.cfg, call.sessionID);
|
|
2140
|
+
// 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
|
|
2141
|
+
// checks (testsPass, lintClean) can cover the child's earlier attempts only once the attempt that introduced the block was
|
|
2142
|
+
// gated with a known change set (its baseline) — until then the gate cannot back `deterministic`.
|
|
2143
|
+
const deferred = carried === null
|
|
2144
|
+
? roleGateDeferred(rp.cfg, verifyPrompt, description, { verifyEnabled: deps.routerVerifyEnabled?.() !== false })
|
|
2145
|
+
: (carried.baseline === undefined || carried.baseline.changed === "unavailable") && carriedChecksChangeSet(carried.block);
|
|
1570
2146
|
const routerGate = roleRouterGate({
|
|
1571
2147
|
cfg: rp.cfg, bypassed, acceptance, ...env,
|
|
1572
|
-
|
|
1573
|
-
|
|
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
|
|
2148
|
+
deferred,
|
|
2149
|
+
outsideWorkRoot: roleGateOutsideWorkRoot(grant.workRoot, verifyPrompt, description, args.cwd, inReadSet), // DF2-F1, QA-P33F1-1-1, nit 3
|
|
1579
2150
|
});
|
|
1580
2151
|
// QA-G-B-7: the gate verifies nothing at all (enforcement off, /bypass, `require: never`, a cwd outside the root it verifies in)
|
|
1581
2152
|
// → detection `none`.
|
|
1582
2153
|
const verifies = roleVerificationRuns({
|
|
1583
|
-
cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd),
|
|
2154
|
+
cfg: rp.cfg, bypassed, ...env, outsideWorkRoot: roleGateOutsideWorkRoot(verifyRoot, verifyPrompt, description, args.cwd, inReadSet),
|
|
1584
2155
|
});
|
|
1585
2156
|
const detection = effectiveDetection({ routerGate, claim, acceptance, verifies });
|
|
2157
|
+
const gateAtReturn = verifies && !deferred && acceptance !== "none";
|
|
1586
2158
|
|
|
1587
2159
|
// 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
2160
|
// after a verification FAIL of this child (for this parent) is a raise-only floor, like `floorTier`; consumed on success.
|
|
@@ -1591,6 +2163,11 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1591
2163
|
const raised = resumeID === null ? null : pendingResumeRaise(resumeID, call.sessionID);
|
|
1592
2164
|
const floorTier = higherTier(tiers, rp.cfg.enforcement?.escalate?.floorTier ?? null, raised);
|
|
1593
2165
|
const bounds = tierBounds(rp.spec, grant, classified, detection, {
|
|
2166
|
+
// The gated cell promises a one-step raise to heavy; a narrowed ceiling or an intermediate rung cannot back it.
|
|
2167
|
+
floorPolicy: {
|
|
2168
|
+
mode: resolveRolesRouting(rp.cfg, "v2").roleFloor,
|
|
2169
|
+
gateAtReturn: gateAtReturn && nextRoleTier(tiers, rp.spec.tierRange.ceiling, "medium") === "heavy",
|
|
2170
|
+
},
|
|
1594
2171
|
floorTier,
|
|
1595
2172
|
runningTier: running?.tier ?? null,
|
|
1596
2173
|
pinTier: routeLine?.tier ?? null,
|
|
@@ -1668,6 +2245,8 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1668
2245
|
// QA-P21-1-11: a fresh dispatch has no binding yet (its child binds later; `noteBinding` writes the observed kind then).
|
|
1669
2246
|
// A resume records the child's current binding.
|
|
1670
2247
|
const binding = resumed ? currentBinding(resumeID, { maxOf: (name) => roleMaxActions(rp.roles.get(name)) })?.kind : undefined;
|
|
2248
|
+
const riskTerm = classifyRiskTerm({ description, prompt, cwd: classifyCwd }, rp.classifyDeps);
|
|
2249
|
+
const inheritedRisk = RISKS.find((risk) => risk === original?.facts.risk);
|
|
1671
2250
|
row = {
|
|
1672
2251
|
v: LOG_ROW_VERSION,
|
|
1673
2252
|
ts: new Date(safeNow(now)).toISOString(),
|
|
@@ -1687,7 +2266,15 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1687
2266
|
reason: `${head}; role @${agent} on ${tier} in ${bounds.floor}..${bounds.ceiling}${extra.length > 0 ? ` [${extra.join("; ")}]` : ""}`,
|
|
1688
2267
|
step: "dispatch",
|
|
1689
2268
|
resume: resumed,
|
|
1690
|
-
trace: { ...traceOf(result, argmin
|
|
2269
|
+
trace: { ...traceOf(result, argmin, {
|
|
2270
|
+
base: CLASS_BASE_RISK[result.trace.rules.class],
|
|
2271
|
+
rules: result.trace.rules.risk,
|
|
2272
|
+
routeLine: routeLine?.risk ?? null,
|
|
2273
|
+
facts: result.facts.risk,
|
|
2274
|
+
...(inheritedRisk === undefined ? {} : { resumedDispatch: inheritedRisk }),
|
|
2275
|
+
effective: taskFacts.risk,
|
|
2276
|
+
...(riskTerm === undefined ? {} : { term: riskTerm }),
|
|
2277
|
+
}), needTerms }, // QA-G-B-3 (3)
|
|
1691
2278
|
detection: {
|
|
1692
2279
|
effective: detection,
|
|
1693
2280
|
...(result.detection !== undefined && result.detection !== null && result.detection !== detection ? { claimed: result.detection } : {}),
|
|
@@ -1717,6 +2304,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1717
2304
|
requestedRoot: root.requested,
|
|
1718
2305
|
notes,
|
|
1719
2306
|
detection,
|
|
2307
|
+
...(bounds.reasons.includes("gated:authority") ? { gated: true as const } : {}),
|
|
1720
2308
|
budget,
|
|
1721
2309
|
routeBudget,
|
|
1722
2310
|
nonce,
|
|
@@ -1727,7 +2315,57 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1727
2315
|
...(carried !== null ? { carried: true as const } : {}), // QA-G-B-2-1
|
|
1728
2316
|
};
|
|
1729
2317
|
rememberRoutedRole(routed);
|
|
2318
|
+
// Cross-repo (P1.4, QA round 1 F5/F9): the dispatch is accepted. The location the GRANT holds (a resume keeps its bound one)
|
|
2319
|
+
// joins the orchestrator's working set (rule 2 for its later dispatches), and only when `routing.repoParents` is set: a
|
|
2320
|
+
// `branch=` / `repo=` alone binds through declare-then-check but does not grow the working set.
|
|
2321
|
+
if (grant.location !== undefined && grant.workRoot !== null && resolveRolesRouting(rp.cfg, "v2").repoParents.length > 0) addToWorkingSet(call.sessionID, grant.location);
|
|
1730
2322
|
if (raised !== null && resumeID !== null) resumeRaises.delete(resumeID); // QA-P21-2-2: consumed once, by a routed resume
|
|
2323
|
+
// P2g (OD6): a role delegate is told its work root. The header goes FIRST; the nonce line / carried block stay last. Only a
|
|
2324
|
+
// grant with a work root and read access gets one; a resume only when its binding is exact (the bound grant is what it holds).
|
|
2325
|
+
const exactResume = resumed && bound?.kind === "exact";
|
|
2326
|
+
// QA round 1 #11: the router's header is always the one the delegate reads. A header the orchestrator copied from another
|
|
2327
|
+
// dispatch (it names that dispatch's work root) is stripped first and replaced, never kept in place of ours.
|
|
2328
|
+
// QA round 1 #12: `dispatchHeader: false` turns the header off, except that a work root other than the session directory is
|
|
2329
|
+
// still told (the work-root rule points to ENVIRONMENT, which is the session directory): then a MINIMAL header, the identity
|
|
2330
|
+
// paragraph (so stripDispatchHeader still removes it before DoD inference) and the `Working directory:` paragraph, no
|
|
2331
|
+
// repositories paragraph.
|
|
2332
|
+
const headerEligible = grant.workRoot !== null
|
|
2333
|
+
&& (grant.actions.has("read") || grant.actions.has("glob") || grant.actions.has("grep"))
|
|
2334
|
+
&& (!resumed || exactResume);
|
|
2335
|
+
const headerOn = rp.cfg.dispatchHeader !== false;
|
|
2336
|
+
const tellsOtherRoot = (root: string): boolean => {
|
|
2337
|
+
const platform = workRootDeps.platform;
|
|
2338
|
+
const same = (candidate: string): boolean => normalizeRootText(root, platform) === normalizeRootText(candidate, platform);
|
|
2339
|
+
if (same(sessionDirectory)) return false;
|
|
2340
|
+
try {
|
|
2341
|
+
const real = workRootDeps.realpath(sessionDirectory);
|
|
2342
|
+
return !(typeof real === "string" && real !== "" && same(real));
|
|
2343
|
+
} catch {
|
|
2344
|
+
return true;
|
|
2345
|
+
}
|
|
2346
|
+
};
|
|
2347
|
+
// Q8 (invariant I9): the header is emitted only when it is relevant — cross-repo is configured (`routing.repoParents`), the route
|
|
2348
|
+
// line declared `repo=` / `branch=` / `root=`, or the work root differs from the session directory. Otherwise the role prompt
|
|
2349
|
+
// is byte-identical to what it was before the header existed (route-stripped text + nonce / carried block).
|
|
2350
|
+
const headerRelevant = (root: string): boolean =>
|
|
2351
|
+
resolveRolesRouting(rp.cfg, "v2").repoParents.length > 0
|
|
2352
|
+
|| declaredLine?.repo !== undefined || declaredLine?.branch !== undefined || declaredLine?.root !== undefined
|
|
2353
|
+
|| tellsOtherRoot(root);
|
|
2354
|
+
const headerWanted = headerEligible && grant.workRoot !== null && headerRelevant(grant.workRoot) && (headerOn || tellsOtherRoot(grant.workRoot));
|
|
2355
|
+
const finalPrompt = headerWanted && grant.workRoot !== null
|
|
2356
|
+
? `${buildRoleDispatchHeader({
|
|
2357
|
+
agent,
|
|
2358
|
+
workRoot: grant.workRoot,
|
|
2359
|
+
edits: grant.actions.has("edit"),
|
|
2360
|
+
...(grant.location === undefined ? {} : { location: grant.location }),
|
|
2361
|
+
...(headerOn
|
|
2362
|
+
? { workingSet: workingSetOf(call.sessionID), readParents: resolveRolesRouting(rp.cfg, "v2").repoParents }
|
|
2363
|
+
: {}),
|
|
2364
|
+
...(exactResume ? { exactResume: true } : {}),
|
|
2365
|
+
})}${stripDispatchHeader(outPrompt)}`
|
|
2366
|
+
// QA round 3: a header the orchestrator copied (it names another dispatch's root and verb) is stripped even when the router
|
|
2367
|
+
// adds none; a prompt without one is returned unchanged (Q8: byte-identical).
|
|
2368
|
+
: stripDispatchHeader(outPrompt);
|
|
1731
2369
|
|
|
1732
2370
|
decided.set(call.callID, {
|
|
1733
2371
|
parentSessionID: call.sessionID,
|
|
@@ -1753,7 +2391,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1753
2391
|
trim(decided, MAX_PENDING);
|
|
1754
2392
|
return {
|
|
1755
2393
|
mode,
|
|
1756
|
-
...(
|
|
2394
|
+
...(finalPrompt !== prompt ? { prompt: finalPrompt } : {}),
|
|
1757
2395
|
model,
|
|
1758
2396
|
...(logged === null ? {} : { decisionID: logged }),
|
|
1759
2397
|
...(outDescription === null ? {} : { description: outDescription }),
|
|
@@ -1840,8 +2478,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1840
2478
|
}
|
|
1841
2479
|
};
|
|
1842
2480
|
|
|
1843
|
-
|
|
1844
|
-
async route(call): Promise<RouteOutcome> {
|
|
2481
|
+
const routeInner = async (call: RouteCall): Promise<RouteOutcome> => {
|
|
1845
2482
|
try {
|
|
1846
2483
|
const agent = str(call.args.agent);
|
|
1847
2484
|
const callKey = `${call.sessionID}\u0000${call.callID}`;
|
|
@@ -1884,8 +2521,36 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1884
2521
|
deps.logger.warn("[router] routing: the engine failed; the dispatch proceeds as the orchestrator chose", { error: describeError(error) });
|
|
1885
2522
|
return UNTOUCHED;
|
|
1886
2523
|
}
|
|
2524
|
+
};
|
|
2525
|
+
|
|
2526
|
+
return {
|
|
2527
|
+
async route(call): Promise<RouteOutcome> {
|
|
2528
|
+
const outcome = await routeInner(call); // throws only RoleDispatchRefusal
|
|
2529
|
+
try {
|
|
2530
|
+
const routed = outcome.role;
|
|
2531
|
+
const d = decided.get(call.callID);
|
|
2532
|
+
if (routed !== undefined) {
|
|
2533
|
+
noteDecision(call.callID, { role: routed.agent, class: routed.class ?? "unknown", scope: d?.facts.scope ?? "unknown", tier: routed.tier, model: routed.model });
|
|
2534
|
+
} else if (d !== undefined) {
|
|
2535
|
+
noteDecision(call.callID, {
|
|
2536
|
+
role: undefined,
|
|
2537
|
+
class: d.facts.class,
|
|
2538
|
+
scope: d.facts.scope,
|
|
2539
|
+
tier: d.final !== null && classifyAgentOrigin(d.final.agent, d.routerIds) === "router" ? d.final.agent : undefined,
|
|
2540
|
+
model: d.final === null ? undefined : d.final.model,
|
|
2541
|
+
});
|
|
2542
|
+
} else {
|
|
2543
|
+
noteDecision(call.callID, { role: undefined, class: "unknown", scope: "unknown", tier: undefined, model: undefined });
|
|
2544
|
+
}
|
|
2545
|
+
} catch (error) {
|
|
2546
|
+
deps.logger.warn("[router] routing: the decision of a call could not be noted", { error: describeError(error) });
|
|
2547
|
+
}
|
|
2548
|
+
return outcome;
|
|
1887
2549
|
},
|
|
1888
2550
|
|
|
2551
|
+
// Valid until `onCallResult`/`onCallFinished` of the call: the adapter reads it in `execute.before` and, before `onCallResult`, in `execute.after`.
|
|
2552
|
+
decisionOf: (callID) => decisionInfos.get(callID),
|
|
2553
|
+
|
|
1889
2554
|
commit(callID, input): void {
|
|
1890
2555
|
try {
|
|
1891
2556
|
const d = decided.get(callID);
|
|
@@ -1994,6 +2659,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
1994
2659
|
onCallResult(callID, childSessionID): void {
|
|
1995
2660
|
try {
|
|
1996
2661
|
decided.delete(callID);
|
|
2662
|
+
decisionInfos.delete(callID);
|
|
1997
2663
|
const entry = entries.get(callID);
|
|
1998
2664
|
entries.delete(callID);
|
|
1999
2665
|
if (entry === undefined) return;
|
|
@@ -2020,6 +2686,7 @@ export function createDispatchRouter(deps: DispatchRouterDeps): DispatchRouter {
|
|
|
2020
2686
|
|
|
2021
2687
|
onCallFinished(callID): void {
|
|
2022
2688
|
decided.delete(callID);
|
|
2689
|
+
decisionInfos.delete(callID);
|
|
2023
2690
|
const entry = entries.get(callID);
|
|
2024
2691
|
entries.delete(callID);
|
|
2025
2692
|
if (entry !== undefined) undoResume(entry);
|