opencode-model-router 2.8.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 +364 -0
- package/README.md +20 -0
- package/package.json +5 -1
- package/src/commands/output.ts +23 -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 +2656 -114
- 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 +1498 -288
- package/src/router/config.ts +776 -25
- package/src/router/git-tools.ts +106 -15
- package/src/router/leases.ts +1469 -0
- package/src/router/logger.ts +44 -32
- package/src/router/protocol.ts +40 -10
- package/src/router/role-agents.ts +224 -17
- package/src/router/roles-config.ts +10 -1
- package/src/router/roles.ts +1 -1
- package/src/router/run-tools.ts +56 -4
- 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/rules.ts +11 -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/stats.ts +170 -11
- package/src/routing/outcomes/timings.ts +836 -0
- package/src/routing/outcomes/types.ts +98 -0
- package/src/routing/roles/approvals.ts +86 -5
- package/src/routing/roles/binding.ts +99 -9
- package/src/routing/roles/orphans.ts +68 -0
- package/src/routing/roles/policy.ts +21 -3
- package/src/routing/roles/work-root.ts +3 -1
- package/src/routing/wire/dispatch.ts +86 -12
- package/src/routing/wire/hint.ts +56 -8
- package/src/v2.ts +94 -49
- package/src/verify/branch.ts +8 -2
- package/src/verify/canonical-path.ts +35 -0
- package/src/verify/deterministic.ts +38 -9
- package/src/verify/dispatch.ts +64 -28
- package/src/verify/exec.ts +52 -9
- package/src/verify/pending.ts +1691 -10
- package/src/verify/perimeter.ts +12 -6
- package/src/verify/plan-task.ts +729 -0
- package/src/verify/reference.ts +216 -3
- package/src/verify/tree.ts +30 -13
- package/src/verify/types.ts +9 -2
- package/src/verify/wiring.ts +290 -31
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Plugin } from "@opencode-ai/plugin";
|
|
2
|
+
import { completionIdentity, observeV2 } from "./compat/v2-observations";
|
|
2
3
|
import type { RouterPluginInput } from "./compat/child-session";
|
|
3
4
|
import { DEPTH_BANNER, ResumeRejectedError, TASK_VERIFICATION } from "./compat/child-session";
|
|
4
5
|
|
|
@@ -72,6 +73,7 @@ import { routerRunTool, type RunRecord } from "./router/run-tools";
|
|
|
72
73
|
import type { WorkRootAnswer } from "./router/git-tools";
|
|
73
74
|
import { GUARD_CUMULATIVE_MULTIPLIER, roleGuardProfile, type GuardProfile } from "./router/guard-profile";
|
|
74
75
|
import { currentBinding } from "./routing/roles/binding";
|
|
76
|
+
import { readRoleOrphans } from "./routing/roles/orphans";
|
|
75
77
|
import { authorityTool, requestedAuthority } from "./routing/roles/authority";
|
|
76
78
|
import {
|
|
77
79
|
CARRIED_NO_PROCESS_REASON, lapsedApprovalReason, pruneLapsedApprovals, roleAttemptVerification, roleEscalationAfterFail, roleMaxActions,
|
|
@@ -89,10 +91,20 @@ import { createCatalogPricing, createIngest, ingestSettings } from "./routing/ou
|
|
|
89
91
|
import type { Ingest } from "./routing/outcomes/ingest";
|
|
90
92
|
import { isAnnotationRow, verdictGraderOf, verdictOf, type LogRow } from "./routing/outcomes/types";
|
|
91
93
|
import { createPersister, nodePersistDeps, summarizeRoles } from "./routing/outcomes";
|
|
94
|
+
import { countUnknownBindings } from "./routing/outcomes/stats";
|
|
92
95
|
import { roleAgentSteps } from "./router/role-agents";
|
|
93
96
|
import type { HostBudgetObservation } from "./compat/v2-hooks";
|
|
97
|
+
import { ROUTER_TURN_STATE_ATTACH, TURN_STATE_ROOT, type TurnStateRegistry } from "./compat/turn-state";
|
|
98
|
+
import { ADOPTION_REFUSED, ROUTER_FINISH_ATTACH, type AdoptedRecords, type AdoptionRefused, type FinishApi, type FinishAttach, type FinishInput, type FinishResult, type HeldSink, type InflightJournal, type LeaseGuard, type PersistedRecord, type RestoredDispatch, type RoutedRoleSnapshot } from "./compat/background";
|
|
99
|
+
import type { DispatchDelta } from "./verify/dispatch";
|
|
100
|
+
import { configAsWritten, configuredV2OnlyKeys, setConfigNoticeHost } from "./router/config";
|
|
101
|
+
|
|
102
|
+
/** Phase 2.1: the v2-only config keys already announced as ignored on a v1 host (once per key per process). */
|
|
103
|
+
const warnedV2OnlyKeys = new Set<string>();
|
|
94
104
|
import { checkpointLine, formatStatsReply, runStatsCommand } from "./routing/commands/stats";
|
|
95
|
-
import { buildAnnotateDirectives } from "./routing/commands/annotate-plan";
|
|
105
|
+
import { agentInfosForPlan, buildAnnotateDirectives } from "./routing/commands/annotate-plan";
|
|
106
|
+
import { annotateSteps } from "./routing/engine/plan";
|
|
107
|
+
import { classifyMany as classifyPlanSteps } from "./routing/classify";
|
|
96
108
|
import { applyV1Roles, hasExplicitV1Roles, v1AgentInfos } from "./routing/commands/v1-roles";
|
|
97
109
|
import type { HostAgentInfo } from "./routing/engine/types";
|
|
98
110
|
import { createEngineRuntime } from "./routing/wire/runtime";
|
|
@@ -123,19 +135,24 @@ import {
|
|
|
123
135
|
lastStepContext,
|
|
124
136
|
} from "./router/sessions";
|
|
125
137
|
import type { Cap, SubagentState } from "./router/sessions";
|
|
138
|
+
import { EXECUTOR_READ_CAP_LINE, type ExecutorChildGuardPort } from "./executor/types";
|
|
139
|
+
import { executorChildRound, publishExecutorChildRound } from "./executor/child-guards";
|
|
126
140
|
import { createTrajectoryStore } from "./telemetry/trajectory";
|
|
127
141
|
import { createGuardStore } from "./guard/store";
|
|
128
142
|
import { createIdleTtlSweeper } from "./router/idle-sweep";
|
|
129
143
|
import { guardBeforeCall, guardAfterCall, guardRefusedCall, formatScorecard } from "./guard/enforce";
|
|
130
144
|
import { mkdirSync, writeFileSync, existsSync, realpathSync, statSync } from "node:fs";
|
|
131
|
-
import { tmpdir } from "node:os";
|
|
145
|
+
import { homedir, tmpdir } from "node:os";
|
|
132
146
|
import { join, isAbsolute } from "node:path";
|
|
133
147
|
import { access, readFile as fsReadFile } from "node:fs/promises";
|
|
134
148
|
import { tool } from "@opencode-ai/plugin";
|
|
135
149
|
import { scrubText } from "./guard/scrub";
|
|
136
150
|
import { accept, unverifiableGateResult } from "./verify/gate";
|
|
137
|
-
import { applyDispatchCaveats, createVerificationWiring, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart } from "./verify/wiring";
|
|
138
|
-
import {
|
|
151
|
+
import { applyDispatchCaveats, createVerificationWiring, resolvePendingTtlMs, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart, type HandleReport } from "./verify/wiring";
|
|
152
|
+
import { waitTreeFreeExcept } from "./verify/wiring";
|
|
153
|
+
import { createLeaseSelfExemptions, createPlanTaskVerifier, planTaskGit, planTreeKey } from "./verify/plan-task";
|
|
154
|
+
import { locationOutsideWorkRoots } from "./router/work-roots";
|
|
155
|
+
import { CLAIM_REFRESH_MS, HEAD_LOST_REASON, PENDING_INSTANCES_DIRNAME, PERIMETER_LOST_REASON, type DispatchHeadState, claimPendingSession, createInstanceClaimToken, createPendingFileJournal, foldDormantRecords, refreshPendingClaims, releasePendingClaim, resolvePendingJournalDir, processedKeyOf, appendRouterFooter, buildLateNoticeBlock, buildPendingListBlock, unattributedRisk, type DormantSession, type LateNotice, type PendingEntry, type SettledVerification } from "./verify/pending";
|
|
139
156
|
import { createDeadline } from "./verify/deterministic";
|
|
140
157
|
import {
|
|
141
158
|
DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
|
|
@@ -168,6 +185,10 @@ import type { AttemptRecorder, DelegationFacts } from "./escalate/attempt-record
|
|
|
168
185
|
import { createDepthTracker, DEPTH_LOOKUP_RETRY_MS } from "./router/depth";
|
|
169
186
|
import { createDepthGuard } from "./router/depth-guard";
|
|
170
187
|
import { applyEffortOverride, createEffortOverrideStore } from "./escalate/effort-override";
|
|
188
|
+
import { createExecutorAccess, lateRuntime, type ExecutorAccess, type CreateExecutorOptions } from "./executor/create";
|
|
189
|
+
import { executorPlatformSupported, warnExecutorPlatformOnce } from "./executor/platform";
|
|
190
|
+
import { createRouterPlanTool } from "./executor/tool";
|
|
191
|
+
import { createPlanCommand, parsePlanCommand } from "./executor/command";
|
|
171
192
|
|
|
172
193
|
// ---------------------------------------------------------------------------
|
|
173
194
|
// Re-exports — type-only re-exports for IDE/test consumers.
|
|
@@ -266,7 +287,7 @@ function saveEnforcementMode(mode: "off" | "advisory" | "enforced"): void {
|
|
|
266
287
|
* `/router` dispatch. Decides and persists here; rendering lives in
|
|
267
288
|
* src/commands/output.ts.
|
|
268
289
|
*/
|
|
269
|
-
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>, approvals = false): string {
|
|
290
|
+
function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string, roles?: Iterable<RoleSpec>, approvals = false, plan = false): string {
|
|
270
291
|
const tokens = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
271
292
|
const sub = (tokens[0] ?? "").toLowerCase();
|
|
272
293
|
|
|
@@ -300,7 +321,7 @@ function buildRouterOutput(cfg: RouterConfig, args: string, projectDir?: string,
|
|
|
300
321
|
// `/router stats` is listed only for a config that has a `routing` block: without one `/router` is what it was (QA-2.4-3).
|
|
301
322
|
// #84 P2.2: the role lines, only when the caller hands roles (roles mode on v2); otherwise the help is what it was.
|
|
302
323
|
// Cross-repo P4.7: `/router approve|repos|revoke`, only where they run (SD-P4-10); otherwise the help is what it was.
|
|
303
|
-
{ stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }), ...(approvals ? { approvals: true } : {}) },
|
|
324
|
+
{ stats: cfg.routing !== undefined, ...(roles === undefined ? {} : { roles }), ...(approvals ? { approvals: true } : {}), ...(plan ? { plan: true } : {}) },
|
|
304
325
|
);
|
|
305
326
|
}
|
|
306
327
|
|
|
@@ -377,6 +398,71 @@ const V1_HOST_BUILTIN_AGENTS: Record<string, { mode: string }> = {
|
|
|
377
398
|
const SESSION_ROOT_MEMO_MAX = 500;
|
|
378
399
|
const SESSION_LOOKUP_RETRY_MS = DEPTH_LOOKUP_RETRY_MS;
|
|
379
400
|
|
|
401
|
+
/** Phase 1.2 (v2 only): bounds of the late-notice buffer behind the `late` turn-state provider. */
|
|
402
|
+
const LATE_BUFFER_PER_SESSION = 50;
|
|
403
|
+
const LATE_BUFFER_SESSIONS = 100;
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Late notices retained per session until `router_verify` answers their handle, so a request that fails after the
|
|
407
|
+
* transform read them does not lose them (the v1 path delivers them once). First-seen order; a repeated handle replaces
|
|
408
|
+
* its notice in place; the oldest notice and the least recently used session go at the bounds.
|
|
409
|
+
*/
|
|
410
|
+
interface LateBuffer {
|
|
411
|
+
add(sessionID: string, notices: readonly LateNotice[]): void;
|
|
412
|
+
list(sessionID: string): LateNotice[];
|
|
413
|
+
release(sessionID: string, handles: readonly string[]): void;
|
|
414
|
+
/** Marks the session as most recently used (a render read its notices). */
|
|
415
|
+
touch(sessionID: string): void;
|
|
416
|
+
/** Drops the session's buffer (`session.deleted`). */
|
|
417
|
+
forget(sessionID: string): void;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function createLateBuffer(): LateBuffer {
|
|
421
|
+
const sessions = new Map<string, Map<string, LateNotice>>();
|
|
422
|
+
return {
|
|
423
|
+
add(sessionID, notices) {
|
|
424
|
+
if (notices.length === 0) return;
|
|
425
|
+
const buffer = sessions.get(sessionID) ?? new Map<string, LateNotice>();
|
|
426
|
+
sessions.delete(sessionID);
|
|
427
|
+
sessions.set(sessionID, buffer);
|
|
428
|
+
for (const notice of notices) buffer.set(notice.handle, notice);
|
|
429
|
+
while (buffer.size > LATE_BUFFER_PER_SESSION) buffer.delete(buffer.keys().next().value!);
|
|
430
|
+
while (sessions.size > LATE_BUFFER_SESSIONS) sessions.delete(sessions.keys().next().value!);
|
|
431
|
+
},
|
|
432
|
+
list(sessionID) {
|
|
433
|
+
return [...(sessions.get(sessionID)?.values() ?? [])];
|
|
434
|
+
},
|
|
435
|
+
release(sessionID, handles) {
|
|
436
|
+
const buffer = sessions.get(sessionID);
|
|
437
|
+
if (buffer === undefined) return;
|
|
438
|
+
for (const handle of handles) buffer.delete(handle);
|
|
439
|
+
if (buffer.size === 0) sessions.delete(sessionID);
|
|
440
|
+
},
|
|
441
|
+
touch(sessionID) {
|
|
442
|
+
const buffer = sessions.get(sessionID);
|
|
443
|
+
if (buffer === undefined) return;
|
|
444
|
+
sessions.delete(sessionID);
|
|
445
|
+
sessions.set(sessionID, buffer);
|
|
446
|
+
},
|
|
447
|
+
forget(sessionID) {
|
|
448
|
+
sessions.delete(sessionID);
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* The handles a router_verify report answers: a verdict, an unknown input, an expired handle. A run that outlived the call
|
|
455
|
+
* ("elsewhere") and a held background result ("held", QA-2.1-9: its own gate posts the verdict) have no verdict yet.
|
|
456
|
+
*/
|
|
457
|
+
function answeredHandles(items: readonly HandleReport[]): string[] {
|
|
458
|
+
const handles: string[] = [];
|
|
459
|
+
for (const item of items) {
|
|
460
|
+
if (item.kind === "verdict" || item.kind === "expired") handles.push(item.handle);
|
|
461
|
+
else if (item.kind === "unknown") handles.push(item.input);
|
|
462
|
+
}
|
|
463
|
+
return handles;
|
|
464
|
+
}
|
|
465
|
+
|
|
380
466
|
const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
381
467
|
// Project directory this plugin instance serves. Hosts that run several
|
|
382
468
|
// projects in one process (OpenCode v2) may also move process.cwd() away from
|
|
@@ -530,6 +616,21 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
530
616
|
// every role branch below is skipped there and both stay byte-identical (§2.7, I1, I8).
|
|
531
617
|
// -------------------------------------------------------------------------
|
|
532
618
|
const isV2Host = ctx.routerHost === "v2";
|
|
619
|
+
// Phase 5.1 D1: the runtime is resolved at each call, after the adapter's synchronous executor factory runs.
|
|
620
|
+
const executorInput = isV2Host ? ctx as RouterPluginInput & {
|
|
621
|
+
routerExecutor?: ExecutorAccess;
|
|
622
|
+
routerOnPlanAnnotate?: (port: NonNullable<CreateExecutorOptions["annotate"]>) => void;
|
|
623
|
+
} : undefined;
|
|
624
|
+
// G-16: the plan executor is Windows-only; elsewhere no executor access exists, so router_plan and /plan are not built.
|
|
625
|
+
const executorPlatform = isV2Host && executorPlatformSupported();
|
|
626
|
+
const absentExecutor = executorPlatform ? createExecutorAccess() : undefined;
|
|
627
|
+
const executorAccess: ExecutorAccess | undefined = absentExecutor === undefined ? undefined : {
|
|
628
|
+
runtime: () => (executorInput?.routerExecutor ?? absentExecutor).runtime(),
|
|
629
|
+
unavailable: () => (executorInput?.routerExecutor ?? absentExecutor).unavailable(),
|
|
630
|
+
set: (runtime) => (executorInput?.routerExecutor ?? absentExecutor).set(runtime),
|
|
631
|
+
clear: (reason) => (executorInput?.routerExecutor ?? absentExecutor).clear(reason),
|
|
632
|
+
};
|
|
633
|
+
const executorRuntime = executorAccess === undefined ? undefined : lateRuntime(executorAccess);
|
|
533
634
|
/**
|
|
534
635
|
* Cross-repo P2e.6 (OD-P2e-2): a dispatch runs the full scope when the host is OpenCode v2 and the effective testScope is
|
|
535
636
|
* "full"; the deferred finish then never treats an empty change set as nothing to run. Always false on v1. Never throws (an
|
|
@@ -797,6 +898,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
797
898
|
* its registered fallback model, P-1) and the bound dispatch budget.
|
|
798
899
|
*/
|
|
799
900
|
const roleGuardProfileOf = (sessionID: unknown, agent: unknown): GuardProfile | undefined => {
|
|
901
|
+
if (typeof sessionID === "string") consumeExecutorChildRound(sessionID);
|
|
800
902
|
const spec = roleSpecOf(agent) ?? roleOfSession(sessionID);
|
|
801
903
|
if (spec === undefined || typeof sessionID !== "string") return undefined;
|
|
802
904
|
const routed = routedGuardOf(sessionID);
|
|
@@ -805,8 +907,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
805
907
|
profile = roleGuardProfile(spec, routed.tier, routed.routeBudget);
|
|
806
908
|
} else {
|
|
807
909
|
const record = lookupDispatch(sessionID);
|
|
808
|
-
const
|
|
809
|
-
|
|
910
|
+
const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
|
|
911
|
+
const tier = binding?.plan !== undefined && binding.tier !== undefined ? binding.tier
|
|
912
|
+
: record?.agent === spec.agent && typeof record.tier === "string" && record.tier !== "" ? record.tier : spec.tierRange.floor;
|
|
913
|
+
profile = roleGuardProfile(spec, tier, binding?.budget ?? null);
|
|
810
914
|
}
|
|
811
915
|
// QA-G-A3-2-2 (§2.6): the cumulative limit spans the child's rounds, so it follows the LARGEST round budget the child had
|
|
812
916
|
// (a later round with a smaller budget never shrinks it below what earlier rounds were allowed).
|
|
@@ -870,6 +974,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
870
974
|
resolveRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger); // v1 + engine != static: log the notice once, at startup (QA-1.1-8)
|
|
871
975
|
// #84 P2.1 (handoff 1): v1 + any roles key: the "roles delegation requires OpenCode v2" notice, once, at startup.
|
|
872
976
|
resolveRolesRouting(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger);
|
|
977
|
+
// QA-4.1-9: on v1 the executor validation issues are not logged; the notice below names the keys.
|
|
978
|
+
setConfigNoticeHost(isV2Host ? "v2" : "v1");
|
|
979
|
+
if (!isV2Host) {
|
|
980
|
+
// Phase 2.1: the background and lease keys exist on v2 only; a v1 host does nothing with them. QA-2.1-12 (AGENTS.md: at most
|
|
981
|
+
// one notice per process for a v2-only feature): one notice names every configured key, and no later instance logs another.
|
|
982
|
+
// QA-4.1-9: the keys as written (the merged layers), so a value validation dropped is still named.
|
|
983
|
+
const keys = [...configuredV2OnlyKeys(configAsWritten(cfg))];
|
|
984
|
+
if (keys.length > 0 && warnedV2OnlyKeys.size === 0) {
|
|
985
|
+
for (const key of keys) warnedV2OnlyKeys.add(key);
|
|
986
|
+
// QA-2.1-32: the notice names the features actually configured (leases alone are not "background dispatch").
|
|
987
|
+
// QA-4.1-19: a block that is not an object is named whole (`routing.executor`).
|
|
988
|
+
const names = (block: string): boolean => keys.some((key) => key === `routing.${block}` || key.startsWith(`routing.${block}.`));
|
|
989
|
+
const background = names("background");
|
|
990
|
+
const leases = names("leases");
|
|
991
|
+
const executor = names("executor");
|
|
992
|
+
const orphans = names("orphans");
|
|
993
|
+
const features = [background ? "background dispatch" : "", leases ? "leases" : "", executor ? "the plan executor" : "", orphans ? "orphan cleanup" : ""].filter((f) => f !== "");
|
|
994
|
+
const subject = features.length === 0
|
|
995
|
+
? "background dispatch requires"
|
|
996
|
+
: features.length === 1
|
|
997
|
+
? `${features[0]} ${leases && !background && !executor && !orphans ? "require" : "requires"}`
|
|
998
|
+
: `${features.slice(0, -1).join(", ")} and ${features[features.length - 1]} require`;
|
|
999
|
+
logger.warn(`[router] ${subject} OpenCode v2; ignored: ${keys.join(", ")}`);
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
873
1002
|
const depthTracker = createDepthTracker({
|
|
874
1003
|
async getParent(id) {
|
|
875
1004
|
if (sessionRootMemo.get(id) === true) return null;
|
|
@@ -893,6 +1022,36 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
893
1022
|
}).mode,
|
|
894
1023
|
logger: routerWarn,
|
|
895
1024
|
});
|
|
1025
|
+
// State-changing executor actions require depth 0, even for an exactly bound plan child.
|
|
1026
|
+
const planRootCallerAllowed = async (sessionID: unknown): Promise<boolean> => {
|
|
1027
|
+
if (!isV2Host || typeof sessionID !== "string" || sessionID === "") return false;
|
|
1028
|
+
try {
|
|
1029
|
+
return await depthTracker.depthOf(sessionID) === 0;
|
|
1030
|
+
} catch {
|
|
1031
|
+
return false;
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
const planReadCallerAllowed = (sessionID: unknown, planId: unknown): boolean => {
|
|
1035
|
+
if (!isV2Host || typeof sessionID !== "string" || sessionID === "" || typeof planId !== "string") return false;
|
|
1036
|
+
try {
|
|
1037
|
+
const binding = currentBinding(sessionID, { maxOf: roleMaxOf });
|
|
1038
|
+
return binding?.kind === "exact" && binding.plan !== undefined && binding.plan.planId === planId.trim();
|
|
1039
|
+
} catch {
|
|
1040
|
+
return false;
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
// Only this allowlist is read-only; new or unknown actions remain root-only. `/plan inbox` parses as status.
|
|
1044
|
+
const planActionCallerAllowed = async (sessionID: unknown, action: unknown, planId: unknown): Promise<boolean> =>
|
|
1045
|
+
await planRootCallerAllowed(sessionID) ||
|
|
1046
|
+
((action === "status" || action === "ready" || action === "export") && planReadCallerAllowed(sessionID, planId));
|
|
1047
|
+
const planCallerRefusal = "refused: plan actions require a root orchestrator session; bound plan children may only read their own plan.";
|
|
1048
|
+
const routerPlan = executorRuntime === undefined ? undefined : createRouterPlanTool(executorRuntime, {
|
|
1049
|
+
approve: () => resolveRouting(loadConfig(projectDir), "v2").executor.approve,
|
|
1050
|
+
});
|
|
1051
|
+
const planCommand = executorRuntime === undefined ? undefined : createPlanCommand(executorRuntime);
|
|
1052
|
+
const planCommandMarker = Symbol.for("opencode-model-router.plan-command");
|
|
1053
|
+
let userPlanCommandDefined = false;
|
|
1054
|
+
let warnedPlanCommandConflict = false;
|
|
896
1055
|
const effortOverrides = createEffortOverrideStore({ logger: routerWarn });
|
|
897
1056
|
let warnedGraderParams = false;
|
|
898
1057
|
const depthBanners = new Map<string, string>();
|
|
@@ -924,26 +1083,240 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
924
1083
|
}
|
|
925
1084
|
};
|
|
926
1085
|
|
|
1086
|
+
// Phase 2.1 (v2 only): pending.jsonl in the durable per-user state directory, never the temp directory (QA-2.1-8).
|
|
1087
|
+
// On v1 there is no journal, no held state and no restore.
|
|
1088
|
+
const pendingDir = isV2Host
|
|
1089
|
+
? resolvePendingJournalDir({ homedir: homedir(), platform: process.platform, xdgStateHome: process.env.XDG_STATE_HOME })
|
|
1090
|
+
: undefined;
|
|
1091
|
+
/**
|
|
1092
|
+
* QA-2.1-27: the journal compacts and reloads with the resolved `enforcement.verify.pendingTtlMs`, the TTL the pending
|
|
1093
|
+
* registry restores with (a longer configured TTL must not lose entries at the second restart).
|
|
1094
|
+
*/
|
|
1095
|
+
const pendingJournalTtlMs = resolvePendingTtlMs(cfg);
|
|
1096
|
+
const pendingFile = pendingDir === undefined
|
|
1097
|
+
? undefined
|
|
1098
|
+
: createPendingFileJournal(join(pendingDir, "pending.jsonl"), {
|
|
1099
|
+
ttlMs: pendingJournalTtlMs,
|
|
1100
|
+
// QA-2.1-22: a failed start-up compaction is told once (the journal stays as it was).
|
|
1101
|
+
warn: (message) => logger.warn(`[router] ${message}`),
|
|
1102
|
+
});
|
|
1103
|
+
/** Section 11.3: the exclusive per-session claim files of the journal's sessions (v2 only). */
|
|
1104
|
+
const pendingClaimsDir = pendingDir === undefined ? undefined : join(pendingDir, "pending.claims");
|
|
1105
|
+
/** DF-1-10: the beat files of the live plugin instances, which every module copy loaded into one host process can read. */
|
|
1106
|
+
const pendingBeatsDir = pendingDir === undefined ? undefined : join(pendingDir, PENDING_INSTANCES_DIRNAME);
|
|
1107
|
+
/** QA-2.1-33: the v2 adapter's live attempts and holds (`FinishApi.setAdapterSnapshot`); none before it attaches. */
|
|
1108
|
+
let adapterSnapshot: (() => readonly PersistedRecord[]) | undefined;
|
|
1109
|
+
/**
|
|
1110
|
+
* QA-2.1-16/-33: every record a later restore needs from this instance: the live pending entries, the sessions not
|
|
1111
|
+
* adopted yet, and the adapter's live attempts and holds. Registered on the journal (next to `dormantSessions`, once that
|
|
1112
|
+
* state exists), so a `recreate` by any instance of this process on the same path writes this instance's records too.
|
|
1113
|
+
*/
|
|
1114
|
+
function journalSnapshot(): PersistedRecord[] {
|
|
1115
|
+
const dormant: PersistedRecord[] = [];
|
|
1116
|
+
for (const session of dormantSessions.values()) dormant.push(...session.holds, ...session.inflight);
|
|
1117
|
+
return [...pending.persistedRecords(), ...dormant, ...(adapterSnapshot?.() ?? [])];
|
|
1118
|
+
}
|
|
1119
|
+
/** QA-2.1-13: the sessions whose claim this process took at adoption; re-stamped while held, released on delete and dispose. */
|
|
1120
|
+
const claimedSessions = new Set<string>();
|
|
1121
|
+
let claimRefreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
1122
|
+
function stopClaimRefresh(): void {
|
|
1123
|
+
if (claimRefreshTimer === undefined) return;
|
|
1124
|
+
clearInterval(claimRefreshTimer);
|
|
1125
|
+
claimRefreshTimer = undefined;
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* QA-2.1-13/-34: a live owner re-stamps its claims every CLAIM_REFRESH_MS (unref'd timer, stopped when it holds no claim
|
|
1129
|
+
* and on dispose), well within CLAIM_STALE_MS, so they never read as a reused pid's; a crashed owner's claims go stale
|
|
1130
|
+
* within minutes, even when its pid is reused.
|
|
1131
|
+
*/
|
|
1132
|
+
function trackPendingClaim(sessionID: string): void {
|
|
1133
|
+
claimedSessions.add(sessionID);
|
|
1134
|
+
if (claimRefreshTimer !== undefined || pendingClaimsDir === undefined) return;
|
|
1135
|
+
const claimsDir = pendingClaimsDir;
|
|
1136
|
+
claimRefreshTimer = setInterval(() => {
|
|
1137
|
+
refreshPendingClaims(claimsDir, claimedSessions, { pid: process.pid, now: Date.now(), ...(instanceClaim === undefined ? {} : { token: instanceClaim.token }) });
|
|
1138
|
+
// DF-1-10: the instance beat stays fresh while this instance holds a claim (a sibling module copy checks it).
|
|
1139
|
+
instanceClaim?.beat();
|
|
1140
|
+
}, CLAIM_REFRESH_MS);
|
|
1141
|
+
claimRefreshTimer.unref?.();
|
|
1142
|
+
}
|
|
1143
|
+
function releasePendingClaimOf(sessionID: string): void {
|
|
1144
|
+
if (!claimedSessions.delete(sessionID) || pendingClaimsDir === undefined) return;
|
|
1145
|
+
releasePendingClaim(pendingClaimsDir, sessionID, instanceClaim?.token);
|
|
1146
|
+
if (claimedSessions.size === 0) stopClaimRefresh();
|
|
1147
|
+
}
|
|
1148
|
+
function releaseAllPendingClaims(): void {
|
|
1149
|
+
stopClaimRefresh();
|
|
1150
|
+
if (pendingClaimsDir !== undefined) for (const sessionID of claimedSessions) releasePendingClaim(pendingClaimsDir, sessionID, instanceClaim?.token);
|
|
1151
|
+
claimedSessions.clear();
|
|
1152
|
+
// QA-2.1-19: from now on another instance of this process may take this instance's (remaining) claims.
|
|
1153
|
+
instanceClaim?.release();
|
|
1154
|
+
}
|
|
1155
|
+
/**
|
|
1156
|
+
* QA-2.1-19 (v2 only): this instance's claim token. Its claims are refused to every other live instance (of this
|
|
1157
|
+
* process: the token; of another process: the pid) until it disposes. DF-1-10: its beat file in `pending.instances`
|
|
1158
|
+
* makes the token visible to instances of this process that run another copy of the plugin modules.
|
|
1159
|
+
*/
|
|
1160
|
+
const instanceClaim = pendingClaimsDir === undefined ? undefined : createInstanceClaimToken(pendingBeatsDir);
|
|
1161
|
+
/**
|
|
1162
|
+
* QA-2.1-19: takes the claim of `sessionID` for this instance (pid + token), once. The live owner claims at its first
|
|
1163
|
+
* `inflight`/`hold` write; `adopt` claims before handing dormant records over. False when another live instance holds
|
|
1164
|
+
* it (or the claim file cannot be written).
|
|
1165
|
+
*/
|
|
1166
|
+
function claimSessionOnce(sessionID: string): boolean {
|
|
1167
|
+
if (claimedSessions.has(sessionID)) return true;
|
|
1168
|
+
if (pendingClaimsDir === undefined || instanceClaim === undefined) return false;
|
|
1169
|
+
try {
|
|
1170
|
+
const pidAliveNow = (pid: number): boolean => {
|
|
1171
|
+
try {
|
|
1172
|
+
process.kill(pid, 0);
|
|
1173
|
+
return true;
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
1176
|
+
}
|
|
1177
|
+
};
|
|
1178
|
+
// DF-1-10: the beat is fresh before the claim lands, so a sibling copy of the module never reads it as orphaned.
|
|
1179
|
+
if (claimRefreshTimer === undefined) instanceClaim.beat();
|
|
1180
|
+
if (!claimPendingSession(pendingClaimsDir, sessionID, {
|
|
1181
|
+
pid: process.pid, now: Date.now(), isAlive: pidAliveNow, token: instanceClaim.token,
|
|
1182
|
+
...(pendingBeatsDir === undefined ? {} : { beatsDir: pendingBeatsDir }),
|
|
1183
|
+
})) return false;
|
|
1184
|
+
} catch (error) {
|
|
1185
|
+
logger.warn("[router] the pending session claim could not be taken", { sessionID, error: describeError(error) });
|
|
1186
|
+
return false;
|
|
1187
|
+
}
|
|
1188
|
+
trackPendingClaim(sessionID);
|
|
1189
|
+
return true;
|
|
1190
|
+
}
|
|
1191
|
+
/** Late-bound: the lease guard exists only once the v2 adapter attaches (FinishAttach `leaseGate`); the wiring reads it per use. */
|
|
1192
|
+
let leaseGateRef: Pick<LeaseGuard, "waitTreeFree"> | undefined;
|
|
1193
|
+
/** Phase 5.1 D11 (v2 only): the plan-task gates' own holders, exempt from the lease wait in their own slot tree. */
|
|
1194
|
+
const planTaskLeaseExemptions = createLeaseSelfExemptions((root) => planTreeKey(root));
|
|
927
1195
|
const {
|
|
928
1196
|
graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
|
|
929
|
-
prepareVerification, startReferenceGc,
|
|
1197
|
+
prepareVerification, startReferenceGc, beginVerificationBounded,
|
|
930
1198
|
sweepVerification, disposeVerification,
|
|
931
|
-
startDispatch, takeDispatch, isDeferred: wiringIsDeferred, finishDeferred, applyLineage, pending,
|
|
1199
|
+
startDispatch, takeDispatch, isDeferred: wiringIsDeferred, directivesFor, finishDeferred, applyLineage, pending,
|
|
932
1200
|
verifyHandles,
|
|
933
1201
|
// 2.4.5: undefined unless `background: true` at plugin start (pending.ts R14).
|
|
934
1202
|
background,
|
|
935
1203
|
} = createVerificationWiring({
|
|
936
1204
|
client: ctx.client,
|
|
1205
|
+
observations: isV2Host ? ctx.routerObservations : undefined,
|
|
937
1206
|
childRunner: ctx.routerChildRunner,
|
|
938
1207
|
onChildSessionCreated: (sid, creator) => depthTracker.recordPluginChild(sid, creator),
|
|
939
1208
|
directory: ctx.directory,
|
|
940
1209
|
getConfig: () => cfg,
|
|
941
1210
|
logger,
|
|
1211
|
+
...(pendingFile === undefined ? {} : {
|
|
1212
|
+
pending: { persist: pendingFile, onVerdict: (entry: PendingEntry, result: SettledVerification) => postHeldVerdict(entry, result) },
|
|
1213
|
+
pendingRestore: pendingFile.load(),
|
|
1214
|
+
// v2 only. Delegating: the guard arrives with the adapter's attach; until then (or without `leases: enforce`) nothing waits.
|
|
1215
|
+
leaseGate: {
|
|
1216
|
+
waitTreeFree: async (tree, owner, deadlineMs, signal) => {
|
|
1217
|
+
if (leaseGateRef === undefined) return { waitedMs: 0, holders: [], fileCount: 0 };
|
|
1218
|
+
// Phase 5.1 D11: a plan-task gate does not wait for its own task's holders in its own slot tree.
|
|
1219
|
+
const exempt = planTaskLeaseExemptions.exemptFor(tree);
|
|
1220
|
+
if (exempt.size === 0) return leaseGateRef.waitTreeFree(tree, owner, deadlineMs, signal);
|
|
1221
|
+
const gate = leaseGateRef;
|
|
1222
|
+
let fileCount = 0;
|
|
1223
|
+
const probe: Pick<LeaseGuard, "waitTreeFree"> = {
|
|
1224
|
+
waitTreeFree: async (...args) => { const r = await gate.waitTreeFree(...args); fileCount = r.fileCount; return r; },
|
|
1225
|
+
};
|
|
1226
|
+
const wait = await waitTreeFreeExcept(probe, tree, owner, exempt, deadlineMs, signal);
|
|
1227
|
+
return { waitedMs: wait.waitedMs, holders: wait.holders, fileCount: wait.holders.length === 0 ? 0 : fileCount };
|
|
1228
|
+
},
|
|
1229
|
+
},
|
|
1230
|
+
}),
|
|
942
1231
|
});
|
|
943
1232
|
// 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
|
|
944
1233
|
// QA-2.1-11: deferred (unref'd timer), so plugin start never holds the project directory with a
|
|
945
1234
|
// git child; dispose cancels it.
|
|
946
|
-
|
|
1235
|
+
// DF-1-1 (v2 only): with `routing.workRoots` configured and non-empty, a location outside every entry is not the plan's:
|
|
1236
|
+
// the start-up reference GC is skipped (it would run git in, and write to, that repository). Unset or empty: unchanged.
|
|
1237
|
+
const outsideWorkRoots = isV2Host && locationOutsideWorkRoots(ctx.directory, cfg.routing?.workRoots);
|
|
1238
|
+
if (outsideWorkRoots) logger.info?.(`[router] ${ctx.directory} is outside routing.workRoots: the start-up reference GC is skipped`);
|
|
1239
|
+
const stopReferenceGc = outsideWorkRoots ? (): void => undefined : startReferenceGc();
|
|
1240
|
+
// Phase 5.1 D8 (v2 only): plan tasks are verified by this instance's dispatch verification engine; v2.ts hands the verifier to
|
|
1241
|
+
// the adapter's executor seam. Nothing is built or handed over on v1.
|
|
1242
|
+
if (isV2Host) {
|
|
1243
|
+
const planTaskVerifier = createPlanTaskVerifier({
|
|
1244
|
+
changedFileStore,
|
|
1245
|
+
beginVerificationBounded,
|
|
1246
|
+
prepareVerification,
|
|
1247
|
+
buildGateDeps,
|
|
1248
|
+
captureBudget: (childSessionID, capReached) => captureBudget(childSessionID, capReached),
|
|
1249
|
+
readCapReached: (childSessionID) => sessionStore.readCapReached(childSessionID),
|
|
1250
|
+
onVerdict: (childSessionID, verdict) => ingest?.onVerdict(childSessionID, verdictOf(verdict), verdictGraderOf(verdict)),
|
|
1251
|
+
abortSession: async (sessionID) => { await ctx.client.session.abort({ path: { id: sessionID } }); },
|
|
1252
|
+
getConfig: () => cfg,
|
|
1253
|
+
git: planTaskGit(),
|
|
1254
|
+
exemptions: planTaskLeaseExemptions,
|
|
1255
|
+
log: (message, detail) => logger.warn(`[verify] ${message}`, detail === undefined ? undefined : { error: describeError(detail) }),
|
|
1256
|
+
});
|
|
1257
|
+
(ctx as RouterPluginInput & { routerOnSlotVerifier?: (verifier: typeof planTaskVerifier) => void }).routerOnSlotVerifier?.(planTaskVerifier);
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
// Phase 1.2 (v2 only): the turn-state registry the adapter injects. Without it (v1, or a v2 host that injects none) nothing
|
|
1261
|
+
// below is registered or buffered, and the system transform keeps pushing the pending list and the late notices.
|
|
1262
|
+
// The registry arrives through the ROUTER_TURN_STATE_ATTACH hook the v2 adapter calls (the only channel); the hook
|
|
1263
|
+
// returns whether the registry was accepted.
|
|
1264
|
+
let turnState: TurnStateRegistry | undefined;
|
|
1265
|
+
const lateBuffer: LateBuffer | undefined = isV2Host ? createLateBuffer() : undefined;
|
|
1266
|
+
const unregisterTurnStateProviders: Array<() => void> = [];
|
|
1267
|
+
let warnedSecondRegistry = false;
|
|
1268
|
+
const attachTurnState = (registry: TurnStateRegistry): boolean => {
|
|
1269
|
+
if (turnState !== undefined) {
|
|
1270
|
+
if (turnState !== registry && !warnedSecondRegistry) {
|
|
1271
|
+
warnedSecondRegistry = true;
|
|
1272
|
+
logger.warn("[router] turn state: a second registry was ignored");
|
|
1273
|
+
}
|
|
1274
|
+
return turnState === registry;
|
|
1275
|
+
}
|
|
1276
|
+
turnState = registry;
|
|
1277
|
+
if (lateBuffer === undefined) return true;
|
|
1278
|
+
try {
|
|
1279
|
+
// Late notices of background runs that did not pass: buffered before the block is built (a builder throw loses
|
|
1280
|
+
// nothing) and kept until router_verify answers their handle.
|
|
1281
|
+
unregisterTurnStateProviders.push(turnState.registerTurnStateProvider({
|
|
1282
|
+
name: "late",
|
|
1283
|
+
order: 10,
|
|
1284
|
+
render(sid) {
|
|
1285
|
+
if (background === undefined) return undefined;
|
|
1286
|
+
lateBuffer.add(sid, background.takeNotices(sid));
|
|
1287
|
+
lateBuffer.touch(sid);
|
|
1288
|
+
return buildLateNoticeBlock(lateBuffer.list(sid));
|
|
1289
|
+
},
|
|
1290
|
+
active(sid) {
|
|
1291
|
+
return lateBuffer.list(sid).length > 0;
|
|
1292
|
+
},
|
|
1293
|
+
}));
|
|
1294
|
+
// This orchestrator's still-unverified delegations (the same arguments the v1 transform passes).
|
|
1295
|
+
unregisterTurnStateProviders.push(turnState.registerTurnStateProvider({
|
|
1296
|
+
name: "pending",
|
|
1297
|
+
order: 20,
|
|
1298
|
+
render(sid) {
|
|
1299
|
+
return buildPendingListBlock(pending.listPending(sid, { verifying: background !== undefined }));
|
|
1300
|
+
},
|
|
1301
|
+
active(sid) {
|
|
1302
|
+
return pending.listPending(sid, { verifying: background !== undefined }).length > 0;
|
|
1303
|
+
},
|
|
1304
|
+
}));
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
logger.warn("[router] turn state: late/pending providers not registered", { error: scrubText(String(error)) });
|
|
1307
|
+
// Nothing stays half registered: the system transform keeps delivering through the system array.
|
|
1308
|
+
for (const unregister of unregisterTurnStateProviders.splice(0)) {
|
|
1309
|
+
try {
|
|
1310
|
+
unregister();
|
|
1311
|
+
} catch (unregisterError) {
|
|
1312
|
+
logger.warn("[router] turn state: unregistering a provider failed", { error: scrubText(String(unregisterError)) });
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
turnState = undefined;
|
|
1316
|
+
return false;
|
|
1317
|
+
}
|
|
1318
|
+
return true;
|
|
1319
|
+
};
|
|
947
1320
|
|
|
948
1321
|
// Best-effort, secret-free delegate scorecard dump (counts only).
|
|
949
1322
|
const dumpDelegateScorecard = (
|
|
@@ -969,7 +1342,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
969
1342
|
// #84 P2.1: the v2 adapter's role path reads the bypass state (the router gate does not run while bypassed, S10/P-9).
|
|
970
1343
|
(ctx as RouterPluginInput & { routerOnBypassState?: (read: () => boolean) => void }).routerOnBypassState?.(() => bypassed);
|
|
971
1344
|
/** QA-P21-1-3: the budget snapshot of a role child as the signals AND the adapter's budget notice read it (guard + read cap). */
|
|
972
|
-
const roleBudgetSnapshot = (childSessionID: string) =>
|
|
1345
|
+
const roleBudgetSnapshot = (childSessionID: string) => {
|
|
1346
|
+
consumeExecutorChildRound(childSessionID);
|
|
1347
|
+
return captureBudget(childSessionID, sessionStore.readCapReached(childSessionID));
|
|
1348
|
+
};
|
|
973
1349
|
(ctx as RouterPluginInput & { routerOnBudgetSnapshot?: (read: typeof roleBudgetSnapshot) => void }).routerOnBudgetSnapshot?.(roleBudgetSnapshot);
|
|
974
1350
|
/**
|
|
975
1351
|
* QA-G-A3-2 (§2.9 E6, R7 REFUSAL_CAP): a role child's call refused where the guard's before-hook never sees it — the v2
|
|
@@ -1034,21 +1410,30 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1034
1410
|
const ADVISOR_ROLE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
1035
1411
|
/**
|
|
1036
1412
|
* #84 P2.2: the extras of the cost doctor's roles checks — the host and, in roles mode with a live engine, the role × tier
|
|
1037
|
-
* statistics and
|
|
1038
|
-
* (`{ host }` only
|
|
1413
|
+
* statistics, unknown-binding counts and tier dispatch count over {@link ADVISOR_ROLE_WINDOW_MS}, plus process-lifetime orphan
|
|
1414
|
+
* counters. The v2 adapter uses this same gatherer. Tiers mode and v1 read nothing (`{ host }` only); a read failure leaves
|
|
1415
|
+
* the windowed statistics out but keeps the process counters.
|
|
1039
1416
|
*/
|
|
1040
1417
|
const advisorExtras = async (): Promise<AdvisorExtras> => {
|
|
1041
1418
|
const host = isV2Host ? "v2" as const : "v1" as const;
|
|
1042
1419
|
if (rolesNow().size === 0) return { host };
|
|
1420
|
+
const orphanCounters = readRoleOrphans().counters;
|
|
1043
1421
|
const live = ingestSettings(cfg, "v2");
|
|
1044
|
-
if (live === null) return { host }; // engine static: no decision log
|
|
1422
|
+
if (live === null) return { host, orphanCounters }; // engine static: no decision log
|
|
1045
1423
|
try {
|
|
1046
1424
|
const read = await createPersister(live.outcomesDir, nodePersistDeps({ warn: () => undefined })).readRows();
|
|
1047
1425
|
const since = Date.now() - ADVISOR_ROLE_WINDOW_MS;
|
|
1048
|
-
|
|
1426
|
+
const window = { since, until: null };
|
|
1427
|
+
return {
|
|
1428
|
+
host,
|
|
1429
|
+
roleStats: summarizeRoles(null, read.rows, window),
|
|
1430
|
+
tierDispatches: tierDispatchCount(read.rows, since),
|
|
1431
|
+
unknownBindings: countUnknownBindings(read.rows, window),
|
|
1432
|
+
orphanCounters,
|
|
1433
|
+
};
|
|
1049
1434
|
} catch (error) {
|
|
1050
1435
|
logger.warn("[router] cost doctor: the role statistics are unavailable", { error: describeError(error) });
|
|
1051
|
-
return { host };
|
|
1436
|
+
return { host, orphanCounters };
|
|
1052
1437
|
}
|
|
1053
1438
|
};
|
|
1054
1439
|
const gatherAdvisorInputs = async (
|
|
@@ -1091,6 +1476,28 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1091
1476
|
});
|
|
1092
1477
|
return annotateRuntime;
|
|
1093
1478
|
};
|
|
1479
|
+
if (isV2Host) {
|
|
1480
|
+
executorInput?.routerOnPlanAnnotate?.(async (steps) => {
|
|
1481
|
+
const current = loadConfig(projectDir);
|
|
1482
|
+
const runtime = annotatePlanRuntime();
|
|
1483
|
+
const prepared = await runtime?.prepare(current);
|
|
1484
|
+
const routing = prepared?.routing ?? resolveRouting(current, "v2");
|
|
1485
|
+
const classifyDeps = prepared && runtime ? runtime.classifyDeps(prepared) : {
|
|
1486
|
+
cfg: current, settings: { ...routing.classifier, backend: "rules" as const },
|
|
1487
|
+
minClassConfidence: routing.minClassConfidence, backend: null, logger,
|
|
1488
|
+
};
|
|
1489
|
+
let agents: HostAgentInfo[] | null = null;
|
|
1490
|
+
if (prepared && ctx.routerAgents !== undefined) {
|
|
1491
|
+
try { agents = agentInfosForPlan(await ctx.routerAgents()); }
|
|
1492
|
+
catch (error) { logger.warn("[router] executor: the agent list is unavailable; tiers are annotated without it", { error: describeError(error) }); }
|
|
1493
|
+
}
|
|
1494
|
+
return annotateSteps(steps, {
|
|
1495
|
+
cfg: current, routing, agents, store: prepared?.store ?? null, logger,
|
|
1496
|
+
...(prepared ? { pricing: (model) => prepared.catalog.pricing(model), session: prepared.session } : {}),
|
|
1497
|
+
classifyMany: (inputs) => classifyPlanSteps(inputs, { ...classifyDeps, routeLinePositions: "any" }),
|
|
1498
|
+
});
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1094
1501
|
// v1 only (A28): the host's agent list for the text-only roles line, read through `client.app.agents()` and never fetched unless
|
|
1095
1502
|
// `routing.roles` is set explicitly. It is refreshed IN THE BACKGROUND (QA-2.4-13): a turn never waits for it. The first turn after start
|
|
1096
1503
|
// has no list yet and gets the baseline prompt; later turns use the last list, stale while the next one is fetched (every minute). A
|
|
@@ -1292,6 +1699,10 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1292
1699
|
// v1 the set is exactly the previous one (router_run and router_request_authority are not registered; router_git_* keep their
|
|
1293
1700
|
// directory resolution). Switching to roles mode registers them on the next start.
|
|
1294
1701
|
const rolesAtStart = rolesNow().size > 0;
|
|
1702
|
+
// G-16: on v2 off Windows, one notice per process, only for a config that asks for the executor (roles mode at start with
|
|
1703
|
+
// enforced leases and verification not disabled: the prerequisites v2.ts's executor discovery checks).
|
|
1704
|
+
if (isV2Host && !executorPlatform && rolesAtStart && resolveRouting(cfg, "v2").leases.mode === "enforce"
|
|
1705
|
+
&& cfg.enforcement?.verify?.require !== "never") warnExecutorPlatformOnce(logger);
|
|
1295
1706
|
const dynamicRolesAtStart = [...rolesNow().values()].some((spec) => spec.authority.mode === "dynamic");
|
|
1296
1707
|
/**
|
|
1297
1708
|
* Cross-repo 3b.4 (SD-3b-1): `router_git_*` declare `root` only on v2, in roles mode, with `routing.repoParents` non-empty at start
|
|
@@ -1352,6 +1763,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1352
1763
|
};
|
|
1353
1764
|
/** A fresh role child's first call: its exact binding names the dispatch's call, whose cap is registered once. */
|
|
1354
1765
|
const applyPendingRoleCap = (child: string): void => {
|
|
1766
|
+
consumeExecutorChildRound(child);
|
|
1355
1767
|
if (pendingRoleCaps.size === 0) return;
|
|
1356
1768
|
const binding = currentBinding(child, { maxOf: roleMaxOf });
|
|
1357
1769
|
const callID = binding?.kind === "exact" ? binding.candidates[0] : undefined;
|
|
@@ -1360,6 +1772,48 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1360
1772
|
pendingRoleCaps.delete(callID);
|
|
1361
1773
|
registerRoleCap(child, pending.agent, pending.cap);
|
|
1362
1774
|
};
|
|
1775
|
+
/**
|
|
1776
|
+
* QA-PDF21-2-11: an executor budget resume (a launch with `req.resume`) opens a new guard round and a new read-cap round for
|
|
1777
|
+
* its child, exactly as a routed resume does (`noteRoleDispatch`): the per-dispatch budget and the read counter restart, the
|
|
1778
|
+
* cumulative ceiling stays. A cap the launch prompt names replaces the child's previous one.
|
|
1779
|
+
*/
|
|
1780
|
+
const beginExecutorResumeRound = (child: string, agent: string, prompt: string): void => {
|
|
1781
|
+
publishExecutorChildRound(child, agent, executorLineCap(prompt), true);
|
|
1782
|
+
consumeExecutorChildRound(child);
|
|
1783
|
+
};
|
|
1784
|
+
/**
|
|
1785
|
+
* QA-PDF21-2-20: the read cap of a plan child's launch prompt is the executor's own cap line ONLY (`EXECUTOR_READ_CAP_LINE`,
|
|
1786
|
+
* right after the "PLAN CONTEXT" line, DF-2-9), parsed by `parseCapDirective`. A prompt without it (a non-editing task, a
|
|
1787
|
+
* resume) names no cap: plan text — even a `CAP` token split across lines, which the line-bound neutralization misses — never
|
|
1788
|
+
* sets one.
|
|
1789
|
+
*/
|
|
1790
|
+
const executorLineCap = (prompt: string): Cap | null =>
|
|
1791
|
+
prompt.startsWith(`PLAN CONTEXT\n${EXECUTOR_READ_CAP_LINE}\n`) ? parseCapDirective(EXECUTOR_READ_CAP_LINE) : null;
|
|
1792
|
+
/**
|
|
1793
|
+
* QA-PDF21-2-20: a plan child the executor just bound gets the read cap of its launch prompt's cap line, through the state a
|
|
1794
|
+
* routed role dispatch uses (`registerRoleCap`). A plan child has no parent `task` call, so `applyPendingRoleCap` never
|
|
1795
|
+
* reaches it, and its role agent is no tier, so `registerFromChatMessage` does not either.
|
|
1796
|
+
*/
|
|
1797
|
+
const applyExecutorChildCap = (child: string, agent: string, prompt: string): void => {
|
|
1798
|
+
publishExecutorChildRound(child, agent, executorLineCap(prompt), false);
|
|
1799
|
+
consumeExecutorChildRound(child);
|
|
1800
|
+
};
|
|
1801
|
+
const executorRoundsSeen = new Map<string, number>();
|
|
1802
|
+
const consumeExecutorChildRound = (child: string): void => {
|
|
1803
|
+
if (!isV2Host) return;
|
|
1804
|
+
const published = executorChildRound(child);
|
|
1805
|
+
if (published === undefined || executorRoundsSeen.get(child) === published.round) return;
|
|
1806
|
+
setBounded(executorRoundsSeen, child, published.round);
|
|
1807
|
+
rememberRoleSession(child, published.agent);
|
|
1808
|
+
sessionStore.markChildSession(child);
|
|
1809
|
+
guardStore.beginDispatch(child);
|
|
1810
|
+
if (!sessionStore.resumeRoleSession(child, published.cap) && published.cap !== null) registerRoleCap(child, published.agent, published.cap);
|
|
1811
|
+
};
|
|
1812
|
+
// QA-PDF21-2-11/-20: the v2 adapter's executor bookkeeping reaches the guard store and the read-cap state through these.
|
|
1813
|
+
(ctx as RouterPluginInput & { routerOnExecutorChildGuard?: (port: ExecutorChildGuardPort) => void }).routerOnExecutorChildGuard?.({
|
|
1814
|
+
beginResumeRound: beginExecutorResumeRound,
|
|
1815
|
+
applyCap: applyExecutorChildCap,
|
|
1816
|
+
});
|
|
1363
1817
|
/**
|
|
1364
1818
|
* #84 P3.3 DF2-F1: where the `task` call `callID` is verified. A routed role dispatch (`routedRoleOf`, kept until the adapter's
|
|
1365
1819
|
* `execute.after` is done) in its `verifyRoot` — the grant's work root (a resume keeps the child's bound root, QA-P33F1-1-1), else
|
|
@@ -1367,8 +1821,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1367
1821
|
* block's `cwd:`, the order the dispatch-time detection uses, nit 3) still wins inside it, by P2.3's rule (QA-P33F1-1-2); one
|
|
1368
1822
|
* outside it is refused by the gate. Every other dispatch: the explicit cwd, as before (I1).
|
|
1369
1823
|
*/
|
|
1370
|
-
const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }): VerificationScope =>
|
|
1371
|
-
verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), typeof callID === "string" ?
|
|
1824
|
+
const verificationScopeOf = (callID: unknown, args: Record<string, unknown> | undefined, dod: { cwd?: string }, restoredWorkRoot?: string): VerificationScope =>
|
|
1825
|
+
verificationScope(requestedVerificationCwd(args?.cwd, dod.cwd), (typeof callID === "string" ? routedRoleFor(callID)?.verifyRoot : undefined) ?? restoredWorkRoot);
|
|
1372
1826
|
/** The prompt as the orchestrator wrote it: without the router's role dispatch header (P2g.3, OD6) and its nonce line (handoff 18). */
|
|
1373
1827
|
const withoutNonceLine = (prompt: string): string => stripDispatchHeader(prompt).replace(/\r?\n?OMR_NONCE=[A-Za-z0-9_-]+\s*$/, "");
|
|
1374
1828
|
/**
|
|
@@ -1483,28 +1937,43 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1483
1937
|
roleBudgetPeaks.delete(sessionID);
|
|
1484
1938
|
for (const [callID, sent] of roleDispatchTexts) if (sent.parentSessionID === sessionID) roleDispatchTexts.delete(callID);
|
|
1485
1939
|
};
|
|
1486
|
-
|
|
1940
|
+
const routerHooks: Awaited<ReturnType<Plugin>> = {
|
|
1487
1941
|
// Warnings post to /log fire-and-forget, which loses the message when the
|
|
1488
1942
|
// process is about to exit — `opencode run` and `opencode debug` are short
|
|
1489
1943
|
// enough for that to be the normal case. Verified against opencode 1.18.16
|
|
1490
1944
|
// that dispose is both called and awaited, so flushing here is enough.
|
|
1491
1945
|
dispose: async () => {
|
|
1492
1946
|
stopReferenceGc();
|
|
1947
|
+
// Phase 1.2: the turn-state providers of this instance leave the (adapter-owned) registry.
|
|
1948
|
+
for (const unregister of unregisterTurnStateProviders.splice(0)) unregister();
|
|
1949
|
+
// QA-2.1-21 (v2 only): the held gates this instance started (and their verdict posts) end before the pending registry
|
|
1950
|
+
// and the verification wiring go; bounded, a gate still running then ends through the disposals below.
|
|
1951
|
+
await waitHeldGates(HELD_GATES_DISPOSE_BOUND_MS);
|
|
1493
1952
|
// Stop new advisor work and finish state/claim writes and lock removal before teardown.
|
|
1494
1953
|
await advisorNotifier?.dispose();
|
|
1495
1954
|
// 2.4.5: abort a background run and drop its queue and notices before the registry goes.
|
|
1496
1955
|
background?.dispose();
|
|
1497
1956
|
// 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
|
|
1498
1957
|
pending.dispose();
|
|
1958
|
+
// QA-2.1-13 (v2 only): stop re-stamping and give back every session claim this process took at adoption.
|
|
1959
|
+
releaseAllPendingClaims();
|
|
1499
1960
|
// 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
|
|
1500
1961
|
await disposeVerification();
|
|
1501
1962
|
// 2.1.3: flush and release the outcome bundle held by this instance (never rejects).
|
|
1502
1963
|
await ingest?.dispose();
|
|
1503
1964
|
await annotateRuntime?.dispose();
|
|
1504
1965
|
await attemptRecorder?.dispose();
|
|
1966
|
+
// QA-2.1-22 (v2 only): after the last append of this instance; the last journal of the path removes this process's writer mark.
|
|
1967
|
+
await pendingFile?.dispose();
|
|
1505
1968
|
await logger.flush();
|
|
1506
1969
|
},
|
|
1507
1970
|
tool: {
|
|
1971
|
+
...(rolesAtStart && routerPlan !== undefined ? { router_plan: {
|
|
1972
|
+
...routerPlan,
|
|
1973
|
+
execute: async (args, context) => await planActionCallerAllowed(context?.sessionID, args?.action, args?.planId)
|
|
1974
|
+
? routerPlan.execute(args, context)
|
|
1975
|
+
: `[router_plan] ${planCallerRefusal}`,
|
|
1976
|
+
} } : {}),
|
|
1508
1977
|
// QA-G-A2-2: a role session's work root must belong to the repository its dispatch listed the worktrees in (this directory's).
|
|
1509
1978
|
...gitTools(rolesAtStart ? {
|
|
1510
1979
|
resolveWorkRoot: resolveWorkRootFor("router_git"), ...(ctx.directory ? { dispatchRepository: ctx.directory } : {}),
|
|
@@ -1876,7 +2345,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
1876
2345
|
let verification;
|
|
1877
2346
|
try {
|
|
1878
2347
|
// Cross-repo P3a (D23 as amended, QA C1): the dispatch's own start, the `since` of W's ignored-module listing.
|
|
1879
|
-
verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline, dispatchStart?.dispatchedAt);
|
|
2348
|
+
verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline, dispatchStart?.dispatchedAt, undefined, isV2Host ? toolCtx?.sessionID : undefined);
|
|
1880
2349
|
} catch (error) {
|
|
1881
2350
|
gateDeadline.dispose();
|
|
1882
2351
|
throw error;
|
|
@@ -2148,6 +2617,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2148
2617
|
// R6: handles are scoped by the calling session; without one, every handle is unknown.
|
|
2149
2618
|
const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
|
|
2150
2619
|
const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
|
|
2620
|
+
// Phase 1.2 (v2 only): the late notices this report answers stop being retained for the turn-state tail.
|
|
2621
|
+
lateBuffer?.release(sessionID, answeredHandles(report.items));
|
|
2151
2622
|
return report.text;
|
|
2152
2623
|
} catch (error) {
|
|
2153
2624
|
logger.warn("[verify] router_verify failed", { error: scrubText(String(error)) });
|
|
@@ -2334,6 +2805,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2334
2805
|
// non-subagent sessions or when enforcement is off (GA-1 preserved).
|
|
2335
2806
|
// -----------------------------------------------------------------------
|
|
2336
2807
|
"tool.execute.before": async (input: any, output: any) => {
|
|
2808
|
+
if (typeof input?.sessionID === "string") consumeExecutorChildRound(input.sessionID);
|
|
2809
|
+
rememberTaskArgs(input, output); // phase 2.1 (v2 only; a no-op on v1)
|
|
2337
2810
|
// #84 P2.1: a role child's own call names its role agent (the v2 adapter passes the calling agent). Remembered even while
|
|
2338
2811
|
// bypassed (the work-root resolver and the authority tool are authority, not routing), and marked a child session: role
|
|
2339
2812
|
// agents are subagents, so the guard engages from their first call. Never on v1 / in tiers mode (no role table).
|
|
@@ -2525,6 +2998,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2525
2998
|
// treats them as ground truth rather than advisory system noise.
|
|
2526
2999
|
// -----------------------------------------------------------------------
|
|
2527
3000
|
"tool.execute.after": async (input: any, output: any) => {
|
|
3001
|
+
if (typeof input?.sessionID === "string") consumeExecutorChildRound(input.sessionID);
|
|
2528
3002
|
if (input?.tool === "grep" && typeof output.output === "string") {
|
|
2529
3003
|
const tier = input.agent ?? pluginAgentSessions.get(input.sessionID) ?? sessionStore.getTier(input.sessionID);
|
|
2530
3004
|
const definition = tier && getActiveTiers(cfg)[tier];
|
|
@@ -2629,252 +3103,9 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2629
3103
|
// Option (i): verify-dispatch around the built-in `task` tool (advisory-grade —
|
|
2630
3104
|
// we observe the finished task result and append a forcing note if it is not
|
|
2631
3105
|
// accepted; we cannot retry a task call that already finished).
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
2636
|
-
} catch {
|
|
2637
|
-
// fall through with mode "off"
|
|
2638
|
-
}
|
|
2639
|
-
const requireMode = cfg.enforcement?.verify?.require;
|
|
2640
|
-
if (shouldVerifyTask(input.tool, mode, requireMode)) {
|
|
2641
|
-
try {
|
|
2642
|
-
// pending.ts R11: the producer's changes landed by now.
|
|
2643
|
-
const returnedAt = Date.now();
|
|
2644
|
-
const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
|
|
2645
|
-
const producerTier =
|
|
2646
|
-
typeof input?.args?.subagent_type === "string"
|
|
2647
|
-
? input.args.subagent_type
|
|
2648
|
-
: "";
|
|
2649
|
-
const dod = buildDelegationDoD({
|
|
2650
|
-
prompt: input?.args?.prompt,
|
|
2651
|
-
description: input?.args?.description,
|
|
2652
|
-
});
|
|
2653
|
-
// DF2-F1: a role dispatch is verified in its verification root (capture, change set, checks, deferral); a requested
|
|
2654
|
-
// cwd outside that root is refused by the gate below, never deferred to run there later.
|
|
2655
|
-
const scope = verificationScopeOf(input.callID, input?.args, dod);
|
|
2656
|
-
const cwdSource = requestedVerificationCwdSource(input?.args?.cwd, dod.cwd);
|
|
2657
|
-
const effectiveCwd = scope.cwd;
|
|
2658
|
-
const dispatchID = `task:${input.sessionID}:${input.callID}`;
|
|
2659
|
-
// #84 QA-G-B-2-1: a routed role dispatch keeps its child's verification lineage; a resume that CARRIES the acceptance of an
|
|
2660
|
-
// earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
|
|
2661
|
-
const routedRole = typeof input.callID === "string" ? routedRoleOf(input.callID) : undefined;
|
|
2662
|
-
const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
|
|
2663
|
-
// Cross-repo P2a.3 (v2 only): where each check of a routed role dispatch runs. Tier dispatches resolve nothing.
|
|
2664
|
-
// P2e.6: valid per-check `cwd=`/`scope=` keys may be deferred (the placements travel with the handle, and router_verify
|
|
2665
|
-
// runs each check where it was placed); only a refusal is verified at once, below.
|
|
2666
|
-
const placement = routedRole === undefined ? undefined : resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routedRole) });
|
|
2667
|
-
// P2b.7 (OD1=B, v2 only): a tier dispatch with a per-check `cwd=` is unverifiable (the gate refuses it); it is never deferred.
|
|
2668
|
-
const tierRefusal = routedRole === undefined && ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
|
|
2669
|
-
// P2e.6: a refused placement or the OD1 tier refusal is certain now: verified at once, never deferred.
|
|
2670
|
-
const placementRefused = tierRefusal !== undefined || placement?.refused !== undefined;
|
|
2671
|
-
const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
|
|
2672
|
-
const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
|
|
2673
|
-
const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
|
|
2674
|
-
// 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
|
|
2675
|
-
const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
|
|
2676
|
-
const trivial = childSessionID
|
|
2677
|
-
? sessionStore.isTrivial(childSessionID)
|
|
2678
|
-
: false;
|
|
2679
|
-
// QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
|
|
2680
|
-
// deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
|
|
2681
|
-
// B2: the reason a deferred finish refused for a branch switch, carried into the artefact below.
|
|
2682
|
-
let deferredSwitch: string | undefined;
|
|
2683
|
-
if (!scope.outside && !carriedRole && !placementRefused && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
|
|
2684
|
-
// Section 1.5-16: no gate, no test process; the result goes back now with the
|
|
2685
|
-
// footer, which is appended last and never says accepted or verified.
|
|
2686
|
-
const finish = await finishDeferred(changedFileStore, {
|
|
2687
|
-
dispatchID,
|
|
2688
|
-
orchestratorSessionID,
|
|
2689
|
-
producerSessionID: childSessionID ?? "",
|
|
2690
|
-
producerTier,
|
|
2691
|
-
description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
|
|
2692
|
-
cwd: effectiveCwd,
|
|
2693
|
-
// I2 (P2.3): the change observation stays in W; the registration's cwd above is the check base (F5).
|
|
2694
|
-
...(scope.workRoot !== undefined ? { captureRoot: captureRootOf(scope) } : {}),
|
|
2695
|
-
// #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
|
|
2696
|
-
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
2697
|
-
dod,
|
|
2698
|
-
dispatchedAt: start.dispatchedAt,
|
|
2699
|
-
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
|
|
2700
|
-
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
2701
|
-
// Cross-repo P2e.6: the checks' placements (registered with the handle), and the full scope on v2 (OD-P2e-2).
|
|
2702
|
-
...(placement?.placements !== undefined ? { placements: placement.placements } : {}),
|
|
2703
|
-
...(fullScopeOf(cfg) ? { fullScope: true } : {}),
|
|
2704
|
-
});
|
|
2705
|
-
if (finish.deferred) {
|
|
2706
|
-
output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
|
|
2707
|
-
// The dispatch record is cleared by finishDeferred once its capture settled.
|
|
2708
|
-
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
2709
|
-
return;
|
|
2710
|
-
}
|
|
2711
|
-
if (finish.reason === "branch-switched") deferredSwitch = finish.detail;
|
|
2712
|
-
// QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
|
|
2713
|
-
}
|
|
2714
|
-
// Same bound as the delegate gate: one deadline per invocation,
|
|
2715
|
-
// a withTimeout ceiling, and abort-on-reject so a hung check or
|
|
2716
|
-
// grader cannot hold the after-hook (and its process tree) open.
|
|
2717
|
-
// The deadline exists before prepareVerification (T2 P0,
|
|
2718
|
-
// QA-2.1-4), so preparation counts against gateBudgetMs.
|
|
2719
|
-
const { gateBudgetMs } = resolveVerifyBudget(cfg);
|
|
2720
|
-
const gateDeadline = createDeadline(gateBudgetMs);
|
|
2721
|
-
let verification;
|
|
2722
|
-
try {
|
|
2723
|
-
// Cross-repo P3a (D23 as amended, QA C1): the dispatch's start (takeDispatch), the `since` of W's ignored-module
|
|
2724
|
-
// listing. A start that was never remembered reads as now (the return), which lists nothing older: never stale inputs.
|
|
2725
|
-
verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", captureRootOf(scope), gateDeadline, start.dispatchedAt);
|
|
2726
|
-
} catch (error) {
|
|
2727
|
-
gateDeadline.dispose();
|
|
2728
|
-
throw error;
|
|
2729
|
-
}
|
|
2730
|
-
// QA2 F4: a switch the deferred finish saw (and this gate's own read missed) is part of this attempt before the role
|
|
2731
|
-
// lineage records it; its change set may hold the other branch's commits, so it is unavailable.
|
|
2732
|
-
if (deferredSwitch !== undefined && verification.branchSwitch === undefined) {
|
|
2733
|
-
verification = { ...verification, branchSwitch: deferredSwitch, changeBaseline: "unavailable" as const };
|
|
2734
|
-
}
|
|
2735
|
-
// #84 QA-G-B-2-1: the role child's lineage — this attempt starts it (its own block) or is judged on everything the child
|
|
2736
|
-
// changed since the attempt that introduced the carried block, against that attempt's reference.
|
|
2737
|
-
if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
|
|
2738
|
-
// #84 P2.1: a role agent follows the return contract (handoff 26; roles mode only).
|
|
2739
|
-
const roleProducer = roleSpecOf(producerTier) !== undefined;
|
|
2740
|
-
const artefact = {
|
|
2741
|
-
changedFiles: verification.changedFiles,
|
|
2742
|
-
changeBaseline: verification.changeBaseline,
|
|
2743
|
-
...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
|
|
2744
|
-
...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
|
|
2745
|
-
...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
|
|
2746
|
-
? { unattributedWriters: verification.unattributedWriters } : {}),
|
|
2747
|
-
...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
|
|
2748
|
-
finalReturnText,
|
|
2749
|
-
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
2750
|
-
producerSessionID: childSessionID ?? "",
|
|
2751
|
-
producerTier,
|
|
2752
|
-
...(roleProducer ? { returnContract: true } : {}),
|
|
2753
|
-
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule; every mode): the guard's budget state when the task
|
|
2754
|
-
// returned, not when the gate runs. Without a stop it judges like the live read it replaces.
|
|
2755
|
-
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
2756
|
-
};
|
|
2757
|
-
|
|
2758
|
-
// Read-only / research delegation: an auto-inferred, criteria-only DoD on a
|
|
2759
|
-
// native Task() that changed no files is exploration, not implementation.
|
|
2760
|
-
// There is nothing concrete to verify, so skip rather than grade the
|
|
2761
|
-
// findings against the task's own summary, which otherwise appends false
|
|
2762
|
-
// "not accepted" notes to legitimate read-only research delegations.
|
|
2763
|
-
// Explicit [acceptance] blocks (source != "inferred") and inferred
|
|
2764
|
-
// deterministic checks (dod.kind === "deterministic") still verify normally.
|
|
2765
|
-
if (
|
|
2766
|
-
dod.source === "inferred" &&
|
|
2767
|
-
dod.kind === "checker" &&
|
|
2768
|
-
artefact.changedFiles.length === 0
|
|
2769
|
-
) {
|
|
2770
|
-
gateDeadline.dispose();
|
|
2771
|
-
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
2772
|
-
changedFileStore.clear(dispatchID);
|
|
2773
|
-
return;
|
|
2774
|
-
}
|
|
2775
|
-
|
|
2776
|
-
const gateGraderSessions = new Set<string>();
|
|
2777
|
-
const completedFailures: string[] = [];
|
|
2778
|
-
// Keep the native grader unparented on the backend; only depth tracking uses its caller.
|
|
2779
|
-
const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
|
|
2780
|
-
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
2781
|
-
// #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
|
|
2782
|
-
if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
|
|
2783
|
-
let res;
|
|
2784
|
-
try {
|
|
2785
|
-
res = await withTimeout(
|
|
2786
|
-
accept(
|
|
2787
|
-
{
|
|
2788
|
-
dod,
|
|
2789
|
-
trivial,
|
|
2790
|
-
mode: "modeA",
|
|
2791
|
-
// Native task has no cwd argument; the acceptance block can supply it.
|
|
2792
|
-
...(scope.requested ? { cwd: scope.requested } : {}),
|
|
2793
|
-
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
2794
|
-
...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
|
|
2795
|
-
// Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
|
|
2796
|
-
...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
|
|
2797
|
-
// Cross-repo P2b.5 (v2 only): where each check of a routed role dispatch runs, or the check the router refused.
|
|
2798
|
-
...(placement?.placements !== undefined ? { checkPlacements: placement.placements } : {}),
|
|
2799
|
-
...(placement?.refused !== undefined ? { refusedCheck: placement.refused } : tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
|
|
2800
|
-
},
|
|
2801
|
-
artefact,
|
|
2802
|
-
gateDeps,
|
|
2803
|
-
),
|
|
2804
|
-
// What preparation left of the gate budget (QA-2.1-4).
|
|
2805
|
-
gateDeadline.remaining(),
|
|
2806
|
-
"verification gate",
|
|
2807
|
-
);
|
|
2808
|
-
} catch (error) {
|
|
2809
|
-
gateDeadline.abort(
|
|
2810
|
-
error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
|
|
2811
|
-
);
|
|
2812
|
-
if (error instanceof RouterTimeoutError) {
|
|
2813
|
-
for (const gsid of gateGraderSessions) {
|
|
2814
|
-
try {
|
|
2815
|
-
await ctx.client.session.abort({ path: { id: gsid } });
|
|
2816
|
-
} catch {
|
|
2817
|
-
// best-effort: the gate result stands either way
|
|
2818
|
-
}
|
|
2819
|
-
}
|
|
2820
|
-
}
|
|
2821
|
-
res = unverifiableGateResult(
|
|
2822
|
-
error instanceof RouterTimeoutError
|
|
2823
|
-
? `verification gate timed out after ${gateBudgetMs}ms`
|
|
2824
|
-
: `verification unavailable: ${scrubText(String(error))}`,
|
|
2825
|
-
dod.source,
|
|
2826
|
-
cfg.enforcement?.verify?.strictUnverifiable,
|
|
2827
|
-
completedFailures,
|
|
2828
|
-
);
|
|
2829
|
-
} finally {
|
|
2830
|
-
gateDeadline.dispose();
|
|
2831
|
-
}
|
|
2832
|
-
// pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
|
|
2833
|
-
// on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
|
|
2834
|
-
res = applyLineage(res, {
|
|
2835
|
-
orchestratorSessionID,
|
|
2836
|
-
root: verification.snapshot?.root,
|
|
2837
|
-
dispatchID,
|
|
2838
|
-
dispatchedAt: start.dispatchedAt,
|
|
2839
|
-
returnedAt,
|
|
2840
|
-
strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
|
|
2841
|
-
});
|
|
2842
|
-
// QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
|
|
2843
|
-
res = applyDispatchCaveats(res, verification);
|
|
2844
|
-
// M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
|
|
2845
|
-
// #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
|
|
2846
|
-
if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict), verdictGraderOf(res.verdict));
|
|
2847
|
-
if (!res.accepted && !res.verdict.skipped) {
|
|
2848
|
-
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
2849
|
-
const li = ladder.indexOf(producerTier);
|
|
2850
|
-
const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
|
|
2851
|
-
// Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): absent when false, so the note is unchanged.
|
|
2852
|
-
const incomplete = isIncompleteVerdict(res.verdict);
|
|
2853
|
-
let note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier, ...(incomplete ? { incomplete: true } : {}) }));
|
|
2854
|
-
// P-8 (handoff 39): a role agent is resumed on a higher tier of its range, never re-run on a tier agent.
|
|
2855
|
-
// QA-P21-1-4: only after a FAIL (an unverifiable result keeps the generic line: there is nothing to escalate on).
|
|
2856
|
-
// QA-P21-2-2: the hint promises the raise, and records it for this parent's next resume of the child.
|
|
2857
|
-
const roleHint = roleProducer && !incomplete && res.verdict.outcome === "fail" && childSessionID
|
|
2858
|
-
? roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID) : null;
|
|
2859
|
-
const genericNext = "NEXT: address the above and re-run the delegation; do not treat the prior result as complete.";
|
|
2860
|
-
if (roleHint !== null && note.endsWith(genericNext)) note = note.slice(0, note.length - genericNext.length) + scrubText(roleHint);
|
|
2861
|
-
output.output =
|
|
2862
|
-
typeof output.output === "string"
|
|
2863
|
-
? output.output + "\n\n" + note
|
|
2864
|
-
: note;
|
|
2865
|
-
}
|
|
2866
|
-
// QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
|
|
2867
|
-
// check stays silent unless it carries caveats or notes.
|
|
2868
|
-
if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
|
|
2869
|
-
output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
|
|
2870
|
-
}
|
|
2871
|
-
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
2872
|
-
changedFileStore.clear(dispatchID);
|
|
2873
|
-
} catch {
|
|
2874
|
-
// fail-closed: a verification error must NEVER throw out of the after-hook
|
|
2875
|
-
}
|
|
2876
|
-
}
|
|
2877
|
-
}
|
|
3106
|
+
await finishDispatch(input, output, unbannered);
|
|
3107
|
+
// QA-SYNC1-14: a foreground finish settled here; a background call's arguments stay for its finish (child end).
|
|
3108
|
+
if (input?.tool === "task" && typeof input.callID === "string" && !backgroundCalls.has(input.callID)) forgetTaskArgs(input.callID);
|
|
2878
3109
|
},
|
|
2879
3110
|
|
|
2880
3111
|
// -----------------------------------------------------------------------
|
|
@@ -2922,12 +3153,18 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
2922
3153
|
if (key.startsWith(`${id}:`)) depthBanners.delete(key);
|
|
2923
3154
|
}
|
|
2924
3155
|
warnedNoCallID.delete(id);
|
|
3156
|
+
lateBuffer?.forget(id);
|
|
2925
3157
|
forgetRoleSession(id); // #84 P2.1 (the binding and authority registries are evicted by the v2 adapter)
|
|
2926
3158
|
forgetWorkingSet(id); // cross-repo P1.4: the orchestrator's bound repository locations
|
|
2927
3159
|
// 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
|
|
2928
3160
|
// 2.4.5: so do its background requests and late notices; its run in flight is aborted.
|
|
2929
3161
|
background?.forgetSession(id);
|
|
2930
3162
|
pending.forgetSession(id);
|
|
3163
|
+
// QA-2.1-13 (v2 only): its held texts go, and its adoption claim is given back.
|
|
3164
|
+
forgetHeldTexts(id);
|
|
3165
|
+
// QA-SYNC1-14: its calls' arguments and routed-role copies go too.
|
|
3166
|
+
forgetSessionTaskArgs(id);
|
|
3167
|
+
releasePendingClaimOf(id);
|
|
2931
3168
|
}
|
|
2932
3169
|
} catch {
|
|
2933
3170
|
// best-effort: cleanup must never crash a real session
|
|
@@ -3161,6 +3398,8 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3161
3398
|
|
|
3162
3399
|
// Register commands
|
|
3163
3400
|
opencodeConfig.command ??= {};
|
|
3401
|
+
// Remember the host command the hook sees; our v2 registration is marked so reloads are not conflicts.
|
|
3402
|
+
userPlanCommandDefined = opencodeConfig.command.plan !== undefined && opencodeConfig.command.plan?.[planCommandMarker] !== true;
|
|
3164
3403
|
opencodeConfig.command["tiers"] = {
|
|
3165
3404
|
template: "",
|
|
3166
3405
|
description: "Show model delegation tiers and rules",
|
|
@@ -3228,6 +3467,16 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3228
3467
|
description:
|
|
3229
3468
|
"Model-router controls (e.g., /router enforce off|advisory|enforced, /router overrides, /router models)",
|
|
3230
3469
|
};
|
|
3470
|
+
if (rolesAtStart && planCommand !== undefined) {
|
|
3471
|
+
if (userPlanCommandDefined) {
|
|
3472
|
+
if (!warnedPlanCommandConflict) {
|
|
3473
|
+
warnedPlanCommandConflict = true;
|
|
3474
|
+
logger.warn("[router] /plan command conflict: preserving the user-defined /plan; router_plan remains available");
|
|
3475
|
+
}
|
|
3476
|
+
} else {
|
|
3477
|
+
opencodeConfig.command.plan = { template: "$ARGUMENTS", description: planCommand.description, [planCommandMarker]: true };
|
|
3478
|
+
}
|
|
3479
|
+
}
|
|
3231
3480
|
},
|
|
3232
3481
|
|
|
3233
3482
|
// -----------------------------------------------------------------------
|
|
@@ -3299,7 +3548,7 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3299
3548
|
try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
|
|
3300
3549
|
// #84 P2.1 (T2.1.3): v2 roles mode carries the roles protocol (P2.2); "" (v1, tiers mode, no enabled role) keeps today's prompt.
|
|
3301
3550
|
const rolesPrompt = isV2Host ? assembleRolesSystemPrompt(cfg, rolesNow(), orchestratorModel, enfOn) : "";
|
|
3302
|
-
let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn);
|
|
3551
|
+
let systemPrompt = rolesPrompt !== "" ? rolesPrompt : assembleSystemPrompt(cfg, orchestratorModel, enfOn, isV2Host ? "v2" : "v1");
|
|
3303
3552
|
// A28 (D1): on v1 only, and only with an explicit `routing.roles`, the `R:` line lists those agents as destinations (prose; no model
|
|
3304
3553
|
// override). Anything else leaves `systemPrompt` the very string it is: the v1 protocol stays byte-identical.
|
|
3305
3554
|
// Any failure leaves the baseline prompt (QA-2.4-13): the line is an extra, never a reason to lose the protocol.
|
|
@@ -3319,27 +3568,34 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3319
3568
|
// a system part that changes would cost the orchestrator its prompt cache (QA-2.4-9).
|
|
3320
3569
|
advisorNotifier?.poll();
|
|
3321
3570
|
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
|
|
3325
|
-
|
|
3326
|
-
|
|
3327
|
-
|
|
3328
|
-
//
|
|
3329
|
-
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
|
|
3334
|
-
}
|
|
3335
|
-
// 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
|
|
3336
|
-
// not pass, each delivered once (takeNotices marks them delivered).
|
|
3337
|
-
if (background !== undefined) {
|
|
3571
|
+
if (turnState !== undefined) {
|
|
3572
|
+
// Phase 1.2 (v2 only): the pending list, the late notices and the route hint are rendered into the turn-state tail
|
|
3573
|
+
// by the context hook, never into the system array (which stays byte-identical between requests). This point is
|
|
3574
|
+
// reached for root sessions only (every child returned above): the flag tells the hook to build the tail.
|
|
3575
|
+
output[TURN_STATE_ROOT] = true;
|
|
3576
|
+
} else {
|
|
3577
|
+
// 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
|
|
3578
|
+
// newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
|
|
3579
|
+
// does not grow for sessions that never defer. Orchestrator path only: every child returned
|
|
3580
|
+
// above. With background mode on, an entry the queue is verifying right now is still
|
|
3581
|
+
// unverified to the orchestrator, so it stays listed until its run settles.
|
|
3338
3582
|
try {
|
|
3339
|
-
|
|
3340
|
-
|
|
3583
|
+
// QA-2.4-3: plus background verdicts that did not pass, until router_verify replays them.
|
|
3584
|
+
const open = pending.listPending(sessionID, { verifying: background !== undefined });
|
|
3585
|
+
const block = buildPendingListBlock(open);
|
|
3586
|
+
if (block !== undefined) output.system.push(block);
|
|
3341
3587
|
} catch (error) {
|
|
3342
|
-
logger.warn("[verify]
|
|
3588
|
+
logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
|
|
3589
|
+
}
|
|
3590
|
+
// 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
|
|
3591
|
+
// not pass, each delivered once (takeNotices marks them delivered).
|
|
3592
|
+
if (background !== undefined) {
|
|
3593
|
+
try {
|
|
3594
|
+
const late = buildLateNoticeBlock(background.takeNotices(sessionID));
|
|
3595
|
+
if (late !== undefined) output.system.push(late);
|
|
3596
|
+
} catch (error) {
|
|
3597
|
+
logger.warn("[verify] late notices not injected", { error: scrubText(String(error)) });
|
|
3598
|
+
}
|
|
3343
3599
|
}
|
|
3344
3600
|
}
|
|
3345
3601
|
},
|
|
@@ -3348,6 +3604,31 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3348
3604
|
// Handle /tiers, /preset, and /budget commands
|
|
3349
3605
|
// -----------------------------------------------------------------------
|
|
3350
3606
|
"command.execute.before": async (input: any, output: any) => {
|
|
3607
|
+
if (input.command === "plan") {
|
|
3608
|
+
if (!isV2Host) {
|
|
3609
|
+
// Best-effort on v1 (the command is deliberately unregistered); share the configured-key notice's process guard.
|
|
3610
|
+
if (!userPlanCommandDefined && warnedV2OnlyKeys.size === 0) {
|
|
3611
|
+
warnedV2OnlyKeys.add("routing.executor");
|
|
3612
|
+
logger.warn("[router] the plan executor requires OpenCode v2; ignored: /plan");
|
|
3613
|
+
}
|
|
3614
|
+
return; // No model-visible part on v1.
|
|
3615
|
+
}
|
|
3616
|
+
if (!rolesAtStart || userPlanCommandDefined) return; // Leave unregistered or user-defined /plan commands alone.
|
|
3617
|
+
if (planCommand !== undefined) {
|
|
3618
|
+
const args: string = input.arguments ?? "";
|
|
3619
|
+
const parsed = parsePlanCommand(args);
|
|
3620
|
+
const allowed = parsed.kind !== "call" || await planActionCallerAllowed(
|
|
3621
|
+
input.sessionID, parsed.call.action, "planId" in parsed.call ? parsed.call.planId : undefined,
|
|
3622
|
+
);
|
|
3623
|
+
const text = !allowed
|
|
3624
|
+
? `[router_plan] ${planCallerRefusal}`
|
|
3625
|
+
: executorAccess?.runtime() === null
|
|
3626
|
+
? `[router_plan] ${executorAccess.unavailable()}`
|
|
3627
|
+
: planCommand.execute(args);
|
|
3628
|
+
output.parts.push({ type: "text" as const, text });
|
|
3629
|
+
}
|
|
3630
|
+
return;
|
|
3631
|
+
}
|
|
3351
3632
|
if (input.command === "tiers") {
|
|
3352
3633
|
try {
|
|
3353
3634
|
cfg = loadConfig(projectDir);
|
|
@@ -3495,7 +3776,11 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3495
3776
|
}
|
|
3496
3777
|
} else {
|
|
3497
3778
|
// #84 P2.2: `/router` lists the roles in roles mode on v2 (`rolesNow()` is empty in tiers mode and on v1).
|
|
3498
|
-
|
|
3779
|
+
// Match registration at start and v2.ts's executor discovery prerequisites; never advertise an unregistered command.
|
|
3780
|
+
const planAvailable = rolesAtStart && planCommand !== undefined && !userPlanCommandDefined && resolveRolesRouting(cfg, "v2").delegation === "roles"
|
|
3781
|
+
&& resolveRouting(cfg, "v2").leases.mode === "enforce" && cfg.enforcement?.verify?.require !== "never"
|
|
3782
|
+
&& !locationOutsideWorkRoots(ctx.directory, cfg.routing?.workRoots);
|
|
3783
|
+
text = buildRouterOutput(cfg, args, projectDir, rolesNow().size > 0 ? rolesNow().values() : undefined, approvalsAvailable, planAvailable);
|
|
3499
3784
|
// On the bare status view, surface stale or missing models inline.
|
|
3500
3785
|
if (sub === "") {
|
|
3501
3786
|
text += "\n" + routerStatusLines(cfg, ctx.routerHost === "v2" ? "v2" : "v1", logger, projectDir).join("\n");
|
|
@@ -3528,6 +3813,931 @@ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
|
|
|
3528
3813
|
}
|
|
3529
3814
|
},
|
|
3530
3815
|
};
|
|
3816
|
+
/**
|
|
3817
|
+
* What the verification of a finished `task` call ended in (phase 2.1.4.a). The foreground hook ignores it.
|
|
3818
|
+
*/
|
|
3819
|
+
type FinishOutcome =
|
|
3820
|
+
| { kind: "none" }
|
|
3821
|
+
| { kind: "deferred"; handle: string }
|
|
3822
|
+
// QA-DF1-16: `gate` is the gate's own verdict (method, outcome, reasons, caveats, notes); a held entry settles with it,
|
|
3823
|
+
// QA-DF1-29: with its pass/outcome set from `verdict` (the tag the gate's decision gives; see heldSettlementOf).
|
|
3824
|
+
| { kind: "required"; verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; detail: string; gate: HeldSettlement }
|
|
3825
|
+
// QA-2.1-1: the gate was not run on purpose (a read-only delegation) or failed; neither is a verdict.
|
|
3826
|
+
| { kind: "skipped"; reason: string }
|
|
3827
|
+
| { kind: "error"; reason: string };
|
|
3828
|
+
|
|
3829
|
+
/**
|
|
3830
|
+
* Phase 2.1.4.a: the verification of a finished `task` call, extracted unchanged from the legacy
|
|
3831
|
+
* `tool.execute.after`. It rewrites `output.output` (footer, forcing note, accepted suffix) exactly as before;
|
|
3832
|
+
* the hook calls it in the foreground, and the v2 finish API (below) calls it for background completions.
|
|
3833
|
+
*/
|
|
3834
|
+
async function finishDispatch(
|
|
3835
|
+
input: any,
|
|
3836
|
+
output: any,
|
|
3837
|
+
unbannered: { output: unknown } | undefined,
|
|
3838
|
+
// QA-SYNC1-2: `workRoot`, the journaled work root of a dispatch restored after a restart (its routed-role record is gone).
|
|
3839
|
+
// QA-SYNC1-3: `unattributedWriters`, those a restored held entry journaled (the live tally is gone after a restart).
|
|
3840
|
+
extra?: {
|
|
3841
|
+
delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; graderParentSessionID?: string; workRoot?: string;
|
|
3842
|
+
unattributedWriters?: readonly string[];
|
|
3843
|
+
/** QA-SYNC1-3: the journaled dispatch-time head of a restored held entry; the branch check compares it as before. */
|
|
3844
|
+
restoredHead?: DispatchHeadState;
|
|
3845
|
+
/**
|
|
3846
|
+
* QA-SYNC1-3: never deferred. A restored held entry was held because its verification was required at dispatch (only a
|
|
3847
|
+
* required verification is held); it settles in place, never re-classified under the restarted process into a deferral.
|
|
3848
|
+
*/
|
|
3849
|
+
noDefer?: true;
|
|
3850
|
+
},
|
|
3851
|
+
): Promise<FinishOutcome> {
|
|
3852
|
+
let outcome: FinishOutcome = { kind: "none" };
|
|
3853
|
+
if (typeof input?.tool === "string") {
|
|
3854
|
+
let mode = "off";
|
|
3855
|
+
try {
|
|
3856
|
+
mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
3857
|
+
} catch {
|
|
3858
|
+
// fall through with mode "off"
|
|
3859
|
+
}
|
|
3860
|
+
const requireMode = cfg.enforcement?.verify?.require;
|
|
3861
|
+
if (shouldVerifyTask(input.tool, mode, requireMode)) {
|
|
3862
|
+
try {
|
|
3863
|
+
// pending.ts R11: the producer's changes landed by now.
|
|
3864
|
+
const returnedAt = Date.now();
|
|
3865
|
+
const { finalReturnText, childSessionID } = parseTaskResult(unbannered ? { ...output, output: unbannered.output } : output);
|
|
3866
|
+
const producerTier =
|
|
3867
|
+
typeof input?.args?.subagent_type === "string"
|
|
3868
|
+
? input.args.subagent_type
|
|
3869
|
+
: "";
|
|
3870
|
+
// QA-2.1-17 (v2 only): a gate re-run after a restart verifies the DoD its restored pending entry persisted.
|
|
3871
|
+
const dod = extra?.dod ?? buildDelegationDoD({
|
|
3872
|
+
prompt: input?.args?.prompt,
|
|
3873
|
+
description: input?.args?.description,
|
|
3874
|
+
});
|
|
3875
|
+
// DF2-F1: a role dispatch is verified in its verification root (capture, change set, checks, deferral); a requested
|
|
3876
|
+
// cwd outside that root is refused by the gate below, never deferred to run there later.
|
|
3877
|
+
const scope = verificationScopeOf(input.callID, input?.args, dod, extra?.workRoot);
|
|
3878
|
+
const cwdSource = requestedVerificationCwdSource(input?.args?.cwd, dod.cwd);
|
|
3879
|
+
const effectiveCwd = scope.cwd;
|
|
3880
|
+
const dispatchID = `task:${input.sessionID}:${input.callID}`;
|
|
3881
|
+
// #84 QA-G-B-2-1: a routed role dispatch keeps its child's verification lineage; a resume that CARRIES the acceptance of an
|
|
3882
|
+
// earlier attempt is gated at once (never deferred) on the child's cumulative change set (roleAttemptVerification).
|
|
3883
|
+
// QA-SYNC1-1: a background finish runs after the adapter forgot its record; the copy taken with the call's arguments stands in.
|
|
3884
|
+
const routedRole = typeof input.callID === "string" ? routedRoleFor(input.callID) : undefined;
|
|
3885
|
+
const carriedRole = routedRole?.carried === true && childSessionID !== null && routedRole.resumeID === childSessionID;
|
|
3886
|
+
// Cross-repo P2a.3 (v2 only): where each check of a routed role dispatch runs. Tier dispatches resolve nothing.
|
|
3887
|
+
// P2e.6: valid per-check `cwd=`/`scope=` keys may be deferred (the placements travel with the handle, and router_verify
|
|
3888
|
+
// runs each check where it was placed); only a refusal is verified at once, below.
|
|
3889
|
+
const placement = routedRole === undefined ? undefined : resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routedRole) });
|
|
3890
|
+
// P2b.7 (OD1=B, v2 only): a tier dispatch with a per-check `cwd=` is unverifiable (the gate refuses it); it is never deferred.
|
|
3891
|
+
const tierRefusal = routedRole === undefined && ctx.routerHost === "v2" ? tierCheckCwdRefusal(dod) : undefined;
|
|
3892
|
+
// P2e.6: a refused placement or the OD1 tier refusal is certain now: verified at once, never deferred.
|
|
3893
|
+
const placementRefused = tierRefusal !== undefined || placement?.refused !== undefined;
|
|
3894
|
+
const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
|
|
3895
|
+
const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
|
|
3896
|
+
const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
|
|
3897
|
+
// 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
|
|
3898
|
+
const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
|
|
3899
|
+
const trivial = childSessionID
|
|
3900
|
+
? sessionStore.isTrivial(childSessionID)
|
|
3901
|
+
: false;
|
|
3902
|
+
// QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
|
|
3903
|
+
// deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
|
|
3904
|
+
// B2: the reason a deferred finish refused for a branch switch, carried into the artefact below.
|
|
3905
|
+
let deferredSwitch: string | undefined;
|
|
3906
|
+
if (extra?.noDefer !== true && !scope.outside && !carriedRole && !placementRefused && isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
|
|
3907
|
+
// Section 1.5-16: no gate, no test process; the result goes back now with the
|
|
3908
|
+
// footer, which is appended last and never says accepted or verified.
|
|
3909
|
+
const finish = await finishDeferred(changedFileStore, {
|
|
3910
|
+
dispatchID,
|
|
3911
|
+
orchestratorSessionID,
|
|
3912
|
+
producerSessionID: childSessionID ?? "",
|
|
3913
|
+
producerTier,
|
|
3914
|
+
description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
|
|
3915
|
+
cwd: effectiveCwd,
|
|
3916
|
+
// I2 (P2.3): the change observation stays in W; the registration's cwd above is the check base (F5).
|
|
3917
|
+
...(scope.workRoot !== undefined ? { captureRoot: captureRootOf(scope) } : {}),
|
|
3918
|
+
// #84 P3.3 DF2-F1 (fix-1 review nit): router_verify's gate re-checks containment in the role's work root.
|
|
3919
|
+
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
3920
|
+
dod,
|
|
3921
|
+
dispatchedAt: start.dispatchedAt,
|
|
3922
|
+
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule): router_verify judges the budget at return.
|
|
3923
|
+
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
3924
|
+
// Cross-repo P2e.6: the checks' placements (registered with the handle), and the full scope on v2 (OD-P2e-2).
|
|
3925
|
+
...(placement?.placements !== undefined ? { placements: placement.placements } : {}),
|
|
3926
|
+
...(fullScopeOf(cfg) ? { fullScope: true } : {}),
|
|
3927
|
+
// Phase 2.1.4.b: the change set frozen at child end (background completions only).
|
|
3928
|
+
...(extra?.delta !== undefined ? { delta: extra.delta } : {}),
|
|
3929
|
+
});
|
|
3930
|
+
if (finish.deferred) {
|
|
3931
|
+
output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
|
|
3932
|
+
// The dispatch record is cleared by finishDeferred once its capture settled.
|
|
3933
|
+
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
3934
|
+
outcome = { kind: "deferred", handle: finish.handle };
|
|
3935
|
+
return outcome;
|
|
3936
|
+
}
|
|
3937
|
+
if (finish.reason === "branch-switched") deferredSwitch = finish.detail;
|
|
3938
|
+
// QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
|
|
3939
|
+
}
|
|
3940
|
+
// Same bound as the delegate gate: one deadline per invocation,
|
|
3941
|
+
// a withTimeout ceiling, and abort-on-reject so a hung check or
|
|
3942
|
+
// grader cannot hold the after-hook (and its process tree) open.
|
|
3943
|
+
// The deadline exists before prepareVerification (T2 P0,
|
|
3944
|
+
// QA-2.1-4), so preparation counts against gateBudgetMs.
|
|
3945
|
+
const { gateBudgetMs } = resolveVerifyBudget(cfg);
|
|
3946
|
+
const gateDeadline = createDeadline(gateBudgetMs);
|
|
3947
|
+
let verification;
|
|
3948
|
+
try {
|
|
3949
|
+
// Cross-repo P3a (D23 as amended, QA C1): the dispatch's start (takeDispatch), the `since` of W's ignored-module
|
|
3950
|
+
// listing. A start that was never remembered reads as now (the return), which lists nothing older: never stale inputs.
|
|
3951
|
+
verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", captureRootOf(scope), gateDeadline, start.dispatchedAt, extra?.restoredHead, isV2Host ? orchestratorSessionID : undefined);
|
|
3952
|
+
} catch (error) {
|
|
3953
|
+
gateDeadline.dispose();
|
|
3954
|
+
throw error;
|
|
3955
|
+
}
|
|
3956
|
+
// QA2 F4: a switch the deferred finish saw (and this gate's own read missed) is part of this attempt before the role
|
|
3957
|
+
// lineage records it; its change set may hold the other branch's commits, so it is unavailable.
|
|
3958
|
+
if (deferredSwitch !== undefined && verification.branchSwitch === undefined) {
|
|
3959
|
+
verification = { ...verification, branchSwitch: deferredSwitch, changeBaseline: "unavailable" as const };
|
|
3960
|
+
}
|
|
3961
|
+
// QA-SYNC1-3: a restored held entry's journaled unattributed writers count as the lineage's own.
|
|
3962
|
+
const restoredWriters = extra?.unattributedWriters;
|
|
3963
|
+
if (restoredWriters !== undefined && restoredWriters.length > 0) {
|
|
3964
|
+
verification = { ...verification, unattributedWriters: [...new Set([...(verification.unattributedWriters ?? []), ...restoredWriters])].sort() };
|
|
3965
|
+
}
|
|
3966
|
+
// #84 QA-G-B-2-1: the role child's lineage — this attempt starts it (its own block) or is judged on everything the child
|
|
3967
|
+
// changed since the attempt that introduced the carried block, against that attempt's reference.
|
|
3968
|
+
if (routedRole !== undefined && childSessionID) verification = roleAttemptVerification(childSessionID, verification, { carried: carriedRole });
|
|
3969
|
+
// #84 P2.1: a role agent follows the return contract (handoff 26; roles mode only).
|
|
3970
|
+
const roleProducer = roleSpecOf(producerTier) !== undefined;
|
|
3971
|
+
const artefact = {
|
|
3972
|
+
changedFiles: verification.changedFiles,
|
|
3973
|
+
changeBaseline: verification.changeBaseline,
|
|
3974
|
+
...(verification.snapshot?.root !== undefined ? { changeRoot: verification.snapshot.root } : {}),
|
|
3975
|
+
...((verification.branchSwitch ?? deferredSwitch) !== undefined ? { branchSwitch: verification.branchSwitch ?? deferredSwitch } : {}),
|
|
3976
|
+
...(verification.unattributedWriters !== undefined && verification.unattributedWriters.length > 0
|
|
3977
|
+
? { unattributedWriters: verification.unattributedWriters } : {}),
|
|
3978
|
+
...(verification.perimeter !== undefined ? { perimeter: verification.perimeter } : {}),
|
|
3979
|
+
finalReturnText,
|
|
3980
|
+
declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
|
|
3981
|
+
producerSessionID: childSessionID ?? "",
|
|
3982
|
+
producerTier,
|
|
3983
|
+
...(roleProducer ? { returnContract: true } : {}),
|
|
3984
|
+
// Handoff 24, R7 (I1/I8 exemption: the I7 budget-incomplete rule; every mode): the guard's budget state when the task
|
|
3985
|
+
// returned, not when the gate runs. Without a stop it judges like the live read it replaces.
|
|
3986
|
+
budget: captureBudget(childSessionID ?? "", childSessionID ? sessionStore.readCapReached(childSessionID) : undefined),
|
|
3987
|
+
};
|
|
3988
|
+
|
|
3989
|
+
// Read-only / research delegation: an auto-inferred, criteria-only DoD on a
|
|
3990
|
+
// native Task() that changed no files is exploration, not implementation.
|
|
3991
|
+
// There is nothing concrete to verify, so skip rather than grade the
|
|
3992
|
+
// findings against the task's own summary, which otherwise appends false
|
|
3993
|
+
// "not accepted" notes to legitimate read-only research delegations.
|
|
3994
|
+
// Explicit [acceptance] blocks (source != "inferred") and inferred
|
|
3995
|
+
// deterministic checks (dod.kind === "deterministic") still verify normally.
|
|
3996
|
+
if (
|
|
3997
|
+
dod.source === "inferred" &&
|
|
3998
|
+
dod.kind === "checker" &&
|
|
3999
|
+
artefact.changedFiles.length === 0
|
|
4000
|
+
) {
|
|
4001
|
+
gateDeadline.dispose();
|
|
4002
|
+
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
4003
|
+
changedFileStore.clear(dispatchID);
|
|
4004
|
+
outcome = { kind: "skipped", reason: "read-only delegation: no files changed and no explicit acceptance to verify" };
|
|
4005
|
+
return outcome;
|
|
4006
|
+
}
|
|
4007
|
+
|
|
4008
|
+
const gateGraderSessions = new Set<string>();
|
|
4009
|
+
const completedFailures: string[] = [];
|
|
4010
|
+
// Keep the native grader unparented on the backend; only depth tracking uses its caller. DF-1-3 (v2 finish API only,
|
|
4011
|
+
// absent on the v1 after-hook): a background completion names the parent whose retained context launches the grader.
|
|
4012
|
+
const gateDeps = buildGateDeps(extra?.graderParentSessionID, gateGraderSessions, verification, gateDeadline, false, orchestratorSessionID || null);
|
|
4013
|
+
gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
|
|
4014
|
+
// #84 QA-G-B-2-1: a carried acceptance never passes on a testsPass/lintClean that ran no process.
|
|
4015
|
+
if (carriedRole) gateDeps.deterministic.noAffectedUnverifiable = CARRIED_NO_PROCESS_REASON;
|
|
4016
|
+
let res;
|
|
4017
|
+
try {
|
|
4018
|
+
res = await withTimeout(
|
|
4019
|
+
accept(
|
|
4020
|
+
{
|
|
4021
|
+
dod,
|
|
4022
|
+
trivial,
|
|
4023
|
+
mode: "modeA",
|
|
4024
|
+
// Native task has no cwd argument; the acceptance block can supply it.
|
|
4025
|
+
...(scope.requested ? { cwd: scope.requested } : {}),
|
|
4026
|
+
...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
|
|
4027
|
+
...(scope.refused !== undefined ? { refusedCwd: scope.refused } : {}),
|
|
4028
|
+
// Fix-1 review nit: a refusal names where the cwd came from (the call's `cwd`, else the block's `cwd:`).
|
|
4029
|
+
...(scope.workRoot !== undefined && cwdSource !== undefined ? { cwdSource } : {}),
|
|
4030
|
+
// Cross-repo P2b.5 (v2 only): where each check of a routed role dispatch runs, or the check the router refused.
|
|
4031
|
+
...(placement?.placements !== undefined ? { checkPlacements: placement.placements } : {}),
|
|
4032
|
+
...(placement?.refused !== undefined ? { refusedCheck: placement.refused } : tierRefusal !== undefined ? { refusedCheck: tierRefusal } : {}),
|
|
4033
|
+
},
|
|
4034
|
+
artefact,
|
|
4035
|
+
gateDeps,
|
|
4036
|
+
),
|
|
4037
|
+
// What preparation left of the gate budget (QA-2.1-4).
|
|
4038
|
+
gateDeadline.remaining(),
|
|
4039
|
+
"verification gate",
|
|
4040
|
+
);
|
|
4041
|
+
} catch (error) {
|
|
4042
|
+
gateDeadline.abort(
|
|
4043
|
+
error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
|
|
4044
|
+
);
|
|
4045
|
+
if (error instanceof RouterTimeoutError) {
|
|
4046
|
+
for (const gsid of gateGraderSessions) {
|
|
4047
|
+
try {
|
|
4048
|
+
await ctx.client.session.abort({ path: { id: gsid } });
|
|
4049
|
+
} catch {
|
|
4050
|
+
// best-effort: the gate result stands either way
|
|
4051
|
+
}
|
|
4052
|
+
}
|
|
4053
|
+
}
|
|
4054
|
+
res = unverifiableGateResult(
|
|
4055
|
+
error instanceof RouterTimeoutError
|
|
4056
|
+
? `verification gate timed out after ${gateBudgetMs}ms`
|
|
4057
|
+
: `verification unavailable: ${scrubText(String(error))}`,
|
|
4058
|
+
dod.source,
|
|
4059
|
+
cfg.enforcement?.verify?.strictUnverifiable,
|
|
4060
|
+
completedFailures,
|
|
4061
|
+
);
|
|
4062
|
+
} finally {
|
|
4063
|
+
gateDeadline.dispose();
|
|
4064
|
+
}
|
|
4065
|
+
// pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
|
|
4066
|
+
// on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
|
|
4067
|
+
res = applyLineage(res, {
|
|
4068
|
+
orchestratorSessionID,
|
|
4069
|
+
root: verification.snapshot?.root,
|
|
4070
|
+
dispatchID,
|
|
4071
|
+
dispatchedAt: start.dispatchedAt,
|
|
4072
|
+
returnedAt,
|
|
4073
|
+
strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
|
|
4074
|
+
});
|
|
4075
|
+
// QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
|
|
4076
|
+
res = applyDispatchCaveats(res, verification);
|
|
4077
|
+
// M6 (2.1.3): a real verdict of a registered child dispatch feeds the outcome store (v2, engine != static).
|
|
4078
|
+
// #84 P3.3 fix 2 (plan §2.6, I6): a grader's verdict is a grader signal of a role dispatch, never a deterministic one.
|
|
4079
|
+
if (childSessionID && !res.verdict.skipped) ingest?.onVerdict(childSessionID, verdictOf(res.verdict), verdictGraderOf(res.verdict));
|
|
4080
|
+
// A gated child must not stay on medium when its return gate cannot verify it, even if accepted with a caveat.
|
|
4081
|
+
// Strict children and incomplete returns keep their existing behaviour and text.
|
|
4082
|
+
if (isV2Host && routedRole?.gated === true && childSessionID && !res.verdict.skipped &&
|
|
4083
|
+
res.verdict.outcome === "unverifiable" && !isIncompleteVerdict(res.verdict)) {
|
|
4084
|
+
roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID);
|
|
4085
|
+
}
|
|
4086
|
+
if (!res.accepted && !res.verdict.skipped) {
|
|
4087
|
+
const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
|
|
4088
|
+
const li = ladder.indexOf(producerTier);
|
|
4089
|
+
const nextTier = res.verdict.outcome !== "unverifiable" && li >= 0 && li < ladder.length - 1 ? ladder[li + 1] : null;
|
|
4090
|
+
// Handoff 25, R7 (I1/I8 exemption: the I7 budget-incomplete rule): absent when false, so the note is unchanged.
|
|
4091
|
+
const incomplete = isIncompleteVerdict(res.verdict);
|
|
4092
|
+
let note = scrubText(buildForcingNote(res.verdict.reasons, { producerTier, nextTier, ...(incomplete ? { incomplete: true } : {}) }));
|
|
4093
|
+
// P-8 (handoff 39): a role agent is resumed on a higher tier of its range, never re-run on a tier agent.
|
|
4094
|
+
// QA-P21-1-4: only after a FAIL (an unverifiable result keeps the generic line: there is nothing to escalate on).
|
|
4095
|
+
// QA-P21-2-2: the hint promises the raise, and records it for this parent's next resume of the child.
|
|
4096
|
+
const roleHint = roleProducer && !incomplete && res.verdict.outcome === "fail" && childSessionID
|
|
4097
|
+
? roleEscalationAfterFail(cfg, childSessionID, orchestratorSessionID) : null;
|
|
4098
|
+
const genericNext = "NEXT: address the above and re-run the delegation; do not treat the prior result as complete.";
|
|
4099
|
+
if (roleHint !== null && note.endsWith(genericNext)) note = note.slice(0, note.length - genericNext.length) + scrubText(roleHint);
|
|
4100
|
+
output.output =
|
|
4101
|
+
typeof output.output === "string"
|
|
4102
|
+
? output.output + "\n\n" + note
|
|
4103
|
+
: note;
|
|
4104
|
+
}
|
|
4105
|
+
// QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
|
|
4106
|
+
// check stays silent unless it carries caveats or notes.
|
|
4107
|
+
if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
|
|
4108
|
+
output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
|
|
4109
|
+
}
|
|
4110
|
+
if (childSessionID) changedFileStore.clear(childSessionID);
|
|
4111
|
+
changedFileStore.clear(dispatchID);
|
|
4112
|
+
outcome = {
|
|
4113
|
+
kind: "required",
|
|
4114
|
+
// DF-1-3: the tag follows the outcome; an accepted unverifiable result (gate.ts, not strictUnverifiable) is UNVERIFIABLE.
|
|
4115
|
+
verdict: res.verdict.outcome === "unverifiable" ? "UNVERIFIABLE" : res.accepted ? "PASS" : "FAIL",
|
|
4116
|
+
detail: res.verdict.reasons.join("; "),
|
|
4117
|
+
// QA-DF1-16: the gate's real verdict, so router_verify on a held handle reports what the posted text says.
|
|
4118
|
+
gate: { verdict: res.verdict, retryable: false },
|
|
4119
|
+
};
|
|
4120
|
+
} catch (error) {
|
|
4121
|
+
// fail-closed: a verification error must NEVER throw out of the after-hook. QA-2.1-1: it is logged and reported as an
|
|
4122
|
+
// `error` outcome, so a held dispatch posts UNVERIFIABLE with this reason instead of a PASS.
|
|
4123
|
+
logger.warn("[router] verification failed in the after-hook", { tool: input?.tool, error: describeError(error) });
|
|
4124
|
+
outcome = { kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` };
|
|
4125
|
+
}
|
|
4126
|
+
}
|
|
4127
|
+
}
|
|
4128
|
+
return outcome;
|
|
4129
|
+
}
|
|
4130
|
+
|
|
4131
|
+
/**
|
|
4132
|
+
* Phase 2.1.4.a (v2 only): the `task` arguments of a call in flight, kept for FinishApi.verificationFor / finish. QA-SYNC1-14:
|
|
4133
|
+
* forgotten when the call's finish settles (foreground, held, deferred or immediate) and with its parent session.
|
|
4134
|
+
*/
|
|
4135
|
+
/**
|
|
4136
|
+
* QA-SYNC1-14 (test seam): `routerTaskArgsBounds` overrides the two bounds below (positive integers, `hard` ≥ `max`); anything
|
|
4137
|
+
* else keeps the production defaults.
|
|
4138
|
+
*/
|
|
4139
|
+
const taskArgsBounds = (ctx as RouterPluginInput & { routerTaskArgsBounds?: { max?: number; hard?: number } }).routerTaskArgsBounds;
|
|
4140
|
+
const boundOr = (value: number | undefined, fallback: number): number =>
|
|
4141
|
+
typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
4142
|
+
const MAX_TASK_ARGS = boundOr(taskArgsBounds?.max, 1000);
|
|
4143
|
+
/** QA-SYNC1-14: the bound past which even a call with a background record is evicted (= MAX_HOLDS_GLOBAL, background.ts). */
|
|
4144
|
+
const MAX_TASK_ARGS_HARD = Math.max(MAX_TASK_ARGS, boundOr(taskArgsBounds?.hard, 10_000));
|
|
4145
|
+
const taskArgsByCall = new Map<string, Record<string, unknown>>();
|
|
4146
|
+
/** QA-2.1-7: the parent session of a call in flight (same keys and bound), so captureDelta finds the dispatch record. */
|
|
4147
|
+
const taskParentByCall = new Map<string, string>();
|
|
4148
|
+
/**
|
|
4149
|
+
* QA-SYNC1-1/-2: the routed-role record of a call in flight (same keys and bound), copied when its arguments are remembered.
|
|
4150
|
+
* The adapter forgets its own record once a background acknowledgement returns; the finish (child end) still needs it.
|
|
4151
|
+
*/
|
|
4152
|
+
const routedRoleByCall = new Map<string, RoutedRoleSnapshot>();
|
|
4153
|
+
/**
|
|
4154
|
+
* QA-SYNC1-1: the routed-role record of `callID`: the dispatch module's while it keeps it, else the copy kept until the finish.
|
|
4155
|
+
* QA-SYNC1-13: after a restart, the snapshot a restored held entry journaled (finishRestored puts it in `routedRoleByCall`).
|
|
4156
|
+
*/
|
|
4157
|
+
function routedRoleFor(callID: string): RoutedRoleSnapshot | undefined {
|
|
4158
|
+
return routedRoleOf(callID) ?? routedRoleByCall.get(callID);
|
|
4159
|
+
}
|
|
4160
|
+
/**
|
|
4161
|
+
* QA-SYNC1-6: finishDispatch verifies this dispatch at once, never deferred: a cwd outside the role's verification root, a refused
|
|
4162
|
+
* check placement, or (v2) a tier dispatch's per-check `cwd=` (OD1=B). The same rules as there; a failed read counts as at once.
|
|
4163
|
+
* QA-SYNC1-12: a carried resume too (finishDispatch never defers it; its resumeID is known at dispatch).
|
|
4164
|
+
*/
|
|
4165
|
+
function verifiedAtOnce(callID: string, args: Record<string, unknown>, dod: ReturnType<typeof buildDelegationDoD>): boolean {
|
|
4166
|
+
try {
|
|
4167
|
+
const routed = routedRoleFor(callID);
|
|
4168
|
+
if (routed === undefined) return ctx.routerHost === "v2" && tierCheckCwdRefusal(dod) !== undefined;
|
|
4169
|
+
if (routed.carried === true) return true;
|
|
4170
|
+
const scope = verificationScopeOf(callID, args, dod);
|
|
4171
|
+
if (scope.outside) return true;
|
|
4172
|
+
return resolveCheckPlacements(dod, scope, { inReadSet: roleReadSetFor(routed) }).refused !== undefined;
|
|
4173
|
+
} catch (error) {
|
|
4174
|
+
logger.warn("[router] the check placements of a dispatch could not be read", { callID, error: describeError(error) });
|
|
4175
|
+
return true;
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
4178
|
+
function rememberTaskArgs(input: any, output: any): void {
|
|
4179
|
+
if (!isV2Host || input?.tool !== "task" || typeof input.callID !== "string") return;
|
|
4180
|
+
const args = output?.args;
|
|
4181
|
+
if (typeof args !== "object" || args === null) return;
|
|
4182
|
+
taskArgsByCall.set(input.callID, { ...(args as Record<string, unknown>) });
|
|
4183
|
+
if (typeof input.sessionID === "string") taskParentByCall.set(input.callID, input.sessionID);
|
|
4184
|
+
// QA-SYNC1-1: route() ran before this hook (v2 adapter), so the routed-role record is current here.
|
|
4185
|
+
const routed = routedRoleOf(input.callID);
|
|
4186
|
+
if (routed === undefined) routedRoleByCall.delete(input.callID);
|
|
4187
|
+
else routedRoleByCall.set(input.callID, routed);
|
|
4188
|
+
// QA-SYNC1-14: oldest first, but never a call that still has a held or in-flight background record (its finish needs the
|
|
4189
|
+
// arguments and the routed copy), nor the call just remembered; those are bounded by the background bounds instead.
|
|
4190
|
+
while (taskArgsByCall.size > MAX_TASK_ARGS) {
|
|
4191
|
+
let oldest: string | undefined;
|
|
4192
|
+
for (const key of taskArgsByCall.keys()) {
|
|
4193
|
+
if (key !== input.callID && !backgroundCalls.has(key)) { oldest = key; break; }
|
|
4194
|
+
}
|
|
4195
|
+
// A hard ceiling still holds (= MAX_HOLDS_GLOBAL): past it the oldest background call goes too, as before.
|
|
4196
|
+
if (oldest === undefined && taskArgsByCall.size > MAX_TASK_ARGS_HARD) {
|
|
4197
|
+
for (const key of taskArgsByCall.keys()) {
|
|
4198
|
+
if (key !== input.callID) { oldest = key; break; }
|
|
4199
|
+
}
|
|
4200
|
+
if (oldest !== undefined) backgroundCalls.delete(oldest);
|
|
4201
|
+
}
|
|
4202
|
+
if (oldest === undefined) break;
|
|
4203
|
+
taskArgsByCall.delete(oldest);
|
|
4204
|
+
taskParentByCall.delete(oldest);
|
|
4205
|
+
routedRoleByCall.delete(oldest);
|
|
4206
|
+
}
|
|
4207
|
+
}
|
|
4208
|
+
/**
|
|
4209
|
+
* QA-SYNC1-14: the calls with a held or in-flight background record (the adapter reserved a held slot for them, or read their
|
|
4210
|
+
* dispatch to journal an acknowledged background attempt); the FIFO bound above skips them. Forgotten with the call's arguments.
|
|
4211
|
+
*/
|
|
4212
|
+
const backgroundCalls = new Set<string>();
|
|
4213
|
+
function forgetTaskArgs(callID: string): void {
|
|
4214
|
+
taskArgsByCall.delete(callID);
|
|
4215
|
+
taskParentByCall.delete(callID);
|
|
4216
|
+
routedRoleByCall.delete(callID);
|
|
4217
|
+
backgroundCalls.delete(callID);
|
|
4218
|
+
}
|
|
4219
|
+
/** QA-SYNC1-14: a deleted session's calls are never finished; their arguments and routed copies go with it. */
|
|
4220
|
+
function forgetSessionTaskArgs(sessionID: string): void {
|
|
4221
|
+
for (const [callID, parent] of [...taskParentByCall]) if (parent === sessionID) forgetTaskArgs(callID);
|
|
4222
|
+
}
|
|
4223
|
+
|
|
4224
|
+
// ---- Phase 2.1.4.a (v2 only): the finish API ------------------------------------------------------
|
|
4225
|
+
/**
|
|
4226
|
+
* The foreground-equivalent text of a held dispatch, kept from the end of its gate until onVerdict posts it. QA-2.1-13:
|
|
4227
|
+
* bounded (oldest first; an evicted hold posts the generic verdict line) and forgotten with its parent session.
|
|
4228
|
+
* QA-DF1-16: `post` is the tag and reason the held gate posts with its text (its settled verdict keeps every reason).
|
|
4229
|
+
*/
|
|
4230
|
+
type HeldPost = { readonly verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; readonly reason?: string };
|
|
4231
|
+
const heldTexts = new Map<string, { readonly sessionID: string; readonly text: string; readonly post?: HeldPost }>();
|
|
4232
|
+
/** = MAX_HOLDS_GLOBAL (background.ts): there are never more live holds than this. */
|
|
4233
|
+
const MAX_HELD_TEXTS = 10_000;
|
|
4234
|
+
function rememberHeldText(handle: string, sessionID: string, text: string, post?: HeldPost): void {
|
|
4235
|
+
heldTexts.delete(handle);
|
|
4236
|
+
heldTexts.set(handle, { sessionID, text, ...(post === undefined ? {} : { post }) });
|
|
4237
|
+
while (heldTexts.size > MAX_HELD_TEXTS) {
|
|
4238
|
+
const oldest = heldTexts.keys().next();
|
|
4239
|
+
if (oldest.done === true) break;
|
|
4240
|
+
heldTexts.delete(oldest.value);
|
|
4241
|
+
}
|
|
4242
|
+
}
|
|
4243
|
+
function forgetHeldTexts(sessionID: string): void {
|
|
4244
|
+
for (const [handle, held] of heldTexts) if (held.sessionID === sessionID) heldTexts.delete(handle);
|
|
4245
|
+
}
|
|
4246
|
+
let heldSink: HeldSink | undefined;
|
|
4247
|
+
/**
|
|
4248
|
+
* QA-2.1-21: the held gates `finish` starts without awaiting them, each with its verdict post. `finishApi.idle` (the
|
|
4249
|
+
* adapter's settled seam) and `dispose` (bounded) wait for them.
|
|
4250
|
+
*/
|
|
4251
|
+
const heldGates = new Set<Promise<void>>();
|
|
4252
|
+
/** QA-2.1-21: how long `dispose` waits for running held gates before the registry and the wiring go. */
|
|
4253
|
+
const HELD_GATES_DISPOSE_BOUND_MS = 5_000;
|
|
4254
|
+
function trackHeldGate(gate: Promise<unknown>): void {
|
|
4255
|
+
const tracked = gate.then(
|
|
4256
|
+
() => undefined,
|
|
4257
|
+
(error: unknown) => logger.warn("[router] held gate failed", { error: describeError(error) }),
|
|
4258
|
+
);
|
|
4259
|
+
heldGates.add(tracked);
|
|
4260
|
+
void tracked.finally(() => heldGates.delete(tracked));
|
|
4261
|
+
}
|
|
4262
|
+
/** Resolves once no held gate runs (a gate started meanwhile is waited for too). Never rejects. */
|
|
4263
|
+
async function heldGatesIdle(): Promise<void> {
|
|
4264
|
+
while (heldGates.size > 0) await Promise.allSettled([...heldGates]);
|
|
4265
|
+
}
|
|
4266
|
+
async function waitHeldGates(boundMs: number): Promise<void> {
|
|
4267
|
+
if (heldGates.size === 0) return;
|
|
4268
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
4269
|
+
try {
|
|
4270
|
+
await Promise.race([heldGatesIdle(), new Promise<void>((resolve) => { timer = setTimeout(resolve, boundMs); })]);
|
|
4271
|
+
} finally {
|
|
4272
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
|
|
4276
|
+
/** pending.onVerdict: a held entry's verdict goes to the parent through the HeldSink (v2 adapter). */
|
|
4277
|
+
function postHeldVerdict(entry: PendingEntry, result: SettledVerification): void {
|
|
4278
|
+
// QA-2.1-31: settled by `settleHeldDirect` after the adapter posted the verdict itself.
|
|
4279
|
+
if (directlySettled.has(entry.handle)) return;
|
|
4280
|
+
if (entry.hold === undefined || heldSink === undefined) return;
|
|
4281
|
+
// QA-DF1-16: a held gate's text posts with the tag and reason it was written for (unchanged by its full settled verdict).
|
|
4282
|
+
const held = heldTexts.get(entry.handle);
|
|
4283
|
+
const verdict = held?.post?.verdict ?? heldVerdictKind(result.verdict.outcome, result.verdict.pass);
|
|
4284
|
+
const reason = held?.post !== undefined ? held.post.reason : result.verdict.reasons[0];
|
|
4285
|
+
const text = held?.text ?? `[router] ${entry.handle}: verification ended ${verdict}${reason !== undefined ? ` — ${scrubText(reason)}` : ""}`;
|
|
4286
|
+
heldTexts.delete(entry.handle);
|
|
4287
|
+
heldSink.verdict(entry.handle, { verdict, text, ...(reason !== undefined ? { reason } : {}) }).catch((error: unknown) => {
|
|
4288
|
+
logger.warn("[router] held verdict not posted", { handle: entry.handle, error: describeError(error) });
|
|
4289
|
+
});
|
|
4290
|
+
}
|
|
4291
|
+
|
|
4292
|
+
function heldVerdictKind(outcome: string | undefined, pass: boolean): "PASS" | "FAIL" | "UNVERIFIABLE" {
|
|
4293
|
+
if (outcome === "unverifiable") return "UNVERIFIABLE";
|
|
4294
|
+
return pass ? "PASS" : "FAIL";
|
|
4295
|
+
}
|
|
4296
|
+
|
|
4297
|
+
/**
|
|
4298
|
+
* QA-2.1-1: the verdict a held dispatch posts for what its gate ended in. Only a `required` outcome carries a gate verdict;
|
|
4299
|
+
* every other outcome is UNVERIFIABLE with its reason, and `line` is the router line appended to the posted text.
|
|
4300
|
+
*/
|
|
4301
|
+
function heldOutcomeOf(outcome: FinishOutcome): { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; reasons: string[]; line?: string } {
|
|
4302
|
+
if (outcome.kind === "required") return { verdict: outcome.verdict, reasons: outcome.detail !== "" ? [outcome.detail] : [] };
|
|
4303
|
+
const reason =
|
|
4304
|
+
outcome.kind === "skipped" ? `not verified: ${outcome.reason}`
|
|
4305
|
+
: outcome.kind === "error" ? outcome.reason
|
|
4306
|
+
: outcome.kind === "deferred" ? `not verified: deferred to router_verify as ${outcome.handle}`
|
|
4307
|
+
: "not verified: verification is not required for this dispatch";
|
|
4308
|
+
const scrubbed = scrubText(reason);
|
|
4309
|
+
return { verdict: "UNVERIFIABLE", reasons: [scrubbed], line: `[router] UNVERIFIABLE — ${scrubbed}` };
|
|
4310
|
+
}
|
|
4311
|
+
|
|
4312
|
+
/** The `task` result the host would have handed the hook: the child's id and its final text. */
|
|
4313
|
+
function taskOutputText(childSessionID: string, text: string): string {
|
|
4314
|
+
return `task_id: ${childSessionID} (for resuming to continue this task if needed)\n\n<task_result>\n${text}\n</task_result>`;
|
|
4315
|
+
}
|
|
4316
|
+
|
|
4317
|
+
// ONE journal (memo §11): the same `pending.jsonl` the pending store and the held results append to. Absent on v1 (accepts and forgets).
|
|
4318
|
+
const processedKeys = new Set<string>();
|
|
4319
|
+
let dormantSessions = new Map<string, DormantSession>();
|
|
4320
|
+
// QA-2.1-33: registered only now that `pending` and `dormantSessions` exist: another instance's recreate may call it at any time.
|
|
4321
|
+
pendingFile?.setSnapshotProvider(journalSnapshot);
|
|
4322
|
+
const sharedJournal: InflightJournal = {
|
|
4323
|
+
async append(record, opts) {
|
|
4324
|
+
if (record.kind === "processed") {
|
|
4325
|
+
const key = processedKeyOf(record);
|
|
4326
|
+
if (key !== undefined) processedKeys.add(key);
|
|
4327
|
+
}
|
|
4328
|
+
if (pendingFile === undefined) return;
|
|
4329
|
+
// QA-2.1-19: the live owner claims the parent session (pid + instance token) at its first `inflight`/`hold` write, so
|
|
4330
|
+
// no other instance or process adopts it (and posts or wakes for a child that is still running here).
|
|
4331
|
+
if (record.kind === "inflight" || record.kind === "hold") {
|
|
4332
|
+
const parent = typeof record.parentSessionID === "string" ? record.parentSessionID : typeof record.parent === "string" ? record.parent : undefined;
|
|
4333
|
+
if (parent !== undefined && !claimSessionOnce(parent)) {
|
|
4334
|
+
logger.warn("[router] background: another live instance holds the claim of this session", { sessionID: parent });
|
|
4335
|
+
}
|
|
4336
|
+
}
|
|
4337
|
+
// `inflight` and `hold` records are fsync'd (memo §11.2); the rest only when the caller asks.
|
|
4338
|
+
const fsync = opts?.fsync === true || record.kind === "inflight" || record.kind === "hold";
|
|
4339
|
+
// QA-2.1-23: a vanished journal (or state directory) fails the append; it is never recreated behind the reload's back
|
|
4340
|
+
// (QA-2.1-16: `recreateJournal` rewrites it from the in-memory state).
|
|
4341
|
+
await pendingFile.append(record, fsync ? { fsync: true } : undefined);
|
|
4342
|
+
},
|
|
4343
|
+
hasProcessed: (key) => processedKeys.has(key),
|
|
4344
|
+
};
|
|
4345
|
+
/** QA-2.1-17: an UNVERIFIABLE line for a finish after a restart that has nothing to verify with. */
|
|
4346
|
+
const RESTART_DATA_LOST = "verification data lost in restart";
|
|
4347
|
+
/** QA-SYNC1-3: how long a held registration waits for the dispatch-time head read (started at dispatch, normally settled). */
|
|
4348
|
+
const HELD_HEAD_READ_MS = 2_000;
|
|
4349
|
+
/** QA-2.1-31: handles whose restored pending entry the adapter settled after posting the verdict itself (no second post). */
|
|
4350
|
+
const directlySettled = new Set<string>();
|
|
4351
|
+
type HeldClaim = Extract<ReturnType<typeof pending.markVerifying>, { kind: "claimed" }>;
|
|
4352
|
+
type HeldSettlement = Parameters<HeldClaim["settle"]>[0];
|
|
4353
|
+
type HeldScratch = { output: string; title: string; metadata: Record<string, unknown> };
|
|
4354
|
+
/**
|
|
4355
|
+
* QA-DF1-16: what a held entry settles with: a gate verdict as the gate reached it (method, reasons, caveats, notes), anything
|
|
4356
|
+
* else as `heldVerification`. QA-DF1-29: its `pass`/`outcome` are those of the posted tag (the gate's decision, `accepted`, which
|
|
4357
|
+
* a trivial skip or `strictUnverifiable` sets apart from the raw verdict), so every reader that re-derives a tag from them
|
|
4358
|
+
* (router_verify through `gateResult`, the restart re-post and the onVerdict fallback through `heldVerdictKind`) reads the
|
|
4359
|
+
* posted one. Done here, once, not by each reader: a reader cannot re-derive a trivial skip's acceptance (gate.ts accepts it
|
|
4360
|
+
* outside `gateResult`), and `strictUnverifiable` read after a restart need not be the value the gate decided under.
|
|
4361
|
+
*/
|
|
4362
|
+
function heldSettlementOf(outcome: FinishOutcome, held: { verdict: "PASS" | "FAIL" | "UNVERIFIABLE"; reasons: string[] }): HeldSettlement {
|
|
4363
|
+
if (outcome.kind !== "required") return heldVerification(held.verdict, held.reasons);
|
|
4364
|
+
const tag = outcome.verdict;
|
|
4365
|
+
return {
|
|
4366
|
+
...outcome.gate,
|
|
4367
|
+
verdict: { ...outcome.gate.verdict, pass: tag === "PASS", outcome: tag === "PASS" ? "pass" : tag === "FAIL" ? "fail" : "unverifiable" },
|
|
4368
|
+
};
|
|
4369
|
+
}
|
|
4370
|
+
/**
|
|
4371
|
+
* A deterministic, non-retryable result for a held entry whose outcome is not a gate verdict (QA-DF1-16): the held gate's
|
|
4372
|
+
* none/deferred/skipped/error outcomes (verification not required, a read-only skip, a deferral, a gate failure), a restart
|
|
4373
|
+
* that lost the verification data (`finishRestored`), and a verdict the adapter posted itself (`settleHeldDirect`: only its
|
|
4374
|
+
* tag and reason cross the finish API). A gate verdict settles with the gate's own verdict (see `heldSettlementOf`).
|
|
4375
|
+
*/
|
|
4376
|
+
function heldVerification(verdict: "PASS" | "FAIL" | "UNVERIFIABLE", reasons: string[]): HeldSettlement {
|
|
4377
|
+
return {
|
|
4378
|
+
verdict: {
|
|
4379
|
+
pass: verdict === "PASS",
|
|
4380
|
+
outcome: verdict === "PASS" ? "pass" : verdict === "FAIL" ? "fail" : "unverifiable",
|
|
4381
|
+
method: "deterministic",
|
|
4382
|
+
reasons,
|
|
4383
|
+
caveats: [],
|
|
4384
|
+
},
|
|
4385
|
+
retryable: false,
|
|
4386
|
+
};
|
|
4387
|
+
}
|
|
4388
|
+
/** QA-2.1-17: the `task` arguments a journaled dispatch stands in for after a restart. */
|
|
4389
|
+
function restoredTaskArgs(restored: RestoredDispatch): Record<string, unknown> {
|
|
4390
|
+
return {
|
|
4391
|
+
...(restored.prompt === undefined ? {} : { prompt: restored.prompt }),
|
|
4392
|
+
...(restored.description === undefined ? {} : { description: restored.description }),
|
|
4393
|
+
...(restored.subagentType === undefined ? {} : { subagent_type: restored.subagentType }),
|
|
4394
|
+
...(restored.cwd === undefined || restored.cwd === ctx.directory ? {} : { cwd: restored.cwd }),
|
|
4395
|
+
};
|
|
4396
|
+
}
|
|
4397
|
+
/** The verification mode of a dispatch's arguments under the current config (as `verificationFor`). */
|
|
4398
|
+
function verificationModeOfArgs(args: Record<string, unknown>): "none" | "required" | "deferred" {
|
|
4399
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
|
|
4400
|
+
const description = typeof args.description === "string" ? args.description : undefined;
|
|
4401
|
+
let mode = "off";
|
|
4402
|
+
try {
|
|
4403
|
+
mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
4404
|
+
} catch (error) {
|
|
4405
|
+
logger.warn("[router] the enforcement mode could not be read; verification off", { error: describeError(error) });
|
|
4406
|
+
}
|
|
4407
|
+
if (!shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) return "none";
|
|
4408
|
+
const dod = buildDelegationDoD({ prompt, description });
|
|
4409
|
+
return isDeferred(dod, directivesFor(dispatchDirectiveText(prompt, description)), false) ? "deferred" : "required";
|
|
4410
|
+
}
|
|
4411
|
+
/** A held verdict posted straight through the sink (no claimable pending entry carries the hold). Never rejects. */
|
|
4412
|
+
function postHeldDirect(handle: string, verdict: "PASS" | "FAIL" | "UNVERIFIABLE", text: string, reason: string | undefined): Promise<void> {
|
|
4413
|
+
if (heldSink === undefined) return Promise.resolve();
|
|
4414
|
+
heldTexts.delete(handle);
|
|
4415
|
+
return heldSink.verdict(handle, { verdict, text, ...(reason !== undefined ? { reason } : {}) }).catch((error: unknown) => {
|
|
4416
|
+
logger.warn("[router] held verdict not posted", { handle, error: describeError(error) });
|
|
4417
|
+
});
|
|
4418
|
+
}
|
|
4419
|
+
/**
|
|
4420
|
+
* The held gate: the same required gate the foreground path runs. `finish` does not await it; QA-2.1-21: it is tracked
|
|
4421
|
+
* (with its verdict post) for `idle` and `dispose`. Its verdict is posted through pending.onVerdict, or straight through
|
|
4422
|
+
* the sink when no claimable entry carries the hold. `preClaim`: the entry is already claimed (a restored hold).
|
|
4423
|
+
*/
|
|
4424
|
+
function runHeldGate(
|
|
4425
|
+
fin: FinishInput,
|
|
4426
|
+
handle: string,
|
|
4427
|
+
callInput: { tool: string; sessionID: string; callID: string; args: Record<string, unknown> },
|
|
4428
|
+
scratch: HeldScratch,
|
|
4429
|
+
extra: {
|
|
4430
|
+
delta?: DispatchDelta; dod?: ReturnType<typeof buildDelegationDoD>; workRoot?: string; unattributedWriters?: readonly string[];
|
|
4431
|
+
restoredHead?: DispatchHeadState; noDefer?: true;
|
|
4432
|
+
} | undefined,
|
|
4433
|
+
preClaim: HeldClaim | undefined,
|
|
4434
|
+
): void {
|
|
4435
|
+
const settleHeld = (outcome: FinishOutcome): Promise<void> | undefined => {
|
|
4436
|
+
// QA-SYNC1-14: the held finish settled; its call's arguments and routed-role copy are no longer needed.
|
|
4437
|
+
forgetTaskArgs(fin.callID);
|
|
4438
|
+
const claim = preClaim ?? pending.markVerifying(fin.parentSessionID, handle);
|
|
4439
|
+
// QA-2.1-1: only a gate verdict is a verdict; none/deferred/skipped/error post UNVERIFIABLE with their reason.
|
|
4440
|
+
const held = heldOutcomeOf(outcome);
|
|
4441
|
+
const text = held.line === undefined ? scratch.output : `${scratch.output.trimEnd()}\n\n${held.line}`;
|
|
4442
|
+
const reason = held.reasons[0];
|
|
4443
|
+
if (claim.kind !== "claimed") return postHeldDirect(handle, held.verdict, text, reason);
|
|
4444
|
+
rememberHeldText(handle, fin.parentSessionID, text, { verdict: held.verdict, ...(reason !== undefined ? { reason } : {}) });
|
|
4445
|
+
// QA-DF1-16: a gate verdict settles as the gate reached it (method, outcome, reasons, caveats, notes).
|
|
4446
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-gate", handle,
|
|
4447
|
+
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4448
|
+
claim.settle(heldSettlementOf(outcome, held));
|
|
4449
|
+
// onVerdict posts only for an entry that carries its hold.
|
|
4450
|
+
return claim.entry.hold === undefined ? postHeldDirect(handle, held.verdict, text, reason) : undefined;
|
|
4451
|
+
};
|
|
4452
|
+
// DF-1-3: the held gate's grader launches from the orchestrator's retained context too (C14 launcher A).
|
|
4453
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-enqueue", source: "held-gate", handle,
|
|
4454
|
+
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4455
|
+
trackHeldGate(finishDispatch(callInput, scratch, undefined, { ...extra, graderParentSessionID: fin.parentSessionID }).then(settleHeld, (error: unknown) => {
|
|
4456
|
+
logger.warn("[router] held verification failed", { handle, error: describeError(error) });
|
|
4457
|
+
return settleHeld({ kind: "error", reason: `verification unavailable: ${scrubText(String(error))}` });
|
|
4458
|
+
}));
|
|
4459
|
+
}
|
|
4460
|
+
/**
|
|
4461
|
+
* QA-2.1-17: a finish after a restart. A verdict reached before it (the restored entry's `state` record) is posted again,
|
|
4462
|
+
* never recomputed; a restored held entry re-runs the gate on its persisted DoD and changed files; anything else that
|
|
4463
|
+
* needs verification ends UNVERIFIABLE "verification data lost in restart" (the live change set and reference are gone).
|
|
4464
|
+
* Undefined: no verification applies, the plain path finishes it.
|
|
4465
|
+
*/
|
|
4466
|
+
function finishRestored(fin: FinishInput, args: Record<string, unknown>, scratch: HeldScratch): FinishResult | undefined {
|
|
4467
|
+
const lostLine = `[router] UNVERIFIABLE — ${RESTART_DATA_LOST}`;
|
|
4468
|
+
const lost = (): FinishResult => ({
|
|
4469
|
+
outputText: `${fin.outputText}\n\n${lostLine}`, suffix: `\n\n${lostLine}`,
|
|
4470
|
+
verification: { kind: "required", verdict: "UNVERIFIABLE" }, metadata: {},
|
|
4471
|
+
});
|
|
4472
|
+
const handle = fin.heldHandle;
|
|
4473
|
+
if (handle === undefined) return verificationModeOfArgs(args) === "none" ? undefined : lost();
|
|
4474
|
+
const heldResult: FinishResult = { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
|
|
4475
|
+
const claim = pending.markVerifying(fin.parentSessionID, handle);
|
|
4476
|
+
if (claim.kind === "settled") {
|
|
4477
|
+
const verdict = heldVerdictKind(claim.result.verdict.outcome, claim.result.verdict.pass);
|
|
4478
|
+
const reason = claim.result.verdict.reasons[0];
|
|
4479
|
+
const line = `[router] ${verdict}${reason === undefined ? "" : ` — ${scrubText(reason)}`}`;
|
|
4480
|
+
trackHeldGate(postHeldDirect(handle, verdict, `${scratch.output.trimEnd()}\n\n${line}`, reason));
|
|
4481
|
+
return heldResult;
|
|
4482
|
+
}
|
|
4483
|
+
if (claim.kind === "joined") {
|
|
4484
|
+
// A router_verify run of this entry is under way; its settle posts the verdict through onVerdict.
|
|
4485
|
+
trackHeldGate(claim.run);
|
|
4486
|
+
return heldResult;
|
|
4487
|
+
}
|
|
4488
|
+
// No restored entry: the child ended after the restart, so its change set was never persisted.
|
|
4489
|
+
if (claim.kind !== "claimed") return lost();
|
|
4490
|
+
const entry = claim.entry;
|
|
4491
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
|
|
4492
|
+
const description = typeof args.description === "string" ? args.description : undefined;
|
|
4493
|
+
const dod = entry.dod ?? (prompt === undefined ? undefined : buildDelegationDoD({ prompt, description }));
|
|
4494
|
+
const settleLost = (reason: string): FinishResult => {
|
|
4495
|
+
const text = `${scratch.output.trimEnd()}\n\n[router] UNVERIFIABLE — ${reason}`;
|
|
4496
|
+
rememberHeldText(handle, fin.parentSessionID, text);
|
|
4497
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-lost", handle,
|
|
4498
|
+
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4499
|
+
claim.settle(heldVerification("UNVERIFIABLE", [reason]));
|
|
4500
|
+
if (entry.hold === undefined) trackHeldGate(postHeldDirect(handle, "UNVERIFIABLE", text, reason));
|
|
4501
|
+
return heldResult;
|
|
4502
|
+
};
|
|
4503
|
+
if (dod === undefined || entry.changedFiles === "unavailable") return settleLost(RESTART_DATA_LOST);
|
|
4504
|
+
// QA-SYNC1-3: the perimeter (I4) and the dispatch-time head the gate checked before the restart are not journaled, so a
|
|
4505
|
+
// re-run gate would PASS with fewer checks: an entry that had a perimeter, or whose head cannot be confirmed, is UNVERIFIABLE.
|
|
4506
|
+
if (entry.perimeterLost === true) return settleLost(PERIMETER_LOST_REASON);
|
|
4507
|
+
if (entry.headLost === true) return settleLost(HEAD_LOST_REASON);
|
|
4508
|
+
changedFileStore.seed(fin.childSessionID, entry.changedFiles.map((file) => ({ path: file.path, status: file.status ?? "modified" })));
|
|
4509
|
+
const gateArgs = typeof args.cwd === "string" || entry.cwd === ctx.directory ? args : { ...args, cwd: entry.cwd };
|
|
4510
|
+
// QA-SYNC1-2: the journaled work root stands in for the routed-role record the restart lost.
|
|
4511
|
+
const workRoot = fin.restored?.workRoot;
|
|
4512
|
+
// QA-SYNC1-13: so does the journaled routed-role snapshot (routedRoleFor reads it until the held finish settles): the gate
|
|
4513
|
+
// places the checks in the role's root and applies the carried-resume and lineage rules, never the tier `cwd=` refusal.
|
|
4514
|
+
const routedSnapshot = fin.restored?.routed;
|
|
4515
|
+
if (routedSnapshot !== undefined && routedRoleFor(fin.callID) === undefined) routedRoleByCall.set(fin.callID, routedSnapshot);
|
|
4516
|
+
const writers = entry.unattributedWriters;
|
|
4517
|
+
const restoredHead = entry.dispatchHead;
|
|
4518
|
+
runHeldGate(fin, handle, { tool: "task", sessionID: fin.parentSessionID, callID: fin.callID, args: gateArgs }, scratch, {
|
|
4519
|
+
dod, ...(workRoot === undefined ? {} : { workRoot }), ...(writers === undefined ? {} : { unattributedWriters: writers }),
|
|
4520
|
+
...(restoredHead === undefined ? {} : { restoredHead }),
|
|
4521
|
+
// QA-SYNC1-3: a held entry settles in place: without a dispatch record a re-deferral would register an unattributed
|
|
4522
|
+
// change set (risk high) and post "deferred" instead of the held verdict, which no live held gate does.
|
|
4523
|
+
noDefer: true,
|
|
4524
|
+
}, claim);
|
|
4525
|
+
return heldResult;
|
|
4526
|
+
}
|
|
4527
|
+
const finishApi: FinishApi = {
|
|
4528
|
+
journal: sharedJournal,
|
|
4529
|
+
// QA-2.1-7: the change-set store keys a dispatch by `task:<parent>:<callID>` (finishDispatch), never by the bare call id.
|
|
4530
|
+
// The background path passes the key (it knows the parent); the foreground path maps the parent through `taskParentByCall`.
|
|
4531
|
+
captureDelta: async (callID, childSessionID, dispatchID) => {
|
|
4532
|
+
if (dispatchID !== undefined) return changedFileStore.captureDelta(callID, childSessionID, dispatchID);
|
|
4533
|
+
const parent = taskParentByCall.get(callID);
|
|
4534
|
+
return changedFileStore.captureDelta(callID, childSessionID, parent === undefined ? undefined : `task:${parent}:${callID}`);
|
|
4535
|
+
},
|
|
4536
|
+
async reload() {
|
|
4537
|
+
if (pendingFile === undefined) return;
|
|
4538
|
+
const folded = foldDormantRecords(await pendingFile.load(), { now: Date.now(), ttlMs: pendingJournalTtlMs });
|
|
4539
|
+
dormantSessions = folded.sessions;
|
|
4540
|
+
for (const key of folded.processed) processedKeys.add(key);
|
|
4541
|
+
},
|
|
4542
|
+
adopt(sessionID): AdoptedRecords | AdoptionRefused | undefined {
|
|
4543
|
+
const session = dormantSessions.get(sessionID);
|
|
4544
|
+
if (session === undefined || pendingClaimsDir === undefined) return undefined;
|
|
4545
|
+
// QA-2.1-19: a session another live instance (pid, token) claimed is not adopted, and its dormant records stay: they
|
|
4546
|
+
// are that instance's running dispatches, or they wait for a later adoption once its claim is gone.
|
|
4547
|
+
// QA-2.1-34: told apart from "nothing to adopt", so the adapter tries again at a later sighting.
|
|
4548
|
+
if (!claimSessionOnce(sessionID)) return ADOPTION_REFUSED;
|
|
4549
|
+
dormantSessions.delete(sessionID);
|
|
4550
|
+
return { holds: session.holds, inflight: session.inflight };
|
|
4551
|
+
},
|
|
4552
|
+
verificationFor(callID) {
|
|
4553
|
+
const args = taskArgsByCall.get(callID);
|
|
4554
|
+
if (args === undefined) return undefined;
|
|
4555
|
+
const prompt = typeof args.prompt === "string" ? args.prompt : undefined;
|
|
4556
|
+
const description = typeof args.description === "string" ? args.description : undefined;
|
|
4557
|
+
const dod = buildDelegationDoD({ prompt, description });
|
|
4558
|
+
const acceptance = {
|
|
4559
|
+
testsPass: dod.checks.some(c => c.kind === "testsPass"),
|
|
4560
|
+
buildPasses: dod.checks.some(c => c.kind === "buildPasses"),
|
|
4561
|
+
};
|
|
4562
|
+
let mode = "off";
|
|
4563
|
+
try {
|
|
4564
|
+
mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
|
|
4565
|
+
} catch {
|
|
4566
|
+
mode = "off";
|
|
4567
|
+
}
|
|
4568
|
+
if (!shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) return { mode: "none", acceptance };
|
|
4569
|
+
// QA-SYNC1-6: a dispatch finishDispatch verifies at once (a refused placement or cwd, the tier per-check `cwd=` refusal)
|
|
4570
|
+
// is never classified deferred, so it is held like any other required verification.
|
|
4571
|
+
if (verifiedAtOnce(callID, args, dod)) return { mode: "required", acceptance };
|
|
4572
|
+
const directives = directivesFor(dispatchDirectiveText(prompt, description));
|
|
4573
|
+
return { mode: isDeferred(dod, directives, false) ? "deferred" : "required", acceptance };
|
|
4574
|
+
},
|
|
4575
|
+
canHold(parentSessionID) {
|
|
4576
|
+
return pending.hasSlot(parentSessionID);
|
|
4577
|
+
},
|
|
4578
|
+
reserveHeld(parentSessionID, callID) {
|
|
4579
|
+
// QA-SYNC1-14: a held call keeps its arguments and routed copy until its finish settles.
|
|
4580
|
+
if (taskArgsByCall.has(callID)) backgroundCalls.add(callID);
|
|
4581
|
+
return pending.reserveHandle(parentSessionID);
|
|
4582
|
+
},
|
|
4583
|
+
// QA-2.1-14: a held dispatch that ends without a registered entry (failed, interrupted, ack failed) frees its slot at once.
|
|
4584
|
+
releaseHeld(handle) {
|
|
4585
|
+
pending.releaseHandle(handle);
|
|
4586
|
+
},
|
|
4587
|
+
async recreateJournal(records) {
|
|
4588
|
+
if (pendingFile === undefined) return;
|
|
4589
|
+
// QA-2.1-16: every record a later restore needs: the live pending entries, the sessions not adopted yet, and the
|
|
4590
|
+
// adapter's live attempts and holds. `recreate` resets the vanished state once the file is back.
|
|
4591
|
+
// QA-2.1-33: `recreate` adds the snapshot of every other instance of this process on the same journal
|
|
4592
|
+
// (`journalSnapshot`, registered below), so their records survive this instance's rewrite.
|
|
4593
|
+
await pendingFile.recreate([...journalSnapshot(), ...records]);
|
|
4594
|
+
},
|
|
4595
|
+
setAdapterSnapshot(provider) {
|
|
4596
|
+
adapterSnapshot = provider;
|
|
4597
|
+
},
|
|
4598
|
+
idle: () => heldGatesIdle(),
|
|
4599
|
+
settleHeldDirect(parentSessionID, handle, v) {
|
|
4600
|
+
const claim = pending.markVerifying(parentSessionID, handle);
|
|
4601
|
+
if (claim.kind !== "claimed") return;
|
|
4602
|
+
// QA-2.1-31: the verdict already reached the parent; settling must not post it a second time (onVerdict is synchronous).
|
|
4603
|
+
directlySettled.add(handle);
|
|
4604
|
+
try {
|
|
4605
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "verification-settle", source: "held-direct", handle,
|
|
4606
|
+
...completionIdentity(parentSessionID, claim.entry.dispatchID, claim.entry.producerSessionID) }));
|
|
4607
|
+
claim.settle(heldVerification(v.verdict, v.reason === undefined ? [] : [scrubText(v.reason)]));
|
|
4608
|
+
} finally {
|
|
4609
|
+
directlySettled.delete(handle);
|
|
4610
|
+
}
|
|
4611
|
+
},
|
|
4612
|
+
dispatchOf(callID) {
|
|
4613
|
+
const args = taskArgsByCall.get(callID);
|
|
4614
|
+
if (args === undefined) return undefined;
|
|
4615
|
+
// QA-SYNC1-14: the adapter reads the dispatch of an acknowledged background attempt; it keeps its arguments until its finish.
|
|
4616
|
+
backgroundCalls.add(callID);
|
|
4617
|
+
const text = (value: unknown): string | undefined => (typeof value === "string" ? value : undefined);
|
|
4618
|
+
const prompt = text(args.prompt);
|
|
4619
|
+
const description = text(args.description);
|
|
4620
|
+
const subagentType = text(args.subagent_type);
|
|
4621
|
+
let workRoot: string | undefined;
|
|
4622
|
+
try {
|
|
4623
|
+
workRoot = verificationScopeOf(callID, args, buildDelegationDoD({ prompt, description })).workRoot;
|
|
4624
|
+
} catch (error) {
|
|
4625
|
+
logger.warn("[router] the work root of a dispatch could not be read", { callID, error: describeError(error) });
|
|
4626
|
+
}
|
|
4627
|
+
// QA-SYNC1-13: the routed-role facts the gate reads, journaled so a restored held gate verifies it as a role dispatch.
|
|
4628
|
+
const routedRole = routedRoleFor(callID);
|
|
4629
|
+
const routed: RoutedRoleSnapshot | undefined = routedRole === undefined ? undefined : {
|
|
4630
|
+
verifyRoot: routedRole.verifyRoot, parentSessionID: routedRole.parentSessionID, resumeID: routedRole.resumeID,
|
|
4631
|
+
...(routedRole.carried === true ? { carried: true as const } : {}),
|
|
4632
|
+
...(routedRole.gated === true ? { gated: true as const } : {}),
|
|
4633
|
+
};
|
|
4634
|
+
return {
|
|
4635
|
+
...(prompt === undefined ? {} : { prompt }),
|
|
4636
|
+
...(description === undefined ? {} : { description }),
|
|
4637
|
+
...(subagentType === undefined ? {} : { subagentType }),
|
|
4638
|
+
cwd: text(args.cwd) ?? ctx.directory,
|
|
4639
|
+
...(workRoot === undefined ? {} : { workRoot }),
|
|
4640
|
+
...(routed === undefined ? {} : { routed }),
|
|
4641
|
+
};
|
|
4642
|
+
},
|
|
4643
|
+
async finish(fin: FinishInput): Promise<FinishResult> {
|
|
4644
|
+
// QA-2.1-17: after a restart the in-memory call arguments are gone; the journaled dispatch stands in for them.
|
|
4645
|
+
const args: Record<string, unknown> = taskArgsByCall.get(fin.callID) ?? (fin.restored === undefined ? {} : restoredTaskArgs(fin.restored));
|
|
4646
|
+
const callInput = { tool: "task", sessionID: fin.parentSessionID, callID: fin.callID, args };
|
|
4647
|
+
const delta = fin.delta as DispatchDelta | undefined;
|
|
4648
|
+
const scratch = { output: taskOutputText(fin.childSessionID, fin.outputText), title: "", metadata: { sessionId: fin.childSessionID } as Record<string, unknown> };
|
|
4649
|
+
const base = scratch.output.trimEnd();
|
|
4650
|
+
const suffixOf = (): string => (scratch.output.startsWith(base) ? scratch.output.slice(base.length) : "");
|
|
4651
|
+
if (fin.status !== "succeeded") {
|
|
4652
|
+
// QA-2.1-5: a failed, interrupted or unknown child produced no result to verify; the gate never runs on it. The
|
|
4653
|
+
// change-set records of the dispatch are dropped here, as finishDispatch would have.
|
|
4654
|
+
changedFileStore.clear(`task:${fin.parentSessionID}:${fin.callID}`);
|
|
4655
|
+
changedFileStore.clear(fin.childSessionID);
|
|
4656
|
+
forgetTaskArgs(fin.callID);
|
|
4657
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "none" }, metadata: {} };
|
|
4658
|
+
}
|
|
4659
|
+
if (fin.restored !== undefined) {
|
|
4660
|
+
const restored = finishRestored(fin, args, scratch);
|
|
4661
|
+
if (restored !== undefined) return restored;
|
|
4662
|
+
}
|
|
4663
|
+
if (fin.heldHandle !== undefined) {
|
|
4664
|
+
const handle = fin.heldHandle;
|
|
4665
|
+
const dod = buildDelegationDoD({
|
|
4666
|
+
prompt: typeof args.prompt === "string" ? args.prompt : undefined,
|
|
4667
|
+
description: typeof args.description === "string" ? args.description : undefined,
|
|
4668
|
+
});
|
|
4669
|
+
// QA-SYNC1-3: what the held gate checks that a restart loses (the perimeter, the dispatch-time head) is journaled as a
|
|
4670
|
+
// fact, and the unattributed writers as they are, so a restored entry is never re-gated with fewer checks.
|
|
4671
|
+
const dispatchKey = `task:${fin.parentSessionID}:${fin.callID}`;
|
|
4672
|
+
const writers = changedFileStore.unattributedWritersOf(dispatchKey, fin.childSessionID);
|
|
4673
|
+
const headRead = changedFileStore.baselineHead(dispatchKey);
|
|
4674
|
+
const startHead = headRead === undefined ? undefined
|
|
4675
|
+
: await withTimeout(headRead, HELD_HEAD_READ_MS, "dispatch head").catch(() => undefined);
|
|
4676
|
+
// The head the gate compares the tree with (as prepareVerification: the head read, else the dispatch snapshot's head and
|
|
4677
|
+
// branch) is journaled as plain data, so the gate re-run after a restart runs the same branch check. A head reader whose
|
|
4678
|
+
// read gave nothing (the gate fails closed on it too) is journaled as the fact alone (`hadHead`, restored as headLost).
|
|
4679
|
+
const baseline = changedFileStore.baselineSnapshot(dispatchKey);
|
|
4680
|
+
const dispatchHead: DispatchHeadState | undefined = startHead !== undefined && startHead !== "none"
|
|
4681
|
+
? { root: startHead.root, head: startHead.head, branch: startHead.branch, ...(startHead.reflog !== undefined ? { reflog: startHead.reflog } : {}) }
|
|
4682
|
+
: startHead === undefined && baseline !== undefined && baseline.branch !== undefined && typeof baseline.head === "string" && baseline.head !== ""
|
|
4683
|
+
? { root: baseline.root ?? baseline.cwd, head: baseline.head, branch: baseline.branch }
|
|
4684
|
+
: undefined;
|
|
4685
|
+
const heldHead = dispatchHead === undefined && startHead === undefined && headRead !== undefined;
|
|
4686
|
+
observeV2(isV2Host ? ctx.routerObservations : undefined, () => ({ family: "completion-effect", effect: "deferred-register", source: "held-register", handle,
|
|
4687
|
+
parentSessionID: fin.parentSessionID, callID: fin.callID, childSessionID: fin.childSessionID }));
|
|
4688
|
+
const reg = pending.register({
|
|
4689
|
+
orchestratorSessionID: fin.parentSessionID,
|
|
4690
|
+
dispatchID: fin.callID,
|
|
4691
|
+
producerSessionID: fin.childSessionID,
|
|
4692
|
+
producerTier: typeof args.subagent_type === "string" ? args.subagent_type : "",
|
|
4693
|
+
description: typeof args.description === "string" ? args.description : "",
|
|
4694
|
+
cwd: typeof args.cwd === "string" ? args.cwd : ctx.directory,
|
|
4695
|
+
root: undefined,
|
|
4696
|
+
dispatchedAt: fin.endedAt,
|
|
4697
|
+
dod,
|
|
4698
|
+
reference: Promise.resolve({ kind: "none", reason: "held dispatch: the required gate captures its own reference" }),
|
|
4699
|
+
changedFiles: delta === undefined || delta.files === "unavailable" ? "unavailable" : delta.files.map(f => ({ path: f.path, status: f.status })),
|
|
4700
|
+
risk: unattributedRisk(),
|
|
4701
|
+
handle,
|
|
4702
|
+
hold: { childSessionID: fin.childSessionID, callID: fin.callID },
|
|
4703
|
+
...(writers.length > 0 ? { unattributedWriters: writers } : {}),
|
|
4704
|
+
...(changedFileStore.perimeterOf(dispatchKey) !== undefined ? { heldPerimeter: true as const } : {}),
|
|
4705
|
+
...(heldHead ? { heldHead: true as const } : {}),
|
|
4706
|
+
...(dispatchHead !== undefined ? { dispatchHead } : {}),
|
|
4707
|
+
});
|
|
4708
|
+
if (!reg.ok) logger.warn("[router] held dispatch not registered", { code: reg.code, detail: reg.detail });
|
|
4709
|
+
runHeldGate(fin, handle, callInput, scratch, delta === undefined ? undefined : { delta }, undefined);
|
|
4710
|
+
return { outputText: fin.outputText, suffix: "", verification: { kind: "held", handle }, metadata: {} };
|
|
4711
|
+
}
|
|
4712
|
+
// DF-1-3: a background completion has no tool context of the orchestrator; its grader launches from the retained context of
|
|
4713
|
+
// the parent (C14 launcher A), never from whatever context is current (a role child's denies `subagent`).
|
|
4714
|
+
const restoredWorkRoot = taskArgsByCall.has(fin.callID) ? undefined : fin.restored?.workRoot;
|
|
4715
|
+
const outcome = await finishDispatch(callInput, scratch, undefined, {
|
|
4716
|
+
...(delta === undefined ? {} : { delta }), graderParentSessionID: fin.parentSessionID,
|
|
4717
|
+
...(restoredWorkRoot === undefined ? {} : { workRoot: restoredWorkRoot }),
|
|
4718
|
+
});
|
|
4719
|
+
const suffix = suffixOf();
|
|
4720
|
+
const verification: FinishResult["verification"] =
|
|
4721
|
+
outcome.kind === "deferred" ? { kind: "deferred", handle: outcome.handle }
|
|
4722
|
+
: outcome.kind === "required" ? { kind: "required", verdict: outcome.verdict }
|
|
4723
|
+
: { kind: "none" };
|
|
4724
|
+
forgetTaskArgs(fin.callID);
|
|
4725
|
+
return { outputText: fin.outputText + suffix, suffix, verification, metadata: {} };
|
|
4726
|
+
},
|
|
4727
|
+
};
|
|
4728
|
+
const attachFinish: FinishAttach = ({ held, leaseGate }) => {
|
|
4729
|
+
heldSink = held;
|
|
4730
|
+
leaseGateRef = leaseGate;
|
|
4731
|
+
return finishApi;
|
|
4732
|
+
};
|
|
4733
|
+
|
|
4734
|
+
if (isV2Host) {
|
|
4735
|
+
// Phase 1.2 (v2 only): non-enumerable, so spreading or enumerating the hooks never sees it.
|
|
4736
|
+
Object.defineProperty(routerHooks, ROUTER_TURN_STATE_ATTACH, { value: attachTurnState, enumerable: false });
|
|
4737
|
+
// Phase 2.1.4.a (v2 only): the finish API the v2 adapter attaches to; absent on v1.
|
|
4738
|
+
Object.defineProperty(routerHooks, ROUTER_FINISH_ATTACH, { value: attachFinish, enumerable: false });
|
|
4739
|
+
}
|
|
4740
|
+
return routerHooks;
|
|
3531
4741
|
};
|
|
3532
4742
|
|
|
3533
4743
|
export default ModelRouterPlugin;
|