From 274f41fdc65781ef103794430324d0ae35692abf Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:33:18 +0100 Subject: [PATCH 1/4] Route workers using measured scope and provider evidence --- docs/routing-measurement.md | 85 +++- runtime/agents/calibrated-config.ts | 10 + runtime/agents/claude.ts | 11 +- runtime/agents/codex-models.ts | 1 + runtime/agents/codex.ts | 7 +- runtime/agents/cursor.ts | 6 + runtime/agents/types.ts | 2 + runtime/app.ts | 30 +- runtime/qualification-impact.ts | 179 ++++++++ runtime/qualification-targets.ts | 355 +++++++++++++++ runtime/qualification.ts | 563 ++++++++++++++++-------- runtime/router.ts | 647 ++++++++++++++++++++-------- runtime/routing-calibration.ts | 419 ++++++++++++++++++ runtime/routing-intent.ts | 267 ++++++++++++ runtime/story-route.ts | 28 ++ runtime/team/session-sync.ts | 6 +- runtime/workers.ts | 42 +- scripts/routing-evaluate.ts | 22 + src/components/Dialogs.tsx | 5 +- src/components/Routing.tsx | 31 +- src/routing-evidence.ts | 22 + src/routing-signals.ts | 18 + src/shared.ts | 22 +- tests/agent-codex.test.ts | 28 +- tests/routing-calibration.test.ts | 230 ++++++++++ tests/routing-intent.test.ts | 105 +++++ tests/routing-qualification.test.ts | 277 ++++++++++++ tests/routing.test.ts | 316 +++++++++++++- 28 files changed, 3313 insertions(+), 421 deletions(-) create mode 100644 runtime/agents/calibrated-config.ts create mode 100644 runtime/qualification-impact.ts create mode 100644 runtime/qualification-targets.ts create mode 100644 runtime/routing-calibration.ts create mode 100644 runtime/routing-intent.ts create mode 100644 scripts/routing-evaluate.ts create mode 100644 src/routing-evidence.ts create mode 100644 src/routing-signals.ts create mode 100644 tests/routing-calibration.test.ts create mode 100644 tests/routing-intent.test.ts create mode 100644 tests/routing-qualification.test.ts diff --git a/docs/routing-measurement.md b/docs/routing-measurement.md index 92f9659..c158e27 100644 --- a/docs/routing-measurement.md +++ b/docs/routing-measurement.md @@ -45,8 +45,89 @@ Custom or unrecognized model names use a fixed non-content bucket. Show sample counts and measurement/model coverage beside comparisons. Wall-clock duration includes machine, tool and human waits; it is not pure model latency. Router selection, task mix and review delays can bias comparisons. This feature -collects evidence for later investigation; it does not automatically alter routing -policy or declare a winning model. +collects observational evidence for later investigation. Controlled calibration +uses its own opt-in input. + +## Controlled routing comparisons + +Compare the current, wording-only, graph-only and combined policies on the +same frozen stories. Decide the policy versions, candidate catalog, effort, +verification and rework budget before starting. Put all checkouts of each +repository in one group. Reserve whole repositories for evaluation before +fitting policy thresholds or estimating model performance. Use unfamiliar +repositories for the holdout and independent blind review for each first pass. + +Record one initial worker run per frozen story and candidate. Candidate identity +includes the harness, exact requested model, effort and resolved model when the +catalog supplies one. Keep candidate receipts tied to the same source revision +and cohort. Collect the provider-confirmed model, the applied effort, structured +verification, blind review and explicit first-pass acceptance. A failed check, +rejected delivery or observed provider fallback counts against the route. An +unfinished run or missing proof stays unresolved. Record token usage, elapsed +time and actual USD cost in millionths through the same bounded rework window. +Use `null` for unavailable totals, including costs a subscription cannot expose. + +Run the evaluator locally from a development checkout with dependencies installed. + +```sh +node --import tsx scripts/routing-evaluate.ts path/to/frozen-outcomes.json +``` + +The input uses `version: 1`, `heldOutRepoIds`, `outcomes` and `decisions`. Use +opaque `repoId` and `storyId` values and the frozen Git commit as `revision`. +Each outcome supplies `cohort` (`kind`, `tier`, `coverage`), `candidate` +(`harness`, `model`, `effort`, optional `resolvedModel`), `observedModel`, +`observedEffort`, `execution`, `checks`, `blindReview`, `acceptance` and the +nullable totals `totalCostMicros`, `totalTokens` and `totalDurationMs`. A policy +decision has the same frozen story identity and a `routes` map with the four +policy names. Each route is the selected candidate or `null` for an abstention. +The execution states are `running`, `completed` and `failed`. For checks and +blind review, use `passed`, `failed` or `unverified`. For acceptance, use +`accepted`, `rejected` or `pending`. +Keep the raw experiment file local. The evaluator reads measurements and emits +aggregates. It launches no workers and makes no network calls. + +The held-out report compares policies on stories with an observed choice for +every policy and reports coverage for each. Cost, tokens and duration each use a +common denominator across policies. A missing outcome stays visible in the +coverage counts. Keep those counts alongside any reported improvement. + +The calibration snapshot uses paired stories from the training repositories. +Each repository contributes one equally weighted first-pass acceptance share +per cohort and candidate. Unresolved runs contribute zero to the lower bound. +The bound uses a one-sided Hoeffding margin with a correction for the candidates +compared in the cohort. It assumes independently sampled repository groups and +applies only to the frozen protocol and cohort. [Hoeffding, 1963](https://doi.org/10.1080/01621459.1963.10500830) + +Automatic calibrated selection requires at least 30 paired stories across eight +repositories, complete cost coverage, an exact eligible model and effort, and a +lower bound at or above the task’s reliability target. The targets are 80% for +fast, 85% for balanced, 90% for frontier and 95% for extreme. A model alias +needs its concrete provider identity before its results can apply. + +To enable calibrated selection, save only the evaluator’s `calibration` object +as `routing-calibration.json` in the local MemCode data directory shown in +Settings. MemCode reads that snapshot when planning and when starting a worker. +The snapshot digest detects accidental alteration of the aggregate. The +operator supplies the underlying receipts and vouches for the experiment's +provenance. Missing, malformed or sparse evidence leads to the deterministic +envelope policy. + +## Routing a story locally + +The router reads the story title, brief and declared scope. It resolves exact +references against that checkout and records which targets came from search. +Work size uses AST measurements and scope. Impact uses the union of the observed +callers, files and flows across up to five anchors. Module counts are available +when the graph returns module identities. Incomplete coverage raises the minimum +tier and missing counts stay unknown. Review the inputs under **Why this model?** +on the story card. + +Automatic routing compares the account catalogs of connected, approved workers. +Story overrides take precedence. When a follow-up can resume a verified local +conversation, its provider takes priority unless a story or workspace choice +specifies another provider. The story brief remains the routing input for that +pass. ## Planning and privacy diff --git a/runtime/agents/calibrated-config.ts b/runtime/agents/calibrated-config.ts new file mode 100644 index 0000000..aa8fbe8 --- /dev/null +++ b/runtime/agents/calibrated-config.ts @@ -0,0 +1,10 @@ +import type { AgentSessionOptions } from "./types"; + +export function assertCalibratedConfiguration( + options: Pick, + model: unknown, + effort: unknown, +): void { + if (options.calibratedModel && (model !== options.calibratedModel || effort !== options.effort)) + throw Error("The worker could not confirm the calibrated model and effort. Refresh the worker catalog and plan the story again."); +} diff --git a/runtime/agents/claude.ts b/runtime/agents/claude.ts index 5993688..3b04ee3 100644 --- a/runtime/agents/claude.ts +++ b/runtime/agents/claude.ts @@ -15,6 +15,7 @@ import type { import type { AgentSession, AgentSessionOptions } from "./types"; import { withoutPermissionArgs } from "./permissions"; import { ClaudeMeasurements } from "./claude-measurements"; +import { assertCalibratedConfiguration } from "./calibrated-config"; type Frame = Record; const bounded = (value: unknown, limit = 16000): string => @@ -89,7 +90,7 @@ function runClaudeSession(options: AgentSessionOptions, inspect?: (models: Model "stdio", "--permission-mode", nativeMode, - ...(options.model && options.model !== "default" ? ["--effort", options.effort, "--model", options.model] : []), + ...(options.model && options.model !== "default" ? ["--effort", options.effort, "--model", options.calibratedModel ?? options.model] : []), ...profile, ...withoutPermissionArgs("claude", options.toolArgs), ], @@ -399,8 +400,12 @@ function runClaudeSession(options: AgentSessionOptions, inspect?: (models: Model return; } if (options.model && options.model !== "default") { - try { selectClaudeModel(offered, options.model, true); } - catch (error) { fail(error instanceof Error ? error.message : String(error)); return; } + try { + const selected = selectClaudeModel(offered, options.model, true); + const model = offered.find((entry) => entry.id === selected || entry.resolvedId === selected); + assertCalibratedConfiguration(options, model?.resolvedId ?? model?.id, + model?.efforts?.includes(options.effort) ? options.effort : undefined); + } catch (error) { fail(error instanceof Error ? error.message : String(error)); return; } } emit({ type: "prompted" }); write({ diff --git a/runtime/agents/codex-models.ts b/runtime/agents/codex-models.ts index 3897ba8..2005af4 100644 --- a/runtime/agents/codex-models.ts +++ b/runtime/agents/codex-models.ts @@ -73,6 +73,7 @@ export async function readCodexCatalog(command: Command, env: NodeJS.ProcessEnv, export function selectCodexModel(catalog: CodexCatalog, requested: string, automatic: boolean, tier?: ModelTier): string { const { models } = catalog; if (catalog.allModelsDenied) throw Error("Codex rejected every model advertised for this account. Check your Codex account or select another worker."); + if (requested === codexDefaultModel) return ""; if (requested && requested !== codexDefaultModel && models.some(m => m.id === requested)) return requested; if (requested && requested !== codexDefaultModel && !automatic) throw Error(`Codex cannot confirm access to ${requested} for this account. Choose Match task complexity or an available model.`); diff --git a/runtime/agents/codex.ts b/runtime/agents/codex.ts index 2e781fb..0c6c3aa 100644 --- a/runtime/agents/codex.ts +++ b/runtime/agents/codex.ts @@ -8,6 +8,7 @@ import type { AgentSession, AgentSessionOptions } from "./types"; import type { ReasoningEffort } from "../../src/shared"; import type { ReportedTokenUsage } from "../../src/measurements"; import { withoutPermissionArgs } from "./permissions"; +import { assertCalibratedConfiguration } from "./calibrated-config"; import type { WorkerInputOption, WorkerInputPrompt, @@ -679,7 +680,10 @@ function runCodexSession(options: AgentSessionOptions, inspect?: (result: CodexC catalog = await readCodexCatalog(options.command, { ...options.env, ...options.command.env }, (method, params) => request(method, params, 4500), refreshCatalog); if (inspect) { inspect(catalog); finish({ exitCode: 0 }); return; } selected = selectCodexModel(catalog, options.model, !!options.automaticModelTier, options.automaticModelTier); - const efforts = catalog.models.find(m => m.id === selected)?.efforts; + const offered = catalog.models.find(model => model.id === selected); + const efforts = offered?.efforts; + assertCalibratedConfiguration(options, offered?.resolvedId ?? offered?.id, + efforts?.includes(options.effort) ? options.effort : undefined); if (!selected || (efforts?.length && !efforts.includes(options.effort))) selectedEffort = undefined; if (selected !== options.model && options.automaticModelTier) emit({ type: "message", role: "system", text: selected ? `Codex selected ${selected} from this account’s available models.` : "Codex will use this account’s default model." }); @@ -719,6 +723,7 @@ function runCodexSession(options: AgentSessionOptions, inspect?: (result: CodexC threadId = thread.thread?.id; attemptedModel = selected || thread.model; if (!threadId) throw new Error("Codex did not return a thread ID."); + assertCalibratedConfiguration(options, thread.model, thread.reasoningEffort); if (["low", "medium", "high", "xhigh"].includes(thread.reasoningEffort)) reportedEffort = thread.reasoningEffort; modelMeasurement(thread.model, "codex-thread"); diff --git a/runtime/agents/cursor.ts b/runtime/agents/cursor.ts index f02959c..a762a17 100644 --- a/runtime/agents/cursor.ts +++ b/runtime/agents/cursor.ts @@ -12,6 +12,7 @@ import { join } from "node:path"; import type { AgentSession, AgentSessionOptions } from "./types"; import { standardACPCatalog, selectStandardACPModel, standardModelMeasurement } from "./acp-models"; import { withoutPermissionArgs } from "./permissions"; +import { assertCalibratedConfiguration } from "./calibrated-config"; import type { AgentMeasurement } from "../../src/measurements"; import type { WorkerInputOption, @@ -761,6 +762,11 @@ function runCursorSession(options: AgentSessionOptions, inspect?: (session: Json const modelMeasurement = transport ? standardModelMeasurement(transport.id, config, legacyModel) : cursorSessionModel(config, legacyModel); + if (options.calibratedModel) { + const confirmed = config.find(option => option.category === "model" || option.id === "model")?.currentValue ?? legacyModel; + assertCalibratedConfiguration(options, confirmed === options.model ? modelMeasurement?.model?.id : undefined, + modelMeasurement?.model?.effort); + } if (modelMeasurement) emit(modelMeasurement); if ( session.modes?.currentModeId !== "agent" && diff --git a/runtime/agents/types.ts b/runtime/agents/types.ts index f93ad66..5972f00 100644 --- a/runtime/agents/types.ts +++ b/runtime/agents/types.ts @@ -32,6 +32,8 @@ export interface AgentSessionOptions { env: NodeJS.ProcessEnv; model: string; effort: ReasoningEffort; + /** A calibrated route must confirm this model and effort before prompting. */ + calibratedModel?: string; automaticModelTier?: import("../../src/shared").ModelTier; /** Device-local provider session to continue for this story and checkout. */ resumeSessionId?: string; diff --git a/runtime/app.ts b/runtime/app.ts index 4d46e9b..fe7f3a2 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -27,7 +27,8 @@ import { WorkerManager } from "./workers"; import { PreviewManager } from "./preview"; import { localURL } from "./urls"; import { discoverHarnesses } from "./catalog"; -import { planDefinedStory } from "./story-route"; +import { planDefinedStory, readRoutingCalibration } from "./story-route"; +import { qualificationRequestFingerprint } from "./qualification"; import { registerPlanning } from "./planning"; import { registerPlanningControls } from "./planning-controls"; import { ensureTaskEpic } from "./epic-workspace"; @@ -769,20 +770,31 @@ export async function createRuntime( if (parent.analysis !== "ready") await analyze(parent.id); const current = task(id); if (isActive(current)) throw new Error(activeRouteError); - const installed = await discover(); - current.evidence = await engine.qualify( - epicAnalysisProject(project(current.projectId), current), - current, - ); + const measurement = { ...current, scope: current.scope?.slice() }; + const measuredRequest = qualificationRequestFingerprint(measurement); + const [installed, evidence, calibration] = await Promise.all([ + discover(), + engine.qualify( + epicAnalysisProject(project(measurement.projectId), measurement), + measurement, + ), + readRoutingCalibration(store.dir), + ]); const latest = task(id); if (isActive(latest)) throw new Error(activeRouteError); - latest.route = planDefinedStory( + if (latest.epicId !== measurement.epicId || + qualificationRequestFingerprint(latest) !== measuredRequest) + throw Error("The story changed during measurement. Plan the worker again for the new scope."); + const route = planDefinedStory( latest, - latest.evidence, + evidence, installed, store.state, + calibration, ); - latest.harness = latest.route.harness; + latest.evidence = evidence; + latest.route = route; + latest.harness = route.harness; latest.updatedAt = now(); await changed(); }; diff --git a/runtime/qualification-impact.ts b/runtime/qualification-impact.ts new file mode 100644 index 0000000..7bcd8bf --- /dev/null +++ b/runtime/qualification-impact.ts @@ -0,0 +1,179 @@ +import type { RoutingImpactEvidence } from "../src/routing-evidence"; +import { + isNearbyTest, + type QualificationRead, + type QualificationTarget, +} from "./qualification-targets"; + +type ImpactRow = Record; +const TARGET_LIMIT = 5; +const text = (value: unknown): string => + typeof value === "string" ? value : ""; +const path = (value: string) => { + const normalized = value.replaceAll("\\", "/").replace(/^\.\//, ""); + return process.platform === "win32" ? normalized.toLowerCase() : normalized; +}; +const count = (value: unknown): number | undefined => + typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : undefined; +const entries = (value: unknown): ImpactRow[] => + Array.isArray(value) + ? value.filter((row) => !!row && typeof row === "object") + : []; + +interface Observations { + identities: Set; + floor?: number; +} +const observations = (): Observations => ({ identities: new Set() }); +function recordFloor( + group: Observations, + observed: number | undefined, + usableZero: boolean, +) { + if (observed !== undefined && (observed > 0 || usableZero)) + group.floor = Math.max(group.floor ?? 0, observed); +} +function unionSize(group: Observations) { + return group.floor !== undefined || group.identities.size > 0 + ? Math.max(group.floor ?? 0, group.identities.size) + : undefined; +} + +export async function collectQualificationImpact( + confirmed: QualificationTarget[], + inferred: QualificationTarget[], + repoId: string, + read: QualificationRead, + scopeIncomplete: boolean, +): Promise<{ impact: RoutingImpactEvidence; testPaths: Set }> { + const targets = confirmed.length ? confirmed : inferred; + const testPaths = new Set(); + const symbols = observations(), + files = observations(), + processes = observations(); + const modules = new Set(); + const namedOnlyFiles = new Set(), + typedFiles = new Set(); + let observedTargets = 0; + let incomplete = + scopeIncomplete || !confirmed.length || targets.length > TARGET_LIMIT; + const scans = targets.slice(0, TARGET_LIMIT); + // Batches bound contention with Memtrace's graph maintenance lane. + for (let offset = 0; offset < scans.length; offset += 2) { + const batch = scans.slice(offset, offset + 2); + const answers = await Promise.all( + batch.map((target) => + read("get_impact", { + target: target.nodeId ?? target.scopePath ?? target.name, + file_path: target.file, + direction: "upstream", + depth: 3, + }), + ), + ); + for (const [index, answer] of answers.entries()) { + const target = batch[index]; + if ( + answer?.found !== true || + (answer.target?.node_id && + target.nodeId && + answer.target.node_id !== target.nodeId) + ) { + incomplete = true; + continue; + } + observedTargets++; + const partial = + answer.risk === "UNKNOWN" || + answer.graph_incomplete === true || + answer.truncated === true || + answer.total_affected_is_lower_bound === true; + const rows = Object.values(answer.by_depth ?? {}).flatMap(entries); + const seenSymbols = new Set(); + for (const row of rows) { + const repo = text(row.repo_id) || repoId, + file = path(text(row.file_path)); + const stableId = text(row.node_id ?? row.id); + if (stableId) { + const identity = `${repo}\0${stableId}`; + seenSymbols.add(identity); + symbols.identities.add(identity); + if (row.kind === "Module") modules.add(identity); + } + if (file) { + typedFiles.add(file); + files.identities.add(`${repo}\0${file}`); + if (repo === repoId && isNearbyTest(file)) testPaths.add(file); + } + } + const namedFiles = new Set(); + for (const entry of Array.isArray(answer.affected_files) + ? answer.affected_files + : []) { + const file = path( + typeof entry === "string" + ? entry + : text(entry?.file_path ?? entry?.path), + ); + if (!file) continue; + namedFiles.add(file); + const repo = typeof entry === "object" ? text(entry?.repo_id) : ""; + if (repo) { + typedFiles.add(file); + files.identities.add(`${repo}\0${file}`); + if (repo === repoId && isNearbyTest(file)) testPaths.add(file); + } else namedOnlyFiles.add(file); + } + const seenProcesses = new Set(); + for (const entry of Array.isArray(answer.affected_processes) + ? answer.affected_processes + : []) { + const id = + typeof entry === "string" ? entry : text(entry?.node_id ?? entry?.id); + if (!id) continue; + const identity = `${text(entry?.repo_id) || repoId}\0${id}`; + seenProcesses.add(identity); + processes.identities.add(identity); + } + const total = count(answer.total_affected); + const totalFiles = + count(answer.affected_files_count) ?? + (Array.isArray(answer.affected_files) + ? answer.affected_files.length + : undefined); + const totalProcesses = + count(answer.affected_processes_count) ?? + (Array.isArray(answer.affected_processes) + ? answer.affected_processes.length + : undefined); + // A legacy or truncated answer may report counts without identities. + // The largest known single-target count is a safe union lower bound. + recordFloor(symbols, total, !partial); + recordFloor(files, totalFiles, !partial); + recordFloor(processes, totalProcesses, !partial); + incomplete ||= + partial || + total !== seenSymbols.size || + totalFiles !== namedFiles.size || + totalProcesses !== seenProcesses.size; + } + } + for (const file of namedOnlyFiles) { + if (!typedFiles.has(file)) files.identities.add(file); + } + return { + impact: { + targetCount: targets.length, + observedTargets, + basis: confirmed.length ? "confirmed" : "inferred", + incomplete, + affectedSymbols: unionSize(symbols), + affectedFiles: unionSize(files), + affectedProcesses: unionSize(processes), + affectedModules: modules.size || undefined, + }, + testPaths, + }; +} diff --git a/runtime/qualification-targets.ts b/runtime/qualification-targets.ts new file mode 100644 index 0000000..df274b2 --- /dev/null +++ b/runtime/qualification-targets.ts @@ -0,0 +1,355 @@ +import { realpath, stat } from "node:fs/promises"; +import { basename, isAbsolute, relative, resolve } from "node:path"; +import type { Project, WorkItem } from "../src/shared"; +import { normalizedPath, repoFiles, visible } from "./context/source"; +import { within } from "./local"; +import type { RoutingIntentAnalysis } from "./routing-intent"; + +type Row = Record; +export type QualificationRead = ( + name: string, + args: Row, +) => Promise; +export interface QualificationTarget { + name: string; + file: string; + line: number; + endLine: number; + kind: string; + nodeId?: string; + scopePath?: string; + exported: boolean; +} + +const FILE_LIMIT = 4; +const SYMBOL_LIMIT = 5; +const SAMPLE_LIMIT = 8; +const excluded = + /(^|\/)(\.git|\.memcode|\.memdb|\.memtrace|node_modules|target|dist|dist-runtime)(\/|$)/; +const containers = new Set([ + "Class", + "Struct", + "Interface", + "Trait", + "Module", + "Namespace", +]); +export const isNearbyTest = (file: string) => + /(?:^|[/\\])(?:tests?|__tests__)[/\\]|\.(?:test|spec)\./i.test(file); +const callable = (target: QualificationTarget) => + target.kind === "Function" || target.kind === "Method"; +const ordinal = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); +const pathKey = (file: string) => + process.platform === "win32" ? file.toLowerCase() : file; +const text = (value: unknown): string => + typeof value === "string" ? value : ""; +const lineNumber = (value: unknown): number => + typeof value === "number" && Number.isSafeInteger(value) && value > 0 + ? value + : 0; +const list = (value: unknown): Row[] => + Array.isArray(value) + ? value.filter((row) => !!row && typeof row === "object") + : []; +const identity = (target: QualificationTarget) => + target.nodeId ?? + `${pathKey(target.file)}:${target.line}:${target.kind}:${target.scopePath ?? target.name}`; +const distinct = (targets: QualificationTarget[]) => [ + ...new Map(targets.map((target) => [identity(target), target])).values(), +]; + +async function checkoutPath(root: string, file: string, directory = false) { + if (file.split(/[/\\]/).includes("..")) return undefined; + try { + const absolute = await realpath(resolve(root, file)); + const key = normalizedPath(relative(root, absolute)); + if (!key || !within(root, absolute) || excluded.test(key)) return undefined; + const info = await stat(absolute); + if (info.isFile() || (directory && info.isDirectory())) return key; + } catch { + return undefined; + } +} + +function targetFrom( + row: Row | undefined, + project: Project, + root?: string, +): QualificationTarget | undefined { + if ( + !row || + (row.repo_id && row.repo_id !== project.repoId) || + (row.branch && row.branch !== project.branch) + ) + return; + const rawFile = text(row.file_path), + name = text(row.name), + kind = text(row.kind); + if (!rawFile || !name || !kind) return; + const file = normalizedPath( + root && isAbsolute(rawFile) && within(root, rawFile) + ? relative(root, rawFile) + : rawFile, + ); + if ( + /^(?:\/|[A-Za-z]:)|(?:^|\/)\.\.(?:\/|$)/.test(file) || + excluded.test(file) + ) + return; + const line = lineNumber(row.symbol_start_line ?? row.start_line); + return { + name, + kind, + file, + line, + endLine: lineNumber(row.symbol_end_line ?? row.end_line) || line, + nodeId: text(row.node_id) || undefined, + scopePath: text(row.scope_path) || undefined, + exported: row.is_exported === true || kind === "APIEndpoint", + }; +} + +function exactLine(entries: QualificationTarget[], line: number) { + const matches = entries + .filter((row) => row.line > 0 && row.line <= line && row.endLine >= line) + .sort((a, b) => a.endLine - a.line - (b.endLine - b.line)); + const best = matches[0], + other = matches[1]; + if (best && (!other || best.endLine - best.line < other.endLine - other.line)) + return best; +} + +function containsClipped(context: Row) { + const page = context.pagination?.contains; + if (page) + return page.next_offset != null || page.available_is_lower_bound === true; + return context.truncated === true || context.graph_truncated === true; +} + +export async function resolveQualificationTargets( + project: Project, + task: WorkItem, + intent: RoutingIntentAnalysis, + read: QualificationRead, +) { + const root = project.path + ? await realpath(project.path).catch(() => undefined) + : undefined; + const { paths, symbols, errors } = intent.references; + const declared = task.scope ?? []; + const fileHints = [ + ...declared.map((file) => ({ file, line: undefined, declared: true })), + ...paths.map((ref) => ({ ...ref, declared: false })), + ]; + const requestedFiles = new Map(); + for (const hint of fileHints) { + const key = `${pathKey(normalizedPath(hint.file))}:${hint.line ?? ""}`; + if (!requestedFiles.has(key)) requestedFiles.set(key, hint); + } + let unresolved = + Math.max(0, requestedFiles.size - FILE_LIMIT) + + Math.max(0, symbols.length - SYMBOL_LIMIT); + let incomplete = false; + const confirmed: QualificationTarget[] = [], + inferred: QualificationTarget[] = []; + const resolvedFiles: string[] = [], + declaredPaths: string[] = []; + const fileContexts = new Map< + string, + Awaited> + >(); + const incompleteFiles = new Set(); + let fileInventory: Promise | undefined; + const candidates = (rows: Row[]) => + rows.flatMap((row) => targetFrom(row, project, root) ?? []); + if (project.path && !root) { + return { + confirmed, + inferred, + sourceFiles: resolvedFiles, + symbols: [], + unresolved: requestedFiles.size + symbols.length, + incomplete: true, + }; + } + + for (const reference of [...requestedFiles.values()].slice(0, FILE_LIMIT)) { + let file = root + ? await checkoutPath(root, reference.file, reference.declared) + : reference.file; + if (!file && root && !reference.file.includes("/") && !reference.declared) { + fileInventory ??= repoFiles(root).catch(() => []); + const matches = (await fileInventory).filter( + (entry) => pathKey(basename(entry)) === pathKey(reference.file), + ); + if (matches.length === 1) file = await checkoutPath(root, matches[0]); + } + if (!file) { + unresolved++; + continue; + } + if (reference.declared) declaredPaths.push(file); + if ( + !reference.declared && + declared.length && + (!declaredPaths.length || + !visible(pathKey(file), declaredPaths.map(pathKey))) + ) { + unresolved++; + continue; + } + resolvedFiles.push(file); + if (!fileContexts.has(file)) + fileContexts.set( + file, + await read("get_symbol_context", { + symbol: basename(file), + file_path: file, + limit: 64, + }), + ); + const context = fileContexts.get(file); + const target = targetFrom(context?.symbol, project, root); + if ( + !context?.found || + context.ambiguous || + (target && pathKey(target.file) !== pathKey(file)) + ) { + unresolved++; + continue; + } + const declarations = candidates(list(context.contains)).filter( + (row) => pathKey(row.file) === pathKey(file), + ); + const clipped = containsClipped(context); + if (reference.line) { + let match = exactLine(declarations, reference.line); + if (match && containers.has(match.kind) && match.nodeId) { + const container = await read("get_symbol_context", { + symbol: match.nodeId, + file_path: file, + limit: 64, + }); + if ( + container?.found && + !container.ambiguous && + targetFrom(container.symbol, project, root)?.nodeId === match.nodeId + ) { + const members = candidates(list(container.contains)).filter( + (row) => pathKey(row.file) === pathKey(file), + ); + match = exactLine(members, reference.line) ?? match; + incomplete ||= containsClipped(container); + } else incomplete = true; + } + if (match) confirmed.push(match); + else unresolved++; + incomplete ||= clipped; + } else { + if (target?.kind === "File") confirmed.push(target); + else unresolved++; + const callables = declarations.filter(callable); + inferred.push(...callables.slice(0, SAMPLE_LIMIT)); + if (clipped || callables.length > SAMPLE_LIMIT) + incompleteFiles.add(pathKey(file)); + } + } + + const hardScope = declared.length + ? declaredPaths + : intent.signals.fileScopeOnly + ? resolvedFiles + : undefined; + const inScope = (target: QualificationTarget) => + !hardScope || + (hardScope.length > 0 && + visible(pathKey(target.file), hardScope.map(pathKey))); + // An exact file fixes path ambiguity, while an unqualified name still goes + // through Memtrace's declaration selector and retains its ambiguity verdict. + for (const symbol of symbols.slice(0, SYMBOL_LIMIT)) { + const file = + new Set(resolvedFiles).size === 1 ? resolvedFiles[0] : undefined; + const context = await read("get_symbol_context", { + symbol, + ...(file ? { file_path: file } : {}), + limit: 4, + }); + const target = targetFrom(context?.symbol, project, root); + if ( + !target || + !context?.found || + context.ambiguous || + (target.name !== symbol && target.scopePath !== symbol) || + (file && pathKey(file) !== pathKey(target.file)) || + !inScope(target) || + (root && !(await checkoutPath(root, target.file))) + ) { + unresolved++; + continue; + } + confirmed.push(target); + } + + if ( + intent.searchQuery && + (!hardScope || hardScope.length > 0) && + ((!confirmed.length && !inferred.length) || + unresolved > 0 || + errors.length > 0) + ) { + const search = await read("find_code", { + query: intent.searchQuery, + limit: SAMPLE_LIMIT, + include_context: true, + ...(hardScope?.length === 1 ? { file_path: hardScope[0] } : {}), + }); + const result = candidates(list(search?.results)) + .filter(callable) + .filter(inScope); + for (const row of result) { + if (!root || (await checkoutPath(root, row.file))) inferred.push(row); + } + incomplete ||= + search?.status !== "complete" || + !!search.context?.incomplete_reasons?.length; + } + + const exactMatches = distinct(confirmed.filter(inScope)); + const preciseFiles = new Set( + exactMatches + .filter((row) => row.kind !== "File") + .map((row) => pathKey(row.file)), + ); + const exact = exactMatches.filter( + (row) => row.kind !== "File" || !preciseFiles.has(pathKey(row.file)), + ); + const exactKeys = new Set(exact.map(identity)); + const estimates = distinct(inferred.filter(inScope)).filter( + (row) => + !preciseFiles.has(pathKey(row.file)) && !exactKeys.has(identity(row)), + ); + // Keep the narrowest verified definition first for UI and Fleet consumers. + const orderedExact = exact.sort( + (a, b) => + Number(a.kind === "File") - Number(b.kind === "File") || + ordinal(a.file, b.file) || + a.line - b.line || + ordinal(a.name, b.name), + ); + return { + confirmed: orderedExact, + inferred: estimates, + unresolved, + incomplete: + incomplete || + unresolved > 0 || + [...incompleteFiles].some((file) => !preciseFiles.has(file)), + sourceFiles: [...new Set(resolvedFiles)].sort(), + symbols: distinct([ + ...orderedExact.filter(callable), + ...orderedExact.filter((entry) => entry.kind !== "File"), + ...estimates, + ...orderedExact, + ]).slice(0, SAMPLE_LIMIT), + }; +} diff --git a/runtime/qualification.ts b/runtime/qualification.ts index d992525..c7ed805 100644 --- a/runtime/qualification.ts +++ b/runtime/qualification.ts @@ -1,16 +1,27 @@ import { createHash } from "node:crypto"; -import { readFile, stat } from "node:fs/promises"; -import { basename, resolve } from "node:path"; +import { readFile, realpath, stat } from "node:fs/promises"; +import { resolve } from "node:path"; import { isActive } from "../src/domain"; import type { Evidence, Project, WorkItem } from "../src/shared"; import { git, now, within } from "./local"; -import { verifiedIndexRevision } from "./memtrace-peer-index"; +import { + exactRevisionSource, + pathKey as checkoutKey, + verifiedIndexRevision, +} from "./memtrace-peer-index"; +import { collectQualificationImpact } from "./qualification-impact"; +import { + isNearbyTest, + resolveQualificationTargets, +} from "./qualification-targets"; +import { analyzeRoutingIntent } from "./routing-intent"; interface GraphClient { call( project: Project, name: string, args: Record, + signal?: AbortSignal, ): Promise; } @@ -36,6 +47,9 @@ export interface EvidenceBinding { indexBranch?: string; /** The engine's own reason for not being ready, when it gave one. */ indexReason?: string; + /** Re-evaluate when the request changed even if the source did not. */ + requestFingerprint?: string; + resolvedFiles?: string[]; checkedAt: string; } export interface BoundEvidence extends Evidence { @@ -49,6 +63,12 @@ export interface IndexObservation { branch?: string; /** Why the engine is not ready, in its words (branch_publication_incomplete). */ reason?: string; + revision?: string; + graphRevision?: string; + sourceRevision?: string; + sourceCommit?: string; + changedDuringRead?: boolean; + wrongCheckout?: boolean; /** Repo-relative files whose working content differs from the index. */ mismatched: string[]; /** The engine counted more mismatches than it listed. */ @@ -79,7 +99,19 @@ export interface EvidenceRefresh { const BOUND_FILES = 64, DIRECTORY_MEMBERS = 200, - HASHED_BYTES = 2 * 1024 * 1024; + HASHED_BYTES = 2 * 1024 * 1024, + QUALIFICATION_READ_MS = 12_000; +export const qualificationRequestFingerprint = (task: WorkItem) => + createHash("sha256") + .update( + JSON.stringify([ + task.title, + task.description, + task.kind ?? null, + task.scope ?? [], + ]), + ) + .digest("hex"); const fileKey = (file: string) => process.platform === "win32" ? file.toLowerCase() : file; const overlaps = (a: string, b: string) => { @@ -100,7 +132,7 @@ function repoFile(root: string, file: string): string | null { .replace(/\/+$/, ""); const base = clean(root), value = clean(file).replace(/^\.\//, ""); - if (!value || value === ".." || value.startsWith("../")) return null; + if (!value || value.split("/").includes("..")) return null; if (!/^([A-Za-z]:\/|\/)/.test(value)) return value; if ( fileKey(value.slice(0, base.length)) !== fileKey(base) || @@ -113,12 +145,15 @@ function repoFile(root: string, file: string): string | null { export function boundFiles( project: Project, task: WorkItem, - evidence?: Pick, + evidence?: Pick & { + binding?: Pick; + }, ): string[] { if (!project.path) return []; const files = new Map(); for (const raw of [ ...(task.scope ?? []), + ...(evidence?.binding?.resolvedFiles ?? []), ...(evidence?.symbols ?? []).map((symbol) => symbol.file), ]) { const file = repoFile(project.path, raw); @@ -147,13 +182,19 @@ async function fileHash(path: string): Promise { async function sourceHash(root: string, file: string): Promise { const path = resolve(root, file); if (!within(root, path)) return null; - let directory = false; + let canonicalRoot: string, absolute: string; try { - directory = (await stat(path)).isDirectory(); - } catch { - /* fileHash reports a missing file. */ + [canonicalRoot, absolute] = await Promise.all([ + realpath(root), + realpath(path), + ]); + if (!within(canonicalRoot, absolute)) return null; + if (!(await stat(absolute)).isDirectory()) return fileHash(absolute); + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" + ? "missing" + : null; } - if (!directory) return fileHash(path); let members: string[]; try { members = ( @@ -175,16 +216,23 @@ async function sourceHash(root: string, file: string): Promise { } if (members.length > DIRECTORY_MEMBERS) return null; const digest = createHash("sha256"); - for (const member of members) - digest - .update(member + "\0") - .update(((await fileHash(resolve(root, member))) ?? "?") + "\0"); + for (const member of members) { + const memberPath = await realpath(resolve(root, member)).catch( + () => undefined, + ); + const hash = + memberPath && within(canonicalRoot, memberPath) + ? await fileHash(memberPath) + : null; + digest.update(member + "\0").update((hash ?? "?") + "\0"); + } return digest.digest("hex").slice(0, 32); } /** Ask the engine once whether its index matches the working source. */ export async function observeIndex( client: GraphClient, project: Project, + expectedRevision?: string, ): Promise { const unobserved: IndexObservation = { known: false, @@ -197,21 +245,31 @@ export async function observeIndex( try { revision = await client.call(project, "get_query_revision", { repo_id: project.repoId, + ...(expectedRevision ? { expected_revision: expectedRevision } : {}), }); } catch { return unobserved; } if (typeof revision?.ready !== "boolean") return unobserved; - if ( - project.analysisCheckout === "owned-worktree-v1" && - !verifiedIndexRevision(revision, project, project.repoId) - ) - return { - ...unobserved, - known: true, - branch: revision.branch, - reason: "This goal's exact worktree graph has not been certified.", - }; + const owned = project.analysisCheckout === "owned-worktree-v1"; + const wrongCheckout = + (revision.repo_id && revision.repo_id !== project.repoId) || + (revision.branch && revision.branch !== project.branch) || + (typeof revision.worktree === "string" && + checkoutKey(revision.worktree) !== checkoutKey(project.path)) || + (owned + ? !exactRevisionSource(revision, project, project.repoId) + : revision.checkout_mode === "owned-worktree-v1" || + revision.graph_scope === "owned_worktree_graph"); + const ready = verifiedIndexRevision(revision, project, project.repoId); + const graphRevision = + revision._meta?.graph_revision ?? revision.graph_revision; + const reason = wrongCheckout + ? "The engine answered for a different checkout." + : (revision.reason ?? + (owned && !ready + ? "This goal's exact worktree graph has not been certified." + : undefined)); const listed: unknown[] = Array.isArray(revision.mismatched_paths) ? revision.mismatched_paths : []; @@ -222,9 +280,19 @@ export async function observeIndex( }); return { known: true, - ready: revision.ready, + ready, ...(typeof revision.branch === "string" ? { branch: revision.branch } : {}), - ...(typeof revision.reason === "string" ? { reason: revision.reason } : {}), + ...(typeof reason === "string" ? { reason } : {}), + revision: revision.token || undefined, + graphRevision: graphRevision?.token ?? revision.publication?.token, + sourceRevision: revision.source_revision || undefined, + sourceCommit: revision.source_commit || undefined, + changedDuringRead: + revision.requested_revision_matches === false || + revision.requested_source_matches === false || + revision.source_unchanged_during_observation === false || + graphRevision?.publication_unchanged_during_call === false, + wrongCheckout, mismatched, truncated: mismatched.length < listed.length || @@ -271,7 +339,10 @@ export async function observeBinding( if (staleFiles.length) return binding("stale", { staleFiles }); // The engine named why this checkout is not ready, such as a branch it has // not finished publishing. That holds for every file on the branch. - if (index.reason) return binding("stale", { indexReason: index.reason }); + if (index.reason || index.changedDuringRead) + return binding("stale", { + indexReason: index.reason ?? "The graph was changing.", + }); // A complete mismatch list that omits these files means they are published. return binding( index.mismatched.length && !index.truncated ? "current" : "unknown", @@ -292,6 +363,29 @@ function staleNote(binding: EvidenceBinding): string | null { const unconfirmed = (change: string) => `Stale source binding: ${change} Code context has not confirmed its index for this revision, so the last measurements are kept.`; +type QualityRow = Record; + +const measureNumber = (value: unknown): number | undefined => + typeof value === "number" && Number.isFinite(value) && value >= 0 + ? value + : undefined; + +function qualityMatches( + row: QualityRow, + target: { name: string; file: string; line: number; scopePath?: string }, + root: string, +) { + return ( + (!row.name || row.name === target.name) && + (!row.file_path || + fileKey(repoFile(root, row.file_path) ?? "") === fileKey(target.file)) && + (!row.start_line || !target.line || row.start_line === target.line) && + (!row.scope_path || + !target.scopePath || + row.scope_path === target.scopePath) + ); +} + export async function collectEvidence( client: GraphClient, project: Project, @@ -307,180 +401,254 @@ export async function collectEvidence( note: "Analyze this project to add measured code context.", measuredAt, }; - const rows = new Map(); - let incomplete = false, - graphRevision: string | undefined; - if (task.scope?.length) { - const scopedRows: any[][] = []; - for (const file of task.scope.slice(0, 3)) { - const context = await client.call(project, "get_symbol_context", { - repo_id: project.repoId, - branch: project.branch, - symbol: basename(file), - file_path: file, - limit: 64, - }); - graphRevision = context._meta?.graph_revision?.token ?? graphRevision; - const callables = (context.contains ?? []).filter( - (row: any) => row.kind === "Function" || row.kind === "Method", - ); - callables.sort( - (a: any, b: any) => - Number(b.kind === "Function") - Number(a.kind === "Function"), - ); - scopedRows.push(callables); - incomplete ||= - !context.found || !!context.truncated || !!context.graph_truncated; - } - // Sample each declared file before taking more symbols from any one file. - for (let index = 0; index < 8; index++) - for (const group of scopedRows) { - const row = group[index]; - if (row) - rows.set(row.file_path + "::" + (row.node_id ?? row.name), row); - } - } else { - const result = await client.call(project, "find_code", { - repo_id: project.repoId, - branch: project.branch, - query: (task.title + " " + task.description).slice(0, 1000), - limit: 6, - include_context: true, - }); - incomplete ||= - result.status !== "complete" || - !!result.context?.incomplete_reasons?.length; - graphRevision = result._meta?.graph_revision?.token ?? graphRevision; - for (const row of result.results ?? []) - rows.set(row.file_path + "::" + row.name, row); - } - const selected = [...rows.values()] - .filter((row) => row.kind === "Function" || row.kind === "Method") - .slice(0, 8); - const symbols: Evidence["symbols"] = []; - for (const row of selected) { - symbols.push({ - name: row.name, - file: row.file_path, - line: row.symbol_start_line ?? row.start_line, + + const deadline = new AbortController(); + const timeout = setTimeout(() => deadline.abort(), QUALIFICATION_READ_MS); + const stopped = new Promise((done) => { + deadline.signal.addEventListener("abort", () => done(undefined), { + once: true, }); - } - const measureSymbol = async (symbol: Evidence["symbols"][number]) => { + }); + const bounded: GraphClient = { + call: (scope, name, args) => + deadline.signal.aborted + ? Promise.resolve(undefined) + : Promise.race([ + stopped, + client.call(scope, name, args, deadline.signal), + ]), + }; + let changedPublication = false, + missingPublication = false; + const graphRevisions = new Set(); + const read = async ( + name: string, + args: QualityRow, + ): Promise => { try { - const context = await client.call(project, "get_symbol_context", { + const value = await bounded.call(project, name, { repo_id: project.repoId, branch: project.branch, - symbol: symbol.name, - file_path: symbol.file, - limit: 3, + ...args, }); - if (context.found) { - symbol.nodeId = context.symbol.node_id; - symbol.file = context.symbol.file_path; - symbol.line = context.symbol.start_line; - } - const result = await client.call( - project, - "get_function_quality_metrics", - { - repo_id: project.repoId, - branch: project.branch, - function_name: symbol.name, - file_path: symbol.file, - }, - ); - const m = result.function; - if (!m) { - incomplete = true; + if (!value || typeof value !== "object") return; + const revision = value._meta?.graph_revision; + if (typeof revision?.token === "string" && revision.token) + graphRevisions.add(revision.token); + else missingPublication = true; + if ( + revision?.publication_unchanged_during_call === false || + graphRevisions.size > 1 + ) { + changedPublication = true; return; } - symbol.metricSource = m.complexity_source === "ast" ? "ast" : "estimated"; - if (typeof m.cognitive_complexity === "number") - symbol.cognitive = m.cognitive_complexity; - if (typeof m.complexity === "number") symbol.cyclomatic = m.complexity; - if (typeof m.max_nesting === "number") symbol.nesting = m.max_nesting; - if (symbol.metricSource !== "ast") incomplete = true; + if (revision?.status === "partial") missingPublication = true; + return value; } catch { - incomplete = true; + return undefined; } }; - const measured = symbols.slice(0, 5); - for (let offset = 0; offset < measured.length; offset += 3) - await Promise.all(measured.slice(offset, offset + 3).map(measureSymbol)); - if (symbols.length > 5) incomplete = true; - let affected: number | undefined, - affectedProcesses: number | undefined, - affectedFiles: number | undefined; - if (symbols[0]) - try { - const impact = await client.call(project, "get_impact", { - repo_id: project.repoId, - branch: project.branch, - target: symbols[0].nodeId ?? symbols[0].name, - file_path: symbols[0].file, - direction: "upstream", - depth: 3, - }); - if (typeof impact.total_affected === "number") - affected = impact.total_affected; - affectedProcesses = - impact.affected_processes_count ?? - (Array.isArray(impact.affected_processes) - ? impact.affected_processes.length - : undefined); - affectedFiles = - impact.affected_files_count ?? - (Array.isArray(impact.affected_files) - ? impact.affected_files.length - : undefined); - incomplete ||= - !impact.found || - !!impact.graph_incomplete || - !!impact.truncated || - impact.risk === "UNKNOWN" || - !!impact.total_affected_is_lower_bound; - } catch { - incomplete = true; + + try { + const before = Promise.resolve(observed ?? observeIndex(bounded, project)); + const intent = analyzeRoutingIntent(task); + const scope = await resolveQualificationTargets( + project, + task, + intent, + read, + ); + const callable = scope.symbols.filter( + (target) => target.kind === "Function" || target.kind === "Method", + ); + const measurable = callable.slice(0, 5); + const measuredMetrics = new Map< + (typeof callable)[number], + Partial + >(); + const measurements = async () => { + for (let offset = 0; offset < measurable.length; offset += 2) { + await Promise.all( + measurable.slice(offset, offset + 2).map(async (target) => { + const result = await read("get_function_quality_metrics", { + function_name: target.scopePath ?? target.name, + file_path: target.file, + kind: target.kind, + }); + const matching = ( + result?.matches > 1 && Array.isArray(result?.candidates) + ? result.candidates + : [result?.function] + ).filter( + (row) => row && qualityMatches(row, target, project.path ?? ""), + ); + if (matching.length !== 1) return; + const row = matching[0]; + measuredMetrics.set(target, { + cognitive: measureNumber(row.cognitive_complexity), + cyclomatic: measureNumber(row.complexity), + nesting: measureNumber(row.max_nesting), + metricSource: + row.complexity_source === "ast" ? "ast" : "estimated", + }); + }), + ); + } + }; + const [reach] = await Promise.all([ + collectQualificationImpact( + scope.confirmed, + scope.inferred, + project.repoId, + read, + scope.incomplete, + ), + measurements(), + ]); + const firstIndex = await before; + const index = firstIndex.revision + ? await observeIndex(bounded, project, firstIndex.revision) + : firstIndex; + for (const value of [firstIndex.graphRevision, index.graphRevision]) { + if (value) graphRevisions.add(value); } - let sourceRevision: string | undefined, binding: EvidenceBinding | undefined; - if (project.path) - try { - sourceRevision = await git(project.path, ["rev-parse", "HEAD"]); - const index = observed ?? (await observeIndex(client, project)); - binding = await observeBinding( - project, - boundFiles(project, task, { symbols }), - index, + const incorrectCheckout = + firstIndex.wrongCheckout === true || index.wrongCheckout === true; + changedPublication ||= + graphRevisions.size > 1 || + incorrectCheckout || + firstIndex.changedDuringRead === true || + index.changedDuringRead === true || + !!( + firstIndex.revision && + index.revision && + firstIndex.revision !== index.revision ); - // The engine compares its index with the working files, so uncommitted - // saves it has published count as measured. Without its answer a dirty - // tree cannot be shown to be indexed. - if (!index.known) - incomplete ||= !!(await git(project.path, ["status", "--porcelain"])); - else if (!index.ready || binding.index !== "current") incomplete = true; - } catch { - incomplete = true; + const { impact } = reach; + const tests = reach.testPaths; + for (const file of scope.sourceFiles.filter(isNearbyTest)) tests.add(file); + for (const target of scope.confirmed.filter((entry) => + isNearbyTest(entry.file), + )) + tests.add(target.file); + const completeMetrics = [...measuredMetrics.values()].filter( + (metrics) => + metrics.metricSource === "ast" && + metrics.cognitive !== undefined && + metrics.cyclomatic !== undefined && + metrics.nesting !== undefined, + ).length; + const metricsComplete = + callable.length > 0 && callable.length === completeMetrics; + const symbols: Evidence["symbols"] = scope.symbols.map((target) => { + const metrics = changedPublication + ? undefined + : measuredMetrics.get(target); + return { + name: target.name, + file: target.file, + line: target.line, + nodeId: target.nodeId, + ...metrics, + }; + }); + let binding: EvidenceBinding | undefined; + let sourceRevision = index.sourceRevision; + let incomplete = + scope.incomplete || + !scope.confirmed.length || + impact.incomplete || + !metricsComplete || + changedPublication || + missingPublication || + !firstIndex.revision || + !index.revision || + deadline.signal.aborted; + if (project.path) { + try { + const sourceCommit = await git(project.path, ["rev-parse", "HEAD"]); + const current = await observeBinding( + project, + boundFiles(project, task, { + symbols, + binding: { resolvedFiles: scope.sourceFiles }, + }), + index, + ); + binding = { + ...current, + resolvedFiles: scope.sourceFiles, + requestFingerprint: qualificationRequestFingerprint(task), + }; + sourceRevision ??= sourceCommit; + incomplete ||= current.index !== "current" || !index.ready; + if (index.sourceCommit && index.sourceCommit !== sourceCommit) { + // The checkout moved after the question was answered. + changedPublication = true; + incomplete = true; + } + } catch { + incomplete = true; + } } - if (!symbols.length) incomplete = true; - return { - state: incomplete ? "partial" : "measured", - symbols, - affected, - affectedFiles, - affectedProcesses, - incomplete, - sourceRevision, - graphRevision, - measuredAt, - note: - (binding && staleNote(binding)) ?? - (!symbols.length - ? "No source anchors matched. The route remains provisional and starts above the fast tier." - : incomplete - ? "Source measurements are available, with incomplete scope or dependency coverage. Impact refers to the primary source anchor." - : "AST measurements and observed primary-anchor impact are attached. Envelope thresholds remain provisional policy."), - ...(binding ? { binding } : {}), - }; + return { + state: incomplete ? "partial" : "measured", + symbols: changedPublication ? [] : symbols, + // A union containing rows from two publications is not an observation. + impact: changedPublication + ? { + basis: impact.basis, + targetCount: impact.targetCount, + observedTargets: 0, + incomplete: true, + } + : impact, + scopeCoverage: { + confirmedTargets: changedPublication ? 0 : scope.confirmed.length, + inferredTargets: changedPublication ? 0 : scope.inferred.length, + unresolvedReferences: scope.unresolved, + measuredTargets: changedPublication ? 0 : completeMetrics, + incomplete, + ...(changedPublication || !tests.size + ? {} + : { nearbyTests: tests.size }), + ...(changedPublication + ? {} + : { + publicContracts: + scope.confirmed.filter((target) => target.exported).length || + undefined, + }), + }, + affected: changedPublication ? undefined : impact.affectedSymbols, + affectedFiles: changedPublication ? undefined : impact.affectedFiles, + affectedProcesses: changedPublication + ? undefined + : impact.affectedProcesses, + sourceRevision, + graphRevision: changedPublication + ? undefined + : graphRevisions.values().next().value, + incomplete, + measuredAt, + note: incorrectCheckout + ? "Memtrace answered for a different checkout. Measure again on this story's epic." + : changedPublication + ? "The source or graph changed while the task was measured. Measure again to use one revision." + : ((binding && staleNote(binding)) ?? + (deadline.signal.aborted + ? "The code context check reached its time limit. The route uses the evidence collected so far." + : !symbols.length + ? "No source anchors matched. The route remains provisional and starts above the fast tier." + : incomplete + ? "Source measurements cover a bounded scope. Impact may be an observed lower bound." + : "AST measurements and observed upstream impact cover the confirmed source anchors.")), + ...(binding ? { binding } : {}), + }; + } finally { + clearTimeout(timeout); + } } /** Compare the binding recorded with a story's evidence to the current one. */ @@ -602,6 +770,17 @@ export async function refreshEvidence( index ??= await observeIndex(client, project); const current = await observeBinding(project, files, index); let freshness = evidenceFreshness(evidence.binding, current); + if ( + evidence.binding?.requestFingerprint && + evidence.binding.requestFingerprint !== + qualificationRequestFingerprint(task) + ) { + const change = "The work request or its declared scope changed."; + freshness = + current.index === "current" + ? { state: "changed", reason: change } + : { state: "stale", reason: unconfirmed(change) }; + } // Unbound evidence has nothing to compare, but a worker's edit to its // files is a known change. if (freshness.state === "unknown" && touched && !evidence.binding) { @@ -630,7 +809,11 @@ export async function refreshEvidence( state: "partial", incomplete: true, note: freshness.reason, - binding: current, + binding: { + ...current, + requestFingerprint: evidence.binding?.requestFingerprint, + resolvedFiles: evidence.binding?.resolvedFiles, + }, }, ); } else if (freshness.state === "changed") { diff --git a/runtime/router.ts b/runtime/router.ts index 06558bc..e501f8e 100644 --- a/runtime/router.ts +++ b/runtime/router.ts @@ -1,5 +1,10 @@ +import { createHash } from "node:crypto"; import { cursorCatalogValue } from "../src/cursor-models"; -import { codexDefaultModel, cursorDefaultModel } from "../src/shared"; +import { + codexDefaultModel, + cursorDefaultModel, + harnessIds, +} from "../src/shared"; import { selectCodexModel } from "./agents/codex-models"; import { selectClaudeModel } from "./agents/claude-models"; import { @@ -10,12 +15,20 @@ import type { Evidence, Harness, HarnessRuntime, + ModelOption, ModelTier, ReasoningEffort, RouteDecision, Settings, WorkItem, } from "../src/shared"; +import { analyzeRoutingIntent } from "./routing-intent"; +import type { RoutingRequestSignals } from "../src/routing-signals"; +import { + estimateRoutingCandidates, + selectCalibratedCandidate, + type RoutingCalibration, +} from "./routing-calibration"; const tierOrder: ModelTier[] = ["fast", "balanced", "frontier", "extreme"]; const effort: Record = { @@ -24,6 +37,15 @@ const effort: Record = { frontier: "high", extreme: "xhigh", }; +const effortOrder = Object.values(effort); +const reliabilityTarget = { + fast: 0.8, + balanced: 0.85, + frontier: 0.9, + extreme: 0.95, +}; +const rank = (tier?: ModelTier) => (tier ? tierOrder.indexOf(tier) : -1); +const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); // Ported from the existing dogfood envelope-v2 policy. These are transparent, // provisional thresholds, not calibrated probabilities or model benchmarks. export const envelopes = [ @@ -35,6 +57,9 @@ export const envelopes = [ affected: 8, processes: 1, roots: 1, + targets: 2, + files: 4, + modules: 1, }, { tier: "balanced" as const, @@ -44,6 +69,9 @@ export const envelopes = [ affected: 50, processes: 6, roots: 1, + targets: 5, + files: 20, + modules: 4, }, { tier: "frontier" as const, @@ -53,6 +81,9 @@ export const envelopes = [ affected: 150, processes: 14, roots: 2, + targets: 8, + files: 70, + modules: 12, }, ]; function maximum(values: Array): number | null { @@ -64,60 +95,95 @@ function maximum(values: Array): number | null { function moduleRoot(file: string): string { const parts = file.replaceAll("\\", "/").split("/"); const at = parts.findIndex((part) => - ["src", "electron", "tests", "scripts", "crates"].includes(part), + ["src", "runtime", "src-tauri", "tests", "scripts", "crates"].includes( + part, + ), ); const local = at < 0 ? parts.slice(-2) : parts.slice(at); return local[1]?.includes(".") ? local[0] : local.slice(0, 2).join("/"); } -export function routingInputs(evidence?: Evidence): RouteDecision["inputs"] { +export function routingInputs( + evidence?: Evidence, + request?: RoutingRequestSignals, +): RouteDecision["inputs"] { const symbols = evidence?.symbols ?? []; + const ast = symbols.filter((symbol) => symbol.metricSource === "ast"); return { - cognitive: maximum( - symbols.map((s) => (s.metricSource === "ast" ? s.cognitive : undefined)), - ), - cyclomatic: maximum( - symbols.map((s) => (s.metricSource === "ast" ? s.cyclomatic : undefined)), - ), - nesting: maximum(symbols.map((s) => s.nesting)), + cognitive: maximum(ast.map((s) => s.cognitive)), + cyclomatic: maximum(ast.map((s) => s.cyclomatic)), + nesting: maximum(ast.map((s) => s.nesting)), affected: evidence?.affected ?? null, processes: evidence?.affectedProcesses ?? null, moduleRoots: new Set(symbols.map((s) => moduleRoot(s.file))).size, incomplete: - !evidence || evidence.incomplete || evidence.state !== "measured", + !evidence || + evidence.incomplete || + evidence.state !== "measured" || + !!evidence.scopeCoverage?.incomplete || + (!!evidence.impact?.incomplete && !request?.readOnly), sourceRevision: evidence?.sourceRevision, graphRevision: evidence?.graphRevision, + ...(request ? { request } : {}), + ...(evidence?.scopeCoverage ? { scope: evidence.scopeCoverage } : {}), + ...(evidence?.impact ? { impact: evidence.impact } : {}), }; } + +const within = (observed: number | null | undefined, limit: number) => + observed == null || observed <= limit; + +function taskTiers(input: RouteDecision["inputs"]) { + const workTier: ModelTier = + envelopes.find( + (envelope) => + within(input.cognitive, envelope.cognitive) && + within(input.cyclomatic, envelope.cyclomatic) && + within(input.nesting, envelope.nesting) && + within(input.scope?.confirmedTargets, envelope.targets) && + input.moduleRoots <= envelope.roots, + )?.tier ?? "extreme"; + + const impactTier: ModelTier | null = input.request?.readOnly + ? null + : (envelopes.find( + (envelope) => + (input.request?.publicContract !== "change" || + envelope.tier === "frontier") && + (!input.scope?.publicContracts || envelope.tier !== "fast") && + within(input.affected, envelope.affected) && + within(input.processes, envelope.processes) && + within(input.impact?.affectedFiles, envelope.files) && + within(input.impact?.affectedModules, envelope.modules), + )?.tier ?? "extreme"); + + const complete = + !input.incomplete && + input.cognitive !== null && + input.cyclomatic !== null && + input.nesting !== null && + input.moduleRoots > 0 && + (impactTier === null || + (input.affected !== null && input.processes !== null)); + const tier = + tierOrder[ + Math.max(complete ? 0 : 1, rank(workTier), rank(impactTier ?? undefined)) + ]; + return { tier, workTier, impactTier, complete }; +} + export function qualifyTier(input: RouteDecision["inputs"]): ModelTier { - for (const envelope of envelopes) { - if ( - envelope.tier === "fast" && - (input.incomplete || - input.cognitive === null || - input.cyclomatic === null || - input.nesting === null || - input.affected === null || - input.processes === null || - input.moduleRoots === 0) - ) - continue; - if ( - (input.cognitive === null || input.cognitive <= envelope.cognitive) && - (input.cyclomatic === null || input.cyclomatic <= envelope.cyclomatic) && - (input.nesting === null || input.nesting <= envelope.nesting) && - (input.affected === null || input.affected <= envelope.affected) && - (input.processes === null || input.processes <= envelope.processes) && - input.moduleRoots <= envelope.roots - ) - return envelope.tier; - } - return "extreme"; + return taskTiers(input).tier; } function surface( task: WorkItem, - evidence?: Evidence, + evidence: Evidence | undefined, + request: RoutingRequestSignals, ): "ui" | "backend" | "verification" { - if (task.kind === "test") return "verification"; + if ( + task.kind === "test" || + (request.kinds.length === 1 && request.kinds[0] === "test") + ) + return "verification"; const paths = [ ...(task.scope ?? []), ...(evidence?.symbols.map((s) => s.file) ?? []), @@ -140,166 +206,395 @@ function preferredHarness( return tier === "balanced" ? "codex" : "claude"; } -export function assignedHarness(task: WorkItem, settings: Settings): Harness | undefined { +const storyAssignment = (task: WorkItem) => + task.assignment !== "auto" || !!task.modelOverride; + +export function assignedHarness( + task: WorkItem, + settings: Settings, +): Harness | undefined { + if (storyAssignment(task)) return task.harness; if (settings.localModel) return "codex"; - if (settings.model && !task.modelOverride) return settings.defaultHarness; - if (task.assignment !== "auto" || task.modelOverride) return task.harness; + if (settings.model) return settings.defaultHarness; } -export function planRoute( - task: WorkItem, - evidence: Evidence | undefined, +function explicitModel(task: WorkItem, settings: Settings, local: boolean) { + if (task.modelOverride) return task.modelOverride; + if (local || !storyAssignment(task)) return settings.model || undefined; +} + +type Configuration = { + runtime: HarnessRuntime; + model: ModelOption; + effort: ReasoningEffort; + effortBound: boolean; +}; + +function supportedEfforts(model: ModelOption, tier: ModelTier) { + const advertised = effortOrder.filter((level) => + model.efforts?.includes(level), + ); + return advertised.length ? advertised : [effort[tier]]; +} + +function configurations( + runtime: HarnessRuntime, + model: ModelOption, + tier: ModelTier, +): Configuration[] { + return supportedEfforts(model, tier).map((level) => ({ + runtime, + model, + effort: level, + effortBound: + runtime.id !== "dsh" && + (runtime.id !== "cursor" || !!model.efforts?.includes(level)) && + ![codexDefaultModel, cursorDefaultModel, "default"].includes(model.id), + })); +} + +function matchExplicitModel( + runtime: HarnessRuntime, + model: string, + local: boolean, +): ModelOption { + if (local) return { id: model, label: model, source: "alias" }; + const id = runtime.id; + if (id === "codex" && model === codexDefaultModel) + return { id: model, label: model, source: "cli" }; + const selected = + id === "codex" + ? selectCodexModel(runtime, model, false) + : id === "claude" + ? selectClaudeModel(runtime.models, model, true) + : id === "cursor" + ? cursorCatalogValue(model, runtime.models) + : model; + const offered = runtime.models.find( + (option) => option.id === selected || option.resolvedId === selected, + ); + if (offered && selected) return { ...offered, id: selected }; + throw Error( + id === "cursor" + ? `Cursor no longer offers ${model}. Choose Match task complexity or another model in Worker assignment or Settings.` + : `${runtime.name} does not advertise ${model}. Refresh Workers and choose an available model.`, + ); +} + +function defaults(runtime: HarnessRuntime): ModelOption[] { + const advertised = runtime.models.filter((model) => model.isDefault); + if (advertised.length) return advertised; + if (runtime.id === "codex") + return [{ id: codexDefaultModel, label: codexDefaultModel, source: "cli" }]; + if (runtime.id === "claude") + return [{ id: "default", label: "Claude default", source: "cli" }]; + if (runtime.id === "cursor") + return [ + { id: cursorDefaultModel, label: cursorDefaultModel, source: "acp" }, + ]; + return []; +} + +function fingerprint( runtimes: HarnessRuntime[], + task: WorkItem, settings: Settings, -): RouteDecision { - const inputs = routingInputs(evidence); - const tier = qualifyTier(inputs); +) { + const catalog = runtimes + .map((runtime) => [ + runtime.id, + effectivePermissionMode(task, settings, runtime.id), + !!runtime.allModelsDenied, + runtime.models + .map((model) => [ + model.id, + model.resolvedId, + model.tier, + !!model.isDefault, + model.source, + [...new Set(model.efforts)].sort(compareText), + ]) + .sort((a, b) => compareText(JSON.stringify(a), JSON.stringify(b))), + ]) + .sort((a, b) => compareText(JSON.stringify(a), JSON.stringify(b))); + return createHash("sha256").update(JSON.stringify(catalog)).digest("hex"); +} + +function describeInputs(inputs: RouteDecision["inputs"]): string[] { const reasons: string[] = []; + const request = inputs.request; + if (request) { + const kinds = request.kinds.filter((kind) => kind !== "unknown"); + if (kinds.length) reasons.push(`Request intent · ${kinds.join(", ")}.`); + if (request.fileScopeOnly) + reasons.push("The brief limits edits to its named scope."); + if (request.preserveBehavior) + reasons.push("The brief asks to preserve behavior."); + if (request.publicContract === "change") + reasons.push( + "A requested public contract change raises the impact tier.", + ); + if (request.publicContract === "preserve") + reasons.push("The brief asks to preserve the public contract."); + } + if (inputs.scope) { + const { confirmedTargets, inferredTargets, unresolvedReferences } = + inputs.scope; + reasons.push( + `Source targets · ${confirmedTargets} confirmed, ${inferredTargets} inferred, ${unresolvedReferences} unresolved.`, + ); + } if (inputs.cognitive !== null) reasons.push( - `AST cognitive ${inputs.cognitive}; cyclomatic ${inputs.cyclomatic ?? "unknown"}; maximum nesting ${inputs.nesting ?? "unknown"}.`, + `AST maxima · cognitive ${inputs.cognitive}, cyclomatic ${inputs.cyclomatic ?? "unknown"}, nesting ${inputs.nesting ?? "unknown"}.`, ); - if (inputs.affected !== null) + if (request?.readOnly) reasons.push( - `${inputs.affected}${inputs.incomplete ? "+" : ""} observed affected symbols; ${inputs.processes ?? "unknown"} affected processes.`, + "This request is read-only. Source complexity informs the route.", + ); + else if (inputs.impact) { + const impact = inputs.impact; + const count = (unit: string, value?: number) => { + const amount = + value === undefined + ? "unknown" + : `${value}${impact.incomplete ? "+" : ""}`; + return `${amount} ${unit}${value === 1 && !impact.incomplete ? "" : "s"}`; + }; + reasons.push( + `Observed impact across ${impact.observedTargets} of ${impact.targetCount} ${impact.basis} targets · ${count("symbol", impact.affectedSymbols)}, ${count("file", impact.affectedFiles)}, ${count("flow", impact.affectedProcesses)}.`, + ); + } else if (inputs.affected !== null) + reasons.push( + `${inputs.affected}${inputs.incomplete ? "+" : ""} observed affected symbols, ${inputs.processes ?? "unknown"} affected processes.`, ); if (inputs.incomplete) reasons.push( - "Evidence is incomplete. Missing values remain unknown; the fast tier is ineligible.", + "Evidence is partial. Missing values remain unknown and the fast tier is ineligible.", ); - const pinnedModel = task.modelOverride || settings.model; - if (settings.localModel && !pinnedModel) - throw new Error( + return reasons; +} + +export function planRoute( + task: WorkItem, + evidence: Evidence | undefined, + runtimes: HarnessRuntime[], + settings: Settings, + calibration?: RoutingCalibration, +): RouteDecision { + const request = analyzeRoutingIntent(task).signals; + const inputs = routingInputs(evidence, request); + const { tier, workTier, impactTier, complete } = taskTiers(inputs); + const reasons = describeInputs(inputs); + const requested = assignedHarness(task, settings); + const local = requested === "codex" && settings.localModel; + const pinned = explicitModel(task, settings, local); + if (local && !pinned?.trim()) + throw Error( "Enter an installed Ollama model name in Settings before enabling local-model routing.", ); - const requested = assignedHarness(task, settings); - const manual = requested !== undefined; - const wanted = requested ?? preferredHarness(tier, surface(task, evidence)); - const permissionMode = task.permissionMode; - if (permissionMode === "auto") + + const permissionSupported = (id: Harness) => + supportsPermissionMode(id, effectivePermissionMode(task, settings, id)); + if (requested && !permissionSupported(requested)) + throw Error( + "The assigned ACP connection does not support Smart auto. Choose Review or Full access, or select Codex or Claude Code.", + ); + const approved = runtimes.filter( + (runtime) => + runtime.available && !!runtime.path && permissionSupported(runtime.id), + ); + const eligible = approved.filter( + (runtime) => !requested || requested === runtime.id, + ); + const pickedRuntime = requested + ? eligible.find((runtime) => runtime.id === requested) + : undefined; + if (pickedRuntime?.allModelsDenied && !local) + throw Error( + `${pickedRuntime.name} rejected every model advertised for this account. Refresh Workers or choose another harness.`, + ); + + const wanted = preferredHarness(tier, surface(task, evidence, request)); + const harnessRank = (id: Harness) => + id === wanted + ? -2 + : id === settings.defaultHarness + ? -1 + : harnessIds.indexOf(id); + const desired = effortOrder.indexOf(effort[tier]); + const effortDistance = (level: ReasoningEffort) => { + const delta = effortOrder.indexOf(level) - desired; + return delta >= 0 ? delta : effortOrder.length - delta; + }; + const effortFit = (option: Configuration) => + option.effortBound ? effortDistance(option.effort) : 0; + const compare = (a: Configuration, b: Configuration) => + effortFit(a) - effortFit(b) || + harnessRank(a.runtime.id) - harnessRank(b.runtime.id) || + Number(!!b.model.isDefault) - Number(!!a.model.isDefault) || + compareText(a.model.id, b.model.id); + + const active = eligible.filter( + (runtime) => !runtime.allModelsDenied || local, + ); + const advertised = active.flatMap((runtime) => + runtime.models.flatMap((model) => configurations(runtime, model, tier)), + ); + const ranked = advertised.filter(({ model }) => !!model.tier); + const provisioned = active.flatMap((runtime) => + defaults(runtime).flatMap((model) => configurations(runtime, model, tier)), + ); + const matches = ranked + .filter(({ model }) => rank(model.tier) >= rank(tier)) + .sort((a, b) => rank(a.model.tier) - rank(b.model.tier) || compare(a, b)); + const below = ranked + .filter(({ model }) => rank(model.tier) < rank(tier)) + .sort((a, b) => rank(b.model.tier) - rank(a.model.tier) || compare(a, b)); + const byPolicy = matches[0] ?? below[0] ?? provisioned.sort(compare)[0]; + const explicit = + pinned && pickedRuntime + ? configurations( + pickedRuntime, + matchExplicitModel(pickedRuntime, pinned, local), + tier, + ).sort(compare)[0] + : undefined; + + // A calibrated route requires model-specific effort and a provider that can + // confirm the selected configuration before the first prompt. + const calibratedOptions = + calibration && !pinned && !local + ? advertised + .filter( + ({ runtime, model, effort, effortBound }) => + effortBound && + model.efforts?.includes(effort) && + (runtime.id === "codex" || + runtime.id === "claude" || + runtime.id === "cursor"), + ) + .map((option) => { + const { runtime, model, effort } = option; + const cursorVariant = + runtime.id === "cursor" && model.id.includes("[") + ? model.id.split("[", 1)[0] + : undefined; + return { + option, + candidate: { + harness: runtime.id, + model: model.id, + effort, + resolvedModel: model.resolvedId ?? cursorVariant, + }, + }; + }) + : []; + const candidates = calibratedOptions.map((row) => row.candidate); + const kinds = request.kinds.filter((kind) => kind !== "unknown"); + const cohort = { + kind: kinds.length > 1 ? "mixed" : (kinds[0] ?? "unknown"), + tier, + coverage: complete ? ("measured" as const) : ("partial" as const), + }; + const target = reliabilityTarget[tier]; + const estimate = + calibration && candidates.length + ? selectCalibratedCandidate( + estimateRoutingCandidates(calibration, cohort, candidates), + candidates, + target, + ) + : undefined; + const calibrated = estimate + ? calibratedOptions.find( + ({ candidate }) => + candidate.harness === estimate.candidate.harness && + candidate.model === estimate.candidate.model && + candidate.resolvedModel === estimate.candidate.resolvedModel && + candidate.effort === estimate.candidate.effort, + )?.option + : undefined; + const selected = explicit ?? calibrated ?? byPolicy; + if (!selected) + throw Error( + task.permissionMode === "auto" && !approved.length + ? "No connected harness supports Smart auto. Connect Codex or Claude Code, or choose Review or Full access." + : requested + ? `The assigned worker is not connected or has no model for the ${tier} envelope. Connect it in Workers, choose Automatic, or choose an available model.` + : "No eligible connected worker has a discovered model for this task. Connect a worker in Workers, then refresh its model catalog.", + ); + + const { runtime, model, effort: level, effortBound } = selected; + const method = explicit + ? "explicit" + : calibrated + ? "calibration" + : matches.length + ? "envelope" + : "fallback"; + if (explicit) reasons.push( - "Smart auto requires a harness with native automatic approval review; unsupported transports are excluded.", + local + ? "The configured Ollama model runs locally through Codex." + : task.modelOverride + ? "The story’s model override takes precedence." + : "The workspace model override applies to this automatic story.", ); - if ( - manual && - !supportsPermissionMode( - requested, - effectivePermissionMode(task, settings, requested), - ) - ) - throw new Error( - "The assigned ACP connection does not support Smart auto. Choose Review or Full access, or select Codex or Claude Code.", + else if (requested && storyAssignment(task)) + reasons.push(`The story’s assignment limits routing to ${runtime.name}.`); + if (calibrated && estimate) + reasons.push( + `Controlled trials met the ${Math.round(target * 100)}% reliability target for this cohort. ${estimate.samples} matched outcomes across ${estimate.repositories} repositories.`, ); - const ranked = [ - wanted, - ...(["codex", "claude", "cursor", "copilot", "dsh"] as Harness[]).filter( - (id) => id !== wanted, - ), - ]; - for (const id of ranked) { - if (manual && id !== requested) continue; - const candidateMode = effectivePermissionMode(task, settings, id); - if (!supportsPermissionMode(id, candidateMode)) continue; - const runtime = runtimes.find((r) => r.id === id && r.available); - if (!runtime) continue; - if (pinnedModel) { - const cursorCatalog = id === "cursor"; - const selectedId = id === "codex" && !settings.localModel - ? selectCodexModel(runtime, pinnedModel, false) - : id === "claude" ? selectClaudeModel(runtime.models, pinnedModel, true) - : cursorCatalog ? cursorCatalogValue(pinnedModel, runtime.models) : pinnedModel; - if ((id === "copilot" || id === "dsh") && !runtime.models.some(model => model.id === selectedId)) - throw Error(`${runtime.name} does not advertise ${pinnedModel}. Refresh Workers and choose an available model.`); - if (!selectedId) - throw Error(`Cursor no longer offers ${pinnedModel}. Choose Match task complexity or another model in ${task.modelOverride ? "Worker assignment" : "Settings"}.`); - const supportedEffort = cursorCatalog ? runtime.models.find((model) => model.id === selectedId)?.efforts?.[0] : undefined; - reasons.push( - settings.localModel - ? "Explicit local-model override; capability is not inferred from its name." - : "Explicit model override takes precedence over automatic selection.", - ); - return { - policyVersion: "memcode-envelope-v2", - tier, - harness: id, - model: selectedId, - modelLabel: runtime.models.find(model => model.id === selectedId || model.resolvedId === selectedId)?.label, - effort: (["low","medium","high","xhigh"].includes(supportedEffort ?? "") ? supportedEffort : effort[tier]) as ReasoningEffort, - mode: "manual", - status: "provisional", - inputs, - reasons, - plannedAt: new Date().toISOString(), - }; - } - const candidates = runtime.models - .filter( - (model) => model.tier && tierOrder.indexOf(model.tier) >= tierOrder.indexOf(tier), - ) - .sort((a, b) => - tierOrder.indexOf(a.tier!) - tierOrder.indexOf(b.tier!) || - Number(!!b.isDefault) - Number(!!a.isDefault) || - (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), - ); - let model = candidates[0]; - if (id === "codex" && !model) { - if (runtime.allModelsDenied && !manual) continue; - const selected = selectCodexModel(runtime, "", true, tier); - model = runtime.models.find(m => m.id === selected) ?? { id: codexDefaultModel, label: codexDefaultModel, source: "cli" }; - reasons.push(selected ? "The measured tier is unavailable on this account. Codex will use an available model." : "The model catalog is unavailable. Codex will use its configured account default."); - } - if (id === "claude" && !model) { - model = runtime.models.find(option => option.isDefault) ?? { id: "default", label: "Claude default", source: "cli" }; - reasons.push("Claude Code will use its configured default for this account."); - } - if (id === "cursor" && !model) { - model = { id: cursorDefaultModel, label: cursorDefaultModel, source: "acp" }; - reasons.push("Cursor will use the current session’s configured model."); - } - if ((id === "copilot" || id === "dsh") && !model) { - // New providers are uncalibrated. Use only their advertised default and - // label it provisional, rather than infer capability from a model name. - model = runtime.models.find(option => option.isDefault)!; - if (model) reasons.push(`${runtime.name}'s advertised default is available; model capability is not yet calibrated against the measured envelope.`); - } - if (!model) continue; - const desired = effort[tier]; - const level = - model.efforts && !model.efforts.includes(desired) - ? ((["xhigh", "high", "medium", "low"] as ReasoningEffort[]).find((e) => - model.efforts!.includes(e), - ) ?? "medium") - : desired; + else if (method === "envelope") reasons.push( - `${manual ? "The assigned harness" : id === wanted ? `The ${surface(task, evidence)} policy` : "The eligible-harness fallback"} selects ${runtime.name} / ${model.id} at ${level} effort.`, + `The ${tier} envelope was compared across the eligible catalog.`, ); - return { - policyVersion: "memcode-envelope-v2", - tier, - harness: id, - model: model.id, - modelLabel: model.label, - effort: level, - mode: manual ? "manual" : "automatic", - status: inputs.incomplete || !candidates.length ? "provisional" : "measured", - inputs, - reasons, - plannedAt: new Date().toISOString(), - }; - } - throw new Error( - permissionMode === "auto" && - !runtimes.some( - (r) => - r.available && - supportsPermissionMode( - r.id, - effectivePermissionMode(task, settings, r.id), - ), - ) - ? "No connected harness supports Smart auto. Connect Codex or Claude Code, or choose Review or Full access." - : manual - ? `The assigned worker is not connected or has no model for the ${tier} envelope. Connect it in Workers, choose Automatic, or choose an available model.` - : "No eligible connected worker has a discovered model for this task. Connect a worker in Workers, then refresh its model catalog.", + else if (method === "fallback") + reasons.push( + `The eligible catalog has no ranked model that meets the ${tier} envelope. This is a provisional fallback.`, + ); + reasons.push( + `${runtime.name} / ${model.label}${effortBound ? ` at ${level} effort` : " with provider-configured effort"}.`, ); + return { + policyVersion: "memcode-evidence-v3", + tier, + harness: runtime.id, + model: model.id, + modelLabel: model.label, + effort: level, + ...(local ? { localModel: true as const } : {}), + mode: requested ? "manual" : "automatic", + status: + !complete || method === "explicit" || method === "fallback" + ? "provisional" + : "measured", + inputs, + reasons, + plannedAt: new Date().toISOString(), + selection: { + method, + catalogFingerprint: fingerprint(eligible, task, settings), + eligibleConfigurations: explicit + ? 1 + : new Set( + [...advertised, ...provisioned].map(({ runtime, model, effort }) => + JSON.stringify([runtime.id, model.id, effort]), + ), + ).size, + effortBound, + workTier, + impactTier, + ...(calibrated && calibration && estimate + ? { + calibrationDigest: calibration.digest, + calibratedModel: + estimate.candidate.resolvedModel ?? estimate.candidate.model, + } + : {}), + }, + }; } diff --git a/runtime/routing-calibration.ts b/runtime/routing-calibration.ts new file mode 100644 index 0000000..4a831e8 --- /dev/null +++ b/runtime/routing-calibration.ts @@ -0,0 +1,419 @@ +import { createHash } from "node:crypto"; +import { z } from "zod"; +import { harnessIds } from "../src/shared"; + +const modelId = z + .string() + .min(1) + .max(200) + .refine((value) => value === value.trim()); +const effort = z.enum(["low", "medium", "high", "xhigh"]); +const candidateSchema = z.strictObject({ + harness: z.enum(harnessIds), + model: modelId, + effort, + resolvedModel: modelId.optional(), +}); +const cohortSchema = z.strictObject({ + kind: z.string().regex(/^[a-z][a-z0-9_-]{0,39}$/), + tier: z.enum(["fast", "balanced", "frontier", "extreme"]), + coverage: z.enum(["measured", "partial"]), +}); +const nonnegative = z.int().nonnegative(); +const estimateSchema = z.strictObject({ + candidate: candidateSchema, + samples: nonnegative, + repositories: nonnegative, + accepted: nonnegative, + unresolved: nonnegative, + lowerBound: z.number().min(0).max(1), + meanTotalCostMicros: z + .number() + .nonnegative() + .max(Number.MAX_SAFE_INTEGER) + .nullable(), +}); +const profileSchema = z.strictObject({ + version: z.literal("memcode-controlled-routing-v1"), + cohorts: z.array( + z.strictObject({ + cohort: cohortSchema, + estimates: z.array(estimateSchema).min(1), + }), + ), +}); +const calibrationSchema = profileSchema.extend({ + digest: z.string().regex(/^[a-f0-9]{64}$/), +}); + +export type RoutingCandidate = z.infer; +export type RoutingCohort = z.infer; +export type RoutingEstimate = z.infer; +export type RoutingCalibration = z.infer; + +const frozenStory = { + repoId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), + storyId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), + revision: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/), +}; +const check = z.enum(["passed", "failed", "unverified"]); +const outcomeSchema = z.strictObject({ + ...frozenStory, + cohort: cohortSchema, + candidate: candidateSchema, + observedModel: modelId.nullable(), + observedEffort: effort.nullable(), + execution: z.enum(["completed", "failed", "running"]), + checks: check, + blindReview: check, + acceptance: z.enum(["accepted", "rejected", "pending"]), + totalCostMicros: nonnegative.nullable(), + totalTokens: nonnegative.nullable(), + totalDurationMs: nonnegative.nullable(), +}); +export type RoutingOutcome = z.infer; +export const routingEvaluationPolicies = [ + "current", + "wording", + "graph", + "combined", +] as const; +const policySchema = z.strictObject({ + ...frozenStory, + routes: z.record( + z.enum(routingEvaluationPolicies), + candidateSchema.nullable(), + ), +}); +export const routingEvaluationSchema = z.strictObject({ + version: z.literal(1), + heldOutRepoIds: z.array(frozenStory.repoId).min(1), + outcomes: z.array(outcomeSchema), + decisions: z.array(policySchema), +}); +export type RoutingEvaluation = z.infer; + +const cohortKey = ({ kind, tier, coverage }: RoutingCohort) => + JSON.stringify([kind, tier, coverage]); +const candidateKey = ({ + harness, + model, + effort, + resolvedModel, +}: RoutingCandidate) => + JSON.stringify([harness, model, effort, resolvedModel ?? null]); +const storyKey = ({ + repoId, + storyId, + revision, +}: Pick) => + JSON.stringify([repoId, storyId, revision]); +const compare = (left: string, right: string) => + left < right ? -1 : left > right ? 1 : 0; +const digest = (profile: z.infer) => + createHash("sha256").update(JSON.stringify(profile)).digest("hex"); +const knownAlias = + /^(?:.*[ -])?(?:auto|default|latest|haiku|sonnet|opus|fable)(?:\[.*\])?$/i; +function concreteModel(candidate: RoutingCandidate): string | undefined { + const model = candidate.resolvedModel ?? candidate.model; + // A family or an opaque, undated ID needs explicit provider resolution. + if ( + !knownAlias.test(model) && + (candidate.resolvedModel || /\d/.test(model.split("[")[0])) + ) + return model; +} + +function firstPass( + run: RoutingOutcome, +): "accepted" | "rejected" | "unresolved" { + const model = concreteModel(run.candidate); + if ( + run.execution === "failed" || + run.checks === "failed" || + run.blindReview === "failed" || + run.acceptance === "rejected" || + (model && run.observedModel && run.observedModel !== model) || + (run.observedEffort && run.observedEffort !== run.candidate.effort) + ) + return "rejected"; + if ( + run.execution === "completed" && + model && + run.observedModel === model && + run.observedEffort === run.candidate.effort && + run.checks === "passed" && + run.blindReview === "passed" && + run.acceptance === "accepted" + ) + return "accepted"; + return "unresolved"; +} + +function mean(values: number[]): number | null { + if (!values.length) return null; + return values.reduce( + (average, value, index) => average + (value - average) / (index + 1), + 0, + ); +} + +function indexOutcomes(outcomes: readonly RoutingOutcome[]) { + const stories = new Map>(); + const frozen = new Map(); + for (const run of outcomes) { + const story = storyKey(run); + const identity = JSON.stringify([run.repoId, run.storyId]); + const previous = frozen.get(identity); + if ( + previous && + (previous.revision !== run.revision || + previous.cohort !== cohortKey(run.cohort)) + ) + throw Error( + "Comparisons require one frozen revision and cohort per story.", + ); + frozen.set(identity, { + revision: run.revision, + cohort: cohortKey(run.cohort), + }); + const candidates = stories.get(story) ?? new Map(); + const candidate = candidateKey(run.candidate); + if (candidates.has(candidate)) + throw Error( + "Duplicate first-pass outcome for a story and configuration.", + ); + candidates.set(candidate, run); + stories.set(story, candidates); + } + return stories; +} + +function estimate( + runs: RoutingOutcome[], + comparisons: number, +): RoutingEstimate { + const repositories = new Map(); + for (const run of runs) { + const rows = repositories.get(run.repoId) ?? []; + rows.push(run); + repositories.set(run.repoId, rows); + } + const repoSuccess = mean( + [...repositories.values()].map( + (rows) => + rows.filter((row) => firstPass(row) === "accepted").length / + rows.length, + ), + )!; + const repoCosts = [...repositories.values()].map((rows) => + rows.every((row) => row.totalCostMicros !== null) + ? mean(rows.map((row) => row.totalCostMicros!)) + : null, + ); + // Count each repository once. Separate stories in one codebase can share + // their failure modes. Pending outcomes contribute zero to the floor. + const margin = Math.sqrt( + Math.log(comparisons / 0.05) / (2 * repositories.size), + ); + return { + candidate: runs[0].candidate, + samples: runs.length, + repositories: repositories.size, + accepted: runs.filter((row) => firstPass(row) === "accepted").length, + unresolved: runs.filter((row) => firstPass(row) === "unresolved").length, + lowerBound: Math.max(0, repoSuccess - margin), + meanTotalCostMicros: repoCosts.every((cost) => cost !== null) + ? mean(repoCosts as number[]) + : null, + }; +} + +export function compileRoutingCalibration( + outcomes: readonly RoutingOutcome[], + heldOutRepoIds: readonly string[], +): RoutingCalibration { + if (!heldOutRepoIds.length) + throw Error("Reserve whole repositories before calibrating the router."); + const heldOut = new Set(heldOutRepoIds); + const stories = indexOutcomes( + outcomes.filter((run) => !heldOut.has(run.repoId)), + ); + const groups = new Map[]>(); + for (const [, story] of [...stories].sort(([a], [b]) => compare(a, b))) { + const key = cohortKey(story.values().next().value!.cohort); + const items = groups.get(key) ?? []; + items.push(story); + groups.set(key, items); + } + const cohorts: RoutingCalibration["cohorts"] = []; + for (const [, group] of [...groups].sort(([a], [b]) => compare(a, b))) { + const candidates = new Set( + group.flatMap((story) => + [...story.values()] + .filter((row) => concreteModel(row.candidate)) + .map((row) => candidateKey(row.candidate)), + ), + ); + const keys = [...candidates].sort(compare); + if (!keys.length) continue; + const matched = group.filter((story) => + keys.every((key) => story.has(key)), + ); + if (!matched.length) continue; + const cohort = matched[0].get(keys[0])!.cohort; + cohorts.push({ + cohort, + estimates: keys.map((key) => + estimate( + matched.map((story) => story.get(key)!), + keys.length, + ), + ), + }); + } + const profile = profileSchema.parse({ + version: "memcode-controlled-routing-v1", + cohorts, + }); + return { ...profile, digest: digest(profile) }; +} + +export function loadRoutingCalibration( + value: unknown, +): RoutingCalibration | undefined { + const parsed = calibrationSchema.safeParse(value); + if (!parsed.success) return; + const profile = profileSchema.parse({ + version: parsed.data.version, + cohorts: parsed.data.cohorts, + }); + if ( + digest(profile) !== parsed.data.digest || + new Set(profile.cohorts.map((row) => cohortKey(row.cohort))).size !== + profile.cohorts.length + ) + return; + for (const { estimates } of profile.cohorts) { + if ( + new Set(estimates.map((row) => candidateKey(row.candidate))).size !== + estimates.length || + estimates.some( + (row) => + !concreteModel(row.candidate) || + row.repositories === 0 || + row.repositories > row.samples || + row.accepted + row.unresolved > row.samples || + row.lowerBound > + Math.max( + 0, + 1 - + Math.sqrt( + Math.log(estimates.length / 0.05) / (2 * row.repositories), + ), + ), + ) + ) + return; + } + return parsed.data; +} + +export function estimateRoutingCandidates( + calibration: RoutingCalibration, + cohort: RoutingCohort, + eligible: readonly RoutingCandidate[], +): RoutingEstimate[] { + const keys = new Set(eligible.map(candidateKey)); + return ( + calibration.cohorts + .find((row) => cohortKey(row.cohort) === cohortKey(cohort)) + ?.estimates.filter((row) => keys.has(candidateKey(row.candidate))) ?? [] + ); +} + +export function selectCalibratedCandidate( + estimates: readonly RoutingEstimate[], + eligible: readonly RoutingCandidate[], + reliabilityTarget: number, +): RoutingEstimate | undefined { + if ( + !Number.isFinite(reliabilityTarget) || + reliabilityTarget <= 0 || + reliabilityTarget > 1 + ) + return; + const keys = new Set(eligible.map(candidateKey)); + return estimates + .filter( + (row) => + keys.has(candidateKey(row.candidate)) && + concreteModel(row.candidate) && + row.samples >= 30 && + row.repositories >= 8 && + row.lowerBound >= reliabilityTarget && + row.meanTotalCostMicros !== null && + Number.isFinite(row.meanTotalCostMicros) && + row.meanTotalCostMicros >= 0, + ) + .sort( + (a, b) => + a.meanTotalCostMicros! - b.meanTotalCostMicros! || + b.lowerBound - a.lowerBound || + compare(candidateKey(a.candidate), candidateKey(b.candidate)), + )[0]; +} + +export function evaluateRouting(input: RoutingEvaluation) { + const outcomes = indexOutcomes(input.outcomes); + const heldOut = new Set(input.heldOutRepoIds); + const decisions = input.decisions + .filter((decision) => heldOut.has(decision.repoId)) + .sort((a, b) => compare(storyKey(a), storyKey(b))); + if (new Set(decisions.map(storyKey)).size !== decisions.length) + throw Error("Duplicate held-out policy decision for one frozen story."); + const selected = decisions.map((decision) => + routingEvaluationPolicies.map((policy) => { + const candidate = decision.routes[policy]; + return candidate + ? outcomes.get(storyKey(decision))?.get(candidateKey(candidate)) + : undefined; + }), + ); + const paired = selected.filter((row): row is RoutingOutcome[] => + row.every((run) => run !== undefined), + ); + const pairedMetric = ( + field: "totalCostMicros" | "totalTokens" | "totalDurationMs", + index: number, + ) => { + const values = paired + .filter((row) => row.every((run) => run[field] !== null)) + .map((row) => row[index][field]!); + return { samples: values.length, mean: mean(values) }; + }; + return { + heldOutRepositories: heldOut.size, + heldOutStories: decisions.length, + pairedStories: paired.length, + policies: routingEvaluationPolicies.map((policy, index) => { + const runs = paired.map((row) => row[index]); + const status = runs.map(firstPass); + return { + policy, + observedStories: selected.filter((row) => row[index] !== undefined) + .length, + accepted: status.filter((value) => value === "accepted").length, + rejected: status.filter((value) => value === "rejected").length, + unresolved: status.filter((value) => value === "unresolved").length, + costMicros: pairedMetric("totalCostMicros", index), + tokens: pairedMetric("totalTokens", index), + durationMs: pairedMetric("totalDurationMs", index), + }; + }), + calibration: compileRoutingCalibration( + input.outcomes, + input.heldOutRepoIds, + ), + }; +} diff --git a/runtime/routing-intent.ts b/runtime/routing-intent.ts new file mode 100644 index 0000000..46547de --- /dev/null +++ b/runtime/routing-intent.ts @@ -0,0 +1,267 @@ +import type { WorkItem } from "../src/shared"; +import type { + RoutingRequestKind, + RoutingRequestSignals, +} from "../src/routing-signals"; + +interface PathReference { + file: string; + line?: number; + column?: number; +} + +export interface RoutingIntentAnalysis { + signals: RoutingRequestSignals; + references: { + paths: PathReference[]; + symbols: string[]; + errors: string[]; + }; + searchQuery: string; +} + +const extensions = + "tsx?|m[tc]s|cts|jsx?|[cm]js|rs|pyi?|go|java|kt|kts|cs|cpp|cxx|cc|c|hpp|h|rb|php|swift|scala|vue|svelte|html?|css|scss|sass|less|mdx?|txt|rst|asciidoc|jsonc?|jsonl|ya?ml|toml|ini|cfg|conf|xml|sql|graphql|proto|sh|bash|ps1|bat|cmd|lock|gitignore|env"; +const fileName = String.raw`(?:[\w.@+-]+\.(?:${extensions})|Dockerfile|Makefile|Gemfile|Rakefile|\.gitignore|\.env)`; +const location = String.raw`(?::([1-9]\d{0,7})(?::([1-9]\d{0,7}))?|#L([1-9]\d{0,7}))?`; +const boundedPath = new RegExp( + String.raw`(? = [ + [ + "explain", + /^(?:explain|describe|summarize|understand|tell me|walk me through|what|which|how|why|where|when|who)\b/i, + ], + [ + "research", + /^(?:research|investigate|diagnose|compare|evaluate|review|inspect|look (?:up|into|at)|check|find out|trace|audit)\b/i, + ], + [ + "test", + /^(?:(?:test|benchmark|verify|validate)\b|(?:run|write|add|update|expand|repeat)\b[^.;!?\n]{0,45}\b(?:tests?|benchmarks?|checks?|regressions?)\b)/i, + ], + ["fix", /^(?:fix|resolve|repair|correct|patch|prevent)\b/i], + [ + "refactor", + /^(?:refactor|extract|simplify|split|consolidate|restructure|deduplicate|reduce (?:code |the )?complexity)\b/i, + ], + ["rename", /^rename\b/i], + [ + "implement", + /^(?:implement|add|build|change|create|edit|introduce|enable|disable|support|update|remove|replace|modify|make|allow|wire|integrate|move)\b/i, + ], +]; +const requestPrefix = + /^(?:(?:and|also|then|next|also please|please|(?:can|could|would|will|should) (?:you|we)|(?:I|we|you) (?:want|need|have|would like)(?: you)? to|(?:I|we) (?:want|need) (?:it|this) to|I['’]d like (?:you )?to|help me|just|only|be able to)\s+)+/i; +const requestSeparator = + /(?:[.;!?](?=\s|$)|[\n\r]|\s+(?:but|then|and then|also|and|or)\s+)/i; +const negative = + /\b(?:do not|don['’]t|never|without|avoid|must not|should not|can['’]t|cannot|won['’]t)\s+[^.!?;\n]*?(?=[.!?;\n]|\s+(?:but|then|instead)\b|$)/gi; +const fallbackKind = { + feature: "implement", + fix: "fix", + refactor: "refactor", + research: "research", + test: "test", +} as const; + +function unique(items: T[], key: (item: T) => string, limit: number): T[] { + const seen = new Set(); + return items + .filter((item) => { + const value = key(item); + if (seen.has(value)) return false; + seen.add(value); + return true; + }) + .slice(0, limit); +} + +function pathReference( + file: string, + line?: string, + column?: string, +): PathReference | undefined { + const normalized = file.replaceAll("\\", "/").replace(/^\.\//, ""); + if ( + normalized.length > 512 || + normalized.split("/").some((part) => part === ".." || part === ".") + ) + return; + return { + file: normalized, + ...(line ? { line: Number(line) } : {}), + ...(column ? { column: Number(column) } : {}), + }; +} + +function parseReferences(text: string) { + const paths: PathReference[] = []; + const symbols: string[] = []; + const errors: string[] = []; + const addPath = (file: string, line?: string, column?: string) => { + const reference = pathReference(file, line, column); + if (reference) paths.push(reference); + }; + const addSymbol = (symbol: string) => { + if (symbol.length <= 160 && !notSymbols.test(symbol)) symbols.push(symbol); + }; + const unquoted = text.replace( + quotedText, + ( + match: string, + tick, + double, + single, + curvedDouble, + curvedSingle, + offset: number, + ) => { + const literal = String( + tick ?? double ?? single ?? curvedDouble ?? curvedSingle, + ).trim(); + const path = quotedPath.exec(literal); + if (path) { + addPath(path[1], path[2] ?? path[4], path[3]); + return " FILE_REFERENCE "; + } + const symbol = quotedSymbol.exec(literal); + const codes = [...literal.matchAll(errorCode)]; + if ( + errorCue.test(text.slice(Math.max(0, offset - 45), offset)) || + errorText.test(literal) || + codes.length + ) { + if (literal.length >= 3 && literal.length <= 240) errors.push(literal); + } else if (symbol && (tick || /[.:(]/.test(literal))) + addSymbol(symbol[1]); + return " ".repeat(match.length); + }, + ); + const prose = unquoted.replace( + boundedPath, + (match: string, line, column, anchorLine) => { + const file = match.replace( + /(?::[1-9]\d{0,7}(?::[1-9]\d{0,7})?|#L[1-9]\d{0,7})$/i, + "", + ); + addPath(file, line ?? anchorLine, column); + return " FILE_REFERENCE "; + }, + ); + for (const match of prose.matchAll(plainSymbol)) + addSymbol(match[1] ?? match[2]); + for (const match of prose.matchAll(errorCode)) errors.push(match[0]); + for (const match of prose.matchAll( + /\b(?:[\w.]+Error|Error|Exception|panic)\s*:\s*([^\r\n]{3,240})/gi, + )) { + const error = match[0].trim(); + if (error.length <= 240 && !error.includes("FILE_REFERENCE")) + errors.push(error); + } + return { + paths: unique( + paths, + ({ file, line, column }) => `${file}:${line ?? ""}:${column ?? ""}`, + 8, + ), + symbols: unique(symbols, (symbol) => symbol, 12), + errors: unique(errors, (error) => error, 6), + prose, + }; +} + +export function analyzeRoutingIntent( + task: Pick, +): RoutingIntentAnalysis { + const text = `${task.title.slice(0, 500)}\n${task.description.slice(0, 6000)}` + .replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)/g, " ") + .replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s)\]}]+/gi, " "); + const { prose, ...references } = parseReferences(text); + const affirmative = prose.replace(negative, ""); + let changesPublicContract = false; + const requests = affirmative.split(requestSeparator).flatMap((part) => { + const clause = part + .trim() + .replace(/^\s*(?:\d+[.)]\s+|[-*•]\s+)*/, "") + .replace(requestPrefix, ""); + const request = requestPatterns.find(([, pattern]) => + pattern.test(clause), + )?.[0]; + if ( + request && + request !== "explain" && + request !== "research" && + request !== "test" + ) + changesPublicContract ||= changeContract.test(clause); + return request ? [request] : []; + }); + const kinds = unique(requests, (request) => request, requestPatterns.length); + if (!kinds.length) + kinds.push(task.kind ? fallbackKind[task.kind] : "unknown"); + + const searchQuery = [ + ...references.paths.map(({ file }) => file), + ...references.symbols, + ...references.errors, + affirmative.replaceAll("FILE_REFERENCE", " "), + ] + .join(" ") + .replace(/\s+/g, " ") + .trim() + .slice(0, 1000); + + return { + signals: { + kinds, + readOnly: kinds.every( + (kind) => kind === "explain" || kind === "research", + ), + fileScopeOnly: fileConstraint.test(affirmative), + preserveBehavior: behaviorConstraint.test(prose), + publicContract: changesPublicContract + ? "change" + : preserveContract.test(prose) + ? "preserve" + : "unspecified", + }, + references, + searchQuery, + }; +} diff --git a/runtime/story-route.ts b/runtime/story-route.ts index 9fed399..ac45afb 100644 --- a/runtime/story-route.ts +++ b/runtime/story-route.ts @@ -1,3 +1,5 @@ +import { open } from "node:fs/promises"; +import { join } from "node:path"; import type { Evidence, HarnessRuntime, @@ -6,6 +8,30 @@ import type { } from "../src/shared"; import { planRoute } from "./router"; import { connectedRuntimes } from "./worker-connections"; +import { + loadRoutingCalibration, + type RoutingCalibration, +} from "./routing-calibration"; + +export async function readRoutingCalibration(dataDir: string) { + try { + const file = await open(join(dataDir, "routing-calibration.json"), "r"); + try { + const info = await file.stat(); + if (!info.isFile() || !info.size || info.size > 1_000_000) return; + const buffer = Buffer.alloc(info.size + 1); + const { bytesRead } = await file.read(buffer); + if (bytesRead === info.size) + return loadRoutingCalibration( + JSON.parse(buffer.toString("utf8", 0, bytesRead)), + ); + } finally { + await file.close(); + } + } catch { + // An optional local calibration snapshot must never block a story. + } +} /** * Name the harness and model for a story that is already defined. @@ -17,11 +43,13 @@ export function planDefinedStory( evidence: Evidence | undefined, runtimes: HarnessRuntime[], state: AppState, + calibration?: RoutingCalibration, ) { return planRoute( task, evidence, connectedRuntimes(state, runtimes), state.settings, + calibration, ); } diff --git a/runtime/team/session-sync.ts b/runtime/team/session-sync.ts index ecd2416..a7e4fc1 100644 --- a/runtime/team/session-sync.ts +++ b/runtime/team/session-sync.ts @@ -495,7 +495,11 @@ export class TeamSessionSync { harness: task.harness, requestedModel: task.route?.model, actualModel: task.run.measurements?.modelId, - route: task.route ? { ...task.route, reasons: [] } : undefined, + // The v1 relay accepts only the v2 route shape. Requested and actual + // models above remain available with any local routing policy. + route: task.route?.policyVersion === "memcode-envelope-v2" + ? { ...task.route, reasons: [] } + : undefined, state: task.run.state, startedAt: task.run.startedAt, finishedAt: task.run.finishedAt, diff --git a/runtime/workers.ts b/runtime/workers.ts index 7856a5f..054f569 100644 --- a/runtime/workers.ts +++ b/runtime/workers.ts @@ -27,6 +27,7 @@ import { commandIdentity } from "./commands"; import type { MemtraceEngine } from "./memtrace"; import { discoverHarnesses } from "./catalog"; import { assignedHarness, planRoute } from "./router"; +import { readRoutingCalibration } from "./story-route"; import { assertWorkerConnected, connectedRuntimes } from "./worker-connections"; import { EpicWorkspace } from "./epic-workspace"; import { epicAnalysisProject } from "./epic-checkout"; @@ -47,7 +48,7 @@ import { prepareWorkerAnalysis } from "./worker-analysis"; import { WorkerStartupQueue } from "./worker-startup"; import { workerCheckoutBrief, workerContextForPrompt, workerTurnContext } from "./worker-turn"; import { previousProviderSession, resumableProviderSession } from "./provider-session"; -import { effectivePermissionMode } from "../src/permissions"; +import { effectivePermissionMode, supportsPermissionMode } from "../src/permissions"; import type { AgentEvent } from "./agents/types"; import { trackTurnActivity } from "./agents/activity"; import { applyAgentMeasurement } from "./agents/measurements"; @@ -823,12 +824,15 @@ export class WorkerManager { } } await progress("Measuring task scope and checking available workers"); - const routingTask = previousProvider && previousProvider.epicId === task.epicId && task.assignment === "auto" - ? { ...task, assignment: "manual" as const, harness: previousProvider.harness } - : task; - const [evidence, catalog] = await Promise.all([ + const workspace = task.run.workspace!; + const preferred = assignedHarness(task, permissionSettings); + const [evidence, catalog, calibration, previousSessionId] = await Promise.all([ this.engine.qualify(analysisProject, task), - this.catalog(assignedHarness(routingTask, permissionSettings)), + this.catalog(preferred), + readRoutingCalibration(this.dataDir), + previousProvider && (!preferred || preferred === previousProvider.harness) + ? resumableProviderSession(previousProvider, { ...task, harness: previousProvider.harness }, workspace) + : undefined, ]); continuing(); task.evidence = evidence; @@ -845,12 +849,23 @@ export class WorkerManager { const approved = connectedRuntimes(this.state(), catalog); if (!approved.length) throw Error("Connect a worker in Workers before starting a worker."); + const canContinue = previousSessionId && previousProvider && approved.some((runtime) => + runtime.id === previousProvider.harness && !runtime.allModelsDenied && + supportsPermissionMode(runtime.id, + effectivePermissionMode({ ...task, permissionMode: permissionPreference }, permissionSettings, runtime.id)), + ); + const pool = canContinue && !preferred + ? approved.filter((runtime) => runtime.id === previousProvider?.harness) + : approved; task.route = planRoute( - { ...routingTask, permissionMode: permissionPreference }, + { ...task, permissionMode: permissionPreference }, task.evidence, - approved, + pool, permissionSettings, + calibration, ); + if (canContinue && !preferred) + task.route.reasons.push("Continuing this story’s verified local provider conversation."); permissionMode = effectivePermissionMode( { ...task, permissionMode: permissionPreference }, permissionSettings, @@ -874,8 +889,9 @@ export class WorkerManager { await progress("Coordinating with the goal’s other tasks"); task.run.changeRunId = randomUUID(); await this.fleet.before(project, task); - const workspace = task.run.workspace!; - const resumeSessionId = await resumableProviderSession(previousProvider, task, workspace); + const resumeSessionId = canContinue && previousProvider?.harness === task.harness + ? previousSessionId + : undefined; continuing(); // Graph preparation and Fleet admission are serialized within an epic. // Brief retrieval and provider startup are per-worker reads: holding the @@ -1101,7 +1117,7 @@ export class WorkerManager { workspace, prompt, task.route.model, - this.state().settings.localModel, + !!task.route.localModel, task.route.effort, briefPath, contextConfig, @@ -1223,9 +1239,9 @@ export class WorkerManager { command, cwd: workspace, model: task.route.model, - automaticModelTier: task.modelOverride || permissionSettings.model ? undefined : task.route.tier, effort: task.route.effort, - localModel: this.state().settings.localModel, + calibratedModel: task.route.selection?.calibratedModel, + localModel: task.route.localModel, permissionMode, prompt, briefPath, diff --git a/scripts/routing-evaluate.ts b/scripts/routing-evaluate.ts new file mode 100644 index 0000000..7c13103 --- /dev/null +++ b/scripts/routing-evaluate.ts @@ -0,0 +1,22 @@ +import { readFile } from "node:fs/promises"; +import { + evaluateRouting, + routingEvaluationSchema, +} from "../runtime/routing-calibration"; + +if (process.argv.length !== 3) + throw Error( + "Usage: node --import tsx scripts/routing-evaluate.ts ", + ); + +const raw: unknown = JSON.parse(await readFile(process.argv[2], "utf8")); +const parsed = routingEvaluationSchema.safeParse(raw); +if (!parsed.success) { + const fields = parsed.error.issues + .slice(0, 10) + .map((issue) => issue.path.join(".")); + throw Error( + `Invalid routing evaluation fields: ${fields.join(", ") || "input"}`, + ); +} +console.log(JSON.stringify(evaluateRouting(parsed.data), null, 2)); diff --git a/src/components/Dialogs.tsx b/src/components/Dialogs.tsx index 837b4b3..f34d7ba 100644 --- a/src/components/Dialogs.tsx +++ b/src/components/Dialogs.tsx @@ -886,6 +886,7 @@ export function SettingsDialog({ } /> )} + Automatic stories use this override. Story assignments take precedence. diff --git a/src/components/Routing.tsx b/src/components/Routing.tsx index 588b602..576147c 100644 --- a/src/components/Routing.tsx +++ b/src/components/Routing.tsx @@ -45,7 +45,10 @@ export function RoutingCard({
{route.modelLabel || route.model} - {harnessNames[route.harness]} · {route.effort} effort + {harnessNames[route.harness]} ·{" "} + {route.selection?.effortBound === false + ? "Provider effort" + : `${route.effort} effort`}
{route.inputs.cognitive === null && route.inputs.cyclomatic === null && ( @@ -65,9 +68,9 @@ export function RoutingCard({
- {route.inputs.affected === null + {route.inputs.affected === null || route.inputs.request?.readOnly ? "—" - : `${route.inputs.affected}${route.inputs.incomplete ? "+" : ""}`} + : `${route.inputs.affected}${(route.inputs.impact?.incomplete ?? route.inputs.incomplete) ? "+" : ""}`} Impact
@@ -76,7 +79,13 @@ export function RoutingCard({ Why this model? - {route.status === "provisional" ? "Partial scope" : "Measured"} + {route.selection?.method === "explicit" + ? "Override" + : route.selection?.method === "fallback" + ? "Fallback" + : route.status === "provisional" + ? "Partial scope" + : "Measured"}
    @@ -84,10 +93,18 @@ export function RoutingCard({
  • {reason}
  • ))}
+ {route.selection && ( +

+ Work {route.selection.workTier} · Impact{" "} + {route.selection.impactTier ?? "read-only"} ·{" "} + {route.selection.eligibleConfigurations} eligible configurations +

+ )}

- Prototype envelope policy · {route.policyVersion}. Structural - measurements are deterministic; suitability thresholds are not - calibrated. + {route.selection?.method === "calibration" + ? "Controlled trial calibration" + : "Routing policy"}{" "} + · {route.policyVersion}

{route.inputs.sourceRevision && ( Source {route.inputs.sourceRevision.slice(0, 10)} diff --git a/src/routing-evidence.ts b/src/routing-evidence.ts new file mode 100644 index 0000000..2cfc742 --- /dev/null +++ b/src/routing-evidence.ts @@ -0,0 +1,22 @@ +/** Bounded source coverage for a routing decision. Counts describe observed evidence. */ +export interface RoutingScopeCoverage { + confirmedTargets: number; + inferredTargets: number; + unresolvedReferences: number; + measuredTargets: number; + incomplete: boolean; + publicContracts?: number; + nearbyTests?: number; +} + +/** Unique upstream dependencies observed across the selected source anchors. */ +export interface RoutingImpactEvidence { + targetCount: number; + observedTargets: number; + basis: "confirmed" | "inferred"; + incomplete: boolean; + affectedSymbols?: number; + affectedFiles?: number; + affectedProcesses?: number; + affectedModules?: number; +} diff --git a/src/routing-signals.ts b/src/routing-signals.ts new file mode 100644 index 0000000..82d7978 --- /dev/null +++ b/src/routing-signals.ts @@ -0,0 +1,18 @@ +export type RoutingRequestKind = + | "explain" + | "research" + | "test" + | "fix" + | "implement" + | "refactor" + | "rename" + | "unknown"; + +/** Content-free request characteristics used by the routing policy. */ +export interface RoutingRequestSignals { + kinds: RoutingRequestKind[]; + readOnly: boolean; + fileScopeOnly: boolean; + preserveBehavior: boolean; + publicContract: "change" | "preserve" | "unspecified"; +} diff --git a/src/shared.ts b/src/shared.ts index 18c92e9..a2ed44b 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -11,6 +11,8 @@ import type { QualitySnapshot } from "./intelligence"; import type { ContextAssistantSettings } from "./context-settings"; import type { CodeReviewAPI } from "./code-review"; import type { BrowserRequest, BrowserReply } from "./browser"; +import type { RoutingRequestSignals } from "./routing-signals"; +import type { RoutingImpactEvidence, RoutingScopeCoverage } from "./routing-evidence"; export type { ContextAssistantSettings } from "./context-settings"; export type { QualitySnapshot, IntelligenceDetail } from "./intelligence"; export type { @@ -66,17 +68,30 @@ export interface HarnessRuntime { note?: string; } export interface RouteDecision { - policyVersion: "memcode-envelope-v2"; + policyVersion: "memcode-envelope-v2" | "memcode-evidence-v3"; tier: ModelTier; harness: Harness; model: string; /** Account-discovered presentation label; the opaque ID remains the request. */ modelLabel?: string; effort: ReasoningEffort; + localModel?: true; mode: "automatic" | "manual"; status: "measured" | "provisional"; reasons: string[]; plannedAt: string; + /** Decision evidence stays on the device that planned the route. */ + selection?: { + method: "explicit" | "envelope" | "fallback" | "calibration"; + catalogFingerprint: string; + eligibleConfigurations: number; + effortBound: boolean; + workTier: ModelTier; + impactTier: ModelTier | null; + calibrationDigest?: string; + /** Concrete provider model to verify before sending a calibrated turn. */ + calibratedModel?: string; + }; inputs: { cognitive: number | null; cyclomatic: number | null; @@ -87,6 +102,9 @@ export interface RouteDecision { incomplete: boolean; sourceRevision?: string; graphRevision?: string; + request?: RoutingRequestSignals; + scope?: RoutingScopeCoverage; + impact?: RoutingImpactEvidence; }; } export type Priority = "high" | "medium" | "low"; @@ -154,6 +172,8 @@ export interface Evidence { affected?: number; affectedProcesses?: number; affectedFiles?: number; + impact?: RoutingImpactEvidence; + scopeCoverage?: RoutingScopeCoverage; sourceRevision?: string; graphRevision?: string; incomplete: boolean; diff --git a/tests/agent-codex.test.ts b/tests/agent-codex.test.ts index 5457dfd..33d0f9b 100644 --- a/tests/agent-codex.test.ts +++ b/tests/agent-codex.test.ts @@ -35,7 +35,7 @@ rl.on('line',line=>{const p=JSON.parse(line); send({id:p.id,result:{userAgent:'fixture'}}); }else if(p.method==='initialized')initialized=true; else if(p.method==='account/read')send({id:p.id,result:{account:{type:'chatgpt',id:'fixture'}}}); - else if(p.method==='model/list')send({id:p.id,result:{data:process.env.NO_CATALOG==='yes'?[]:[{model:'chosen-model',isDefault:true}]}}); + else if(p.method==='model/list')send({id:p.id,result:{data:process.env.NO_CATALOG==='yes'?[]:[{model:'chosen-model',isDefault:true,...(process.env.ADVERTISED_EFFORT?{supportedReasoningEfforts:[{reasoningEffort:process.env.ADVERTISED_EFFORT}]}:{})}]}}); else if(p.method==='thread/start'||p.method==='thread/resume'){ if(process.env.RESUME && (p.method!=='thread/resume'||p.params.threadId!==process.env.RESUME)){send({id:p.id,error:{message:'Expected the original thread to resume'}});return;} if(process.env.RESUME_ERROR){send({id:p.id,error:{message:'Unknown thread '+p.params.threadId}});return;} @@ -43,7 +43,7 @@ rl.on('line',line=>{const p=JSON.parse(line); if(process.env.MODEL_DENIED==='yes'){send({id:p.id,error:{code:-32603,message:'The requested model is not supported when using Codex with a ChatGPT account.',data:{code:'model_not_found'}}});return;} const full=process.env.MODE==='full-access'; if(!initialized||p.params.approvalPolicy!==(full?'never':'on-request')||p.params.sandbox!==(full?'danger-full-access':'workspace-write')||p.params.approvalsReviewer!==(process.env.MODE==='auto'?'auto_review':'user')||(p.method==='thread/start'&&p.params.allowProviderModelFallback!==false)||p.params.model!==(process.env.NO_CATALOG==='yes'?undefined:'chosen-model'))process.exit(12); - send({id:p.id,result:{thread:{id:process.env.WRONG_RESUME?'unrelated-thread':'thread-native'},...(process.env.NO_MODEL_METADATA==='yes'?{}:{model:'resolved-model',reasoningEffort:'medium'}),approvalPolicy:p.params.approvalPolicy,approvalsReviewer:process.env.DOWNGRADE==='yes'?'user':p.params.approvalsReviewer,sandbox:{type:full?'dangerFullAccess':'workspaceWrite'}}}); + send({id:p.id,result:{thread:{id:process.env.WRONG_RESUME?'unrelated-thread':'thread-native'},...(process.env.NO_MODEL_METADATA==='yes'?{}:{model:process.env.THREAD_MODEL||'resolved-model',reasoningEffort:process.env.THREAD_EFFORT||'medium'}),approvalPolicy:p.params.approvalPolicy,approvalsReviewer:process.env.DOWNGRADE==='yes'?'user':p.params.approvalsReviewer,sandbox:{type:full?'dangerFullAccess':'workspaceWrite'}}}); }else if(p.method==='turn/start'){ turnSettings=p.params; if(p.params.effort!==(process.env.NO_CATALOG==='yes'?undefined:'high')||p.params.input[0].text!=='The exact prompt')process.exit(13); @@ -76,6 +76,7 @@ async function runFixture( env: { ...process.env, ...env }, model: env.REQUESTED ?? "chosen-model", automaticModelTier: env.AUTO_TIER === "yes" ? "balanced" : undefined, + calibratedModel: env.CALIBRATED_MODEL, effort: "high", resumeSessionId: env.RESUME, prompt: "The exact prompt", @@ -152,6 +153,29 @@ test("Codex refuses an unavailable pinned model before the brief is sent", async } finally { await fixture.cleanup(); } }); +test("Codex validates a calibrated route against both the account catalog and the native thread before sending the brief", async () => { + const exact = { + CALIBRATED_MODEL: "chosen-model", + ADVERTISED_EFFORT: "high", + THREAD_MODEL: "chosen-model", + THREAD_EFFORT: "high", + }; + for (const [overrides, shouldPrompt] of [ + [{}, true], + [{ ADVERTISED_EFFORT: "medium" }, false], + [{ THREAD_MODEL: "fallback-model" }, false], + [{ THREAD_EFFORT: "medium" }, false], + ] as const) { + const f = await runFixture({ ...exact, ...overrides }); + try { + const result = await f.session.completion; + assert.equal(f.events.some(event => event.type === "prompted"), shouldPrompt); + assert.equal(result.exitCode, shouldPrompt ? 0 : 1); + if (!shouldPrompt) assert.match(result.error ?? "", /could not confirm the calibrated model and effort/); + } finally { await f.cleanup(); } + } +}); + test("Codex remembers a provider model rejection for the same account and runtime", async () => { const identity = "model-rejection-fixture"; const first = await runFixture({ COMMAND_IDENTITY: identity, MODEL_DENIED: "yes" }); diff --git a/tests/routing-calibration.test.ts b/tests/routing-calibration.test.ts new file mode 100644 index 0000000..4458034 --- /dev/null +++ b/tests/routing-calibration.test.ts @@ -0,0 +1,230 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + compileRoutingCalibration, + estimateRoutingCandidates, + evaluateRouting, + loadRoutingCalibration, + routingEvaluationSchema, + selectCalibratedCandidate, + type RoutingCandidate, + type RoutingCohort, + type RoutingEvaluation, + type RoutingOutcome, +} from "../runtime/routing-calibration"; + +const cohort: RoutingCohort = { + kind: "fix", + tier: "balanced", + coverage: "measured", +}; +const expensive: RoutingCandidate = { + harness: "codex", + model: "codex-test-1", + effort: "medium", +}; +const cheap: RoutingCandidate = { + harness: "claude", + model: "sonnet", + resolvedModel: "claude-sonnet-test-1", + effort: "medium", +}; +const revision = "1".repeat(40); + +function run( + repoId: string, + candidate: RoutingCandidate, + overrides: Partial = {}, +): RoutingOutcome { + return { + repoId, + storyId: "story-1", + revision, + cohort, + candidate, + observedModel: candidate.resolvedModel ?? candidate.model, + observedEffort: candidate.effort, + execution: "completed", + blindReview: "passed", + checks: "passed", + acceptance: "accepted", + totalCostMicros: candidate.harness === "codex" ? 200 : 100, + totalTokens: 1000, + totalDurationMs: 2000, + ...overrides, + }; +} + +const training = Array.from({ length: 250 }, (_, index) => + [expensive, cheap].map((candidate) => run(`train-${index}`, candidate)), +).flat(); + +test("calibration is input-order stable, excludes held-out repositories, and chooses the lowest verified cost", () => { + const heldOut = run("holdout", cheap, { + totalCostMicros: 999, + acceptance: "rejected", + }); + const calibration = compileRoutingCalibration( + [...training, heldOut], + ["holdout"], + ); + const reversed = compileRoutingCalibration([...training].reverse(), [ + "holdout", + ]); + assert.equal(reversed.digest, calibration.digest); + assert.deepEqual( + loadRoutingCalibration(JSON.parse(JSON.stringify(calibration))), + calibration, + ); + const estimates = estimateRoutingCandidates(calibration, cohort, [ + expensive, + cheap, + ]); + assert.equal(estimates.length, 2); + assert.ok( + estimates.every( + (row) => + row.repositories === 250 && row.accepted === 250 && row.lowerBound < 1, + ), + ); + assert.deepEqual( + selectCalibratedCandidate(estimates, [expensive, cheap], 0.9)?.candidate, + cheap, + ); + assert.deepEqual( + selectCalibratedCandidate(estimates, [expensive], 0.9)?.candidate, + expensive, + ); + assert.equal( + selectCalibratedCandidate(estimates, [expensive, cheap], 1), + undefined, + ); + assert.deepEqual( + estimateRoutingCandidates(calibration, { ...cohort, coverage: "partial" }, [ + cheap, + ]), + [], + ); +}); + +test("missing proof and pending reviews remain unresolved, while failures and observed fallbacks count against first-pass acceptance", () => { + const rows = [ + run("training-1", expensive, { + observedEffort: null, + blindReview: "unverified", + acceptance: "pending", + totalCostMicros: null, + }), + run("training-2", expensive, { observedModel: "provider-other-2" }), + run("training-3", expensive, { checks: "failed" }), + run("training-4", expensive), + ]; + const [estimate] = compileRoutingCalibration(rows, ["holdout"]).cohorts[0] + .estimates; + assert.equal(estimate.samples, 4); + assert.equal(estimate.accepted, 1); + assert.equal(estimate.unresolved, 1); + assert.equal(estimate.meanTotalCostMicros, null); + assert.equal( + selectCalibratedCandidate([estimate], [expensive], 0.5), + undefined, + ); +}); + +test("duplicate and conflicting case inputs fail, and unmatched candidate rows cannot skew a comparison", () => { + const row = run("shared", cheap); + assert.throws( + () => compileRoutingCalibration([row, row], ["holdout"]), + /Duplicate first-pass/, + ); + assert.throws( + () => + compileRoutingCalibration( + [row, run("shared", expensive, { revision: "2".repeat(40) })], + ["holdout"], + ), + /one frozen revision/, + ); + const calibration = compileRoutingCalibration( + [row, run("shared", expensive), run("unmatched", cheap)], + ["holdout"], + ); + assert.ok( + calibration.cohorts[0].estimates.every( + (estimate) => estimate.samples === 1, + ), + ); +}); + +test("persisted calibration rejects tampering, unresolved aliases and invalid cost fields", () => { + const calibration = compileRoutingCalibration(training, ["holdout"]); + assert.equal( + loadRoutingCalibration({ ...calibration, version: "unknown" }), + undefined, + ); + const tampered = structuredClone(calibration); + tampered.cohorts[0].estimates[0].meanTotalCostMicros = 1; + assert.equal(loadRoutingCalibration(tampered), undefined); + tampered.cohorts[0].estimates[0].meanTotalCostMicros = -1; + assert.equal(loadRoutingCalibration(tampered), undefined); + const staleAlias = { ...cheap, resolvedModel: "claude-sonnet-test-2" }; + assert.deepEqual( + estimateRoutingCandidates(calibration, cohort, [ + staleAlias, + { ...cheap, resolvedModel: undefined }, + ]), + [], + ); + assert.deepEqual( + compileRoutingCalibration( + [run("test", { ...cheap, resolvedModel: undefined })], + ["holdout"], + ).cohorts, + [], + ); +}); + +test("held-out policy evaluation reports only paired stories and a common denominator for each cost metric", () => { + const frozenStory = { repoId: "holdout", storyId: "story-1", revision }; + const routes = { + current: expensive, + wording: cheap, + graph: expensive, + combined: cheap, + }; + const input: RoutingEvaluation = { + version: 1, + heldOutRepoIds: [frozenStory.repoId], + outcomes: [ + run("train", cheap), + run("holdout", expensive), + run("holdout", cheap, { acceptance: "pending", totalCostMicros: null }), + run("holdout", expensive, { storyId: "missing-variant" }), + ], + decisions: [ + { ...frozenStory, routes }, + { ...frozenStory, storyId: "missing-variant", routes }, + ], + }; + const report = evaluateRouting(routingEvaluationSchema.parse(input)); + assert.equal(report.heldOutStories, 2); + assert.equal(report.pairedStories, 1); + assert.equal( + report.policies.find((row) => row.policy === "current")?.observedStories, + 2, + ); + assert.equal( + report.policies.find((row) => row.policy === "combined")?.unresolved, + 1, + ); + assert.ok( + report.policies.every( + (row) => row.costMicros.samples === 0 && row.costMicros.mean === null, + ), + ); + assert.ok( + report.policies.every( + (row) => row.tokens.samples === 1 && row.tokens.mean === 1000, + ), + ); +}); diff --git a/tests/routing-intent.test.ts b/tests/routing-intent.test.ts new file mode 100644 index 0000000..93c7afc --- /dev/null +++ b/tests/routing-intent.test.ts @@ -0,0 +1,105 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { analyzeRoutingIntent } from "../runtime/routing-intent.ts"; + +test("an explanation can mention changes without requesting an edit", () => { + const result = analyzeRoutingIntent({ + title: "Explain how to rename the public API", + description: "Please trace `planRoute` in `runtime/router.ts:143:5`.", + kind: "feature", + }); + assert.deepEqual(result.signals, { + kinds: ["explain", "research"], + readOnly: true, + fileScopeOnly: false, + preserveBehavior: false, + publicContract: "unspecified", + }); + assert.deepEqual(result.references.paths, [ + { file: "runtime/router.ts", line: 143, column: 5 }, + ]); + assert.deepEqual(result.references.symbols, ["planRoute"]); + assert.match(result.searchQuery, /runtime\/router\.ts planRoute/); +}); + +test("mixed requests carry the external contract and local scope separately", () => { + const result = analyzeRoutingIntent({ + title: "Rename the exported function `getRoute`", + description: + "Only edit `./runtime\\router.ts`. Add tests, then explain the compatibility impact. Preserve behavior.", + }); + assert.deepEqual(result.signals, { + kinds: ["rename", "implement", "test", "explain"], + readOnly: false, + fileScopeOnly: true, + preserveBehavior: true, + publicContract: "change", + }); + assert.deepEqual(result.references.paths, [{ file: "runtime/router.ts" }]); +}); + +test("negated edits and action words inside literal errors do not become requests", () => { + const result = analyzeRoutingIntent({ + title: "Investigate the error “Rename public API failed”", + description: + "Do not fix or change the API. Don’t add tests; just check `useRoute`.", + }); + assert.deepEqual(result.signals.kinds, ["research"]); + assert.equal(result.signals.readOnly, true); + assert.equal(result.signals.publicContract, "preserve"); + assert.deepEqual(result.references.errors, ["Rename public API failed"]); + assert.deepEqual(result.references.symbols, ["useRoute"]); +}); + +test("exact local references are bounded and do not include absolute or remote paths", () => { + const result = analyzeRoutingIntent({ + title: "Fix runtime/router.ts:143 and README.md.", + description: [ + "Compare `runtime/router.ts:143` with `src/Quality views/Graph.tsx#L7` and Dockerfile.", + "Look at function planRoute and formatRoute().", + "Ignore `../other/file.ts`, /tmp/Root.ts, `C:\\Users\\Example\\private.ts` and https://example.test/src/Remote.ts.", + ].join("\n"), + }); + assert.deepEqual(result.references.paths, [ + { file: "runtime/router.ts", line: 143 }, + { file: "src/Quality views/Graph.tsx", line: 7 }, + { file: "README.md" }, + { file: "Dockerfile" }, + ]); + assert.deepEqual(result.references.symbols, ["planRoute", "formatRoute"]); + assert.doesNotMatch(result.searchQuery, /private\.ts|Remote\.ts/); +}); + +test("a classified work item is a fallback and an unclassified fragment stays unknown", () => { + const fragment = { title: "Latency of the local worker", description: "" }; + assert.deepEqual(analyzeRoutingIntent(fragment).signals.kinds, ["unknown"]); + assert.equal(analyzeRoutingIntent(fragment).signals.readOnly, false); + assert.deepEqual( + analyzeRoutingIntent({ ...fragment, kind: "test" }).signals.kinds, + ["test"], + ); + const bounded = analyzeRoutingIntent({ + title: "Fix router.ts", + description: Array.from( + { length: 200 }, + (_, index) => `file${index}.ts`, + ).join(" "), + }); + assert.equal(bounded.references.paths.length, 8); + assert.ok(bounded.searchQuery.length <= 1000); +}); + +test("preserves native diagnostic literals without claiming an edit scope", () => { + const result = analyzeRoutingIntent({ + title: "Diagnose `ERR_INVALID_ARG_TYPE` and HTTP 409", + description: 'The worker is failing with "Something broke" during upload.', + }); + assert.deepEqual(result.references.errors, [ + "ERR_INVALID_ARG_TYPE", + "Something broke", + "HTTP 409", + ]); + assert.deepEqual(result.references.symbols, []); + assert.equal(result.signals.fileScopeOnly, false); + assert.equal(result.signals.readOnly, true); +}); diff --git a/tests/routing-qualification.test.ts b/tests/routing-qualification.test.ts new file mode 100644 index 0000000..8a447ae --- /dev/null +++ b/tests/routing-qualification.test.ts @@ -0,0 +1,277 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { type TestContext } from "node:test"; +import { git } from "../runtime/local"; +import { collectEvidence, refreshEvidence } from "../runtime/qualification"; +import type { Project, WorkItem } from "../src/shared"; + +const graphMeta = (token = "published-a") => ({ + graph_revision: { token, publication_unchanged_during_call: true }, +}); + +async function fixture(t: TestContext, changePublication = false) { + const folder = await mkdtemp(join(tmpdir(), "memcode-routing-fixture-")); + t.after(() => rm(folder, { recursive: true, force: true })); + await mkdir(join(folder, "src")); + const source = [ + "export function loadBoard() {", + " return read();", + "}", + "", + "export function saveBoard() {", + " return write();", + "}", + ].join("\n"); + await writeFile(join(folder, "src", "board.ts"), source, "utf8"); + await git(folder, ["init", "-b", "main"]); + await git(folder, ["add", "--", "src/board.ts"]); + await git(folder, [ + "-c", + "user.name=MemCode Test", + "-c", + "user.email=fixture@example.test", + "-c", + "commit.gpgSign=false", + "commit", + "-m", + "fixture", + ]); + const sourceCommit = await git(folder, ["rev-parse", "HEAD"]); + const project: Project = { + id: "fixture", + repoId: "fixture", + branch: "main", + analysis: "ready", + name: "Fixture", + description: "", + createdAt: "2026-11-20", + path: folder, + }; + const task: WorkItem = { + id: "story", + projectId: project.id, + identifier: "RT-1", + title: "Refactor board persistence", + description: + "Refactor `src/board.ts:2` and `saveBoard` without changing behavior.", + stage: "planned", + priority: "medium", + category: "Tests", + harness: "codex", + assignment: "auto", + kind: "refactor", + checklist: [], + messages: [], + createdAt: "2026-11-20", + updatedAt: "2026-11-20", + run: { state: "idle" }, + }; + const functions = [ + { name: "loadBoard", node_id: "load", start_line: 1, end_line: 3 }, + { name: "saveBoard", node_id: "save", start_line: 5, end_line: 7 }, + ].map((row) => ({ + ...row, + kind: "Function", + file_path: "src/board.ts", + is_exported: true, + })); + const shared = { + node_id: "shared", + file_path: "tests/board.test.ts", + kind: "Function", + }; + const separate = { + node_id: "extra", + file_path: "src/route.ts", + kind: "Module", + }; + const requests: Array<{ name: string; arguments: Record }> = + []; + const client = { + call: async ( + checkout: Project, + tool: string, + args: Record, + ) => { + requests.push({ name: tool, arguments: args }); + assert.equal(checkout, project); + assert.equal(args.repo_id, project.repoId); + if (tool === "get_query_revision") + return { + ready: true, + branch: project.branch, + token: "bound-revision", + source_commit: sourceCommit, + source_revision: "content-fingerprint", + _meta: graphMeta(), + }; + assert.equal(args.branch, project.branch); + if (tool === "get_symbol_context") { + const symbol = + args.symbol === "board.ts" + ? { + name: "board.ts", + kind: "File", + file_path: "src/board.ts", + node_id: "file", + } + : functions.find((functionRow) => functionRow.name === args.symbol); + return { + found: !!symbol, + symbol, + contains: args.symbol === "board.ts" ? functions : [], + pagination: { + contains: { next_offset: null, available_is_lower_bound: false }, + }, + _meta: graphMeta(), + }; + } + if (tool === "find_code") + return { results: functions, status: "complete", _meta: graphMeta() }; + if (tool === "get_function_quality_metrics") + return { + matches: 1, + _meta: graphMeta(), + function: { + ...functions.find((row) => row.name === args.function_name), + complexity_source: "ast", + cognitive_complexity: 4, + complexity: 2, + max_nesting: 1, + }, + }; + if (tool === "get_impact") { + const rows = args.target === "load" ? [shared] : [shared, separate]; + return { + found: true, + risk: "LOW", + target: { node_id: args.target }, + by_depth: { 1: rows }, + total_affected: rows.length, + affected_files: rows.map((row) => row.file_path), + affected_processes: [{ id: "flow" }], + _meta: graphMeta( + changePublication && args.target === "save" + ? "published-b" + : "published-a", + ), + }; + } + throw Error(`Unexpected graph tool ${tool}`); + }, + }; + return { project, task, client, requests }; +} + +test("exact line and symbol qualification deduplicates callers, files and flows", async (t) => { + const { project, task, client, requests } = await fixture(t); + const evidence = await collectEvidence(client, project, task); + assert.equal(evidence.state, "measured", evidence.note); + assert.deepEqual( + evidence.symbols.map((symbol) => symbol.name), + ["loadBoard", "saveBoard"], + ); + assert.deepEqual(evidence.impact, { + targetCount: 2, + observedTargets: 2, + basis: "confirmed", + incomplete: false, + affectedSymbols: 2, + affectedFiles: 2, + affectedProcesses: 1, + affectedModules: 1, + }); + assert.deepEqual(evidence.scopeCoverage, { + confirmedTargets: 2, + inferredTargets: 0, + unresolvedReferences: 0, + measuredTargets: 2, + incomplete: false, + nearbyTests: 1, + publicContracts: 2, + }); + assert.equal(evidence.sourceRevision, "content-fingerprint"); + assert.ok(!requests.some((request) => request.name === "find_code")); + assert.equal( + requests.filter((request) => request.name === "get_query_revision").at(-1) + ?.arguments.expected_revision, + "bound-revision", + ); + assert.deepEqual( + requests + .filter((request) => request.name === "get_impact") + .map((request) => request.arguments.target), + ["load", "save"], + ); +}); + +test("a mixed publication discards grouped impact and AST metrics", async (t) => { + const { project, task, client } = await fixture(t, true); + const evidence = await collectEvidence(client, project, task); + assert.equal(evidence.state, "partial"); + assert.match(evidence.note, /changed while/); + assert.equal(evidence.scopeCoverage?.measuredTargets, 0); + assert.equal(evidence.affected, undefined); + assert.equal(evidence.impact?.observedTargets, 0); + assert.deepEqual(evidence.symbols, []); +}); + +test("a changed work request refreshes evidence on the same checkout", async (t) => { + const { project, task, client } = await fixture(t); + const evidence = await collectEvidence(client, project, task); + const [result] = await refreshEvidence(client, project, [ + { + ...task, + evidence, + description: "Refactor `loadBoard` without changing behavior.", + }, + ]); + assert.equal(result.action, "refreshed"); + assert.deepEqual( + result.evidence?.symbols.map((symbol) => symbol.name), + ["loadBoard"], + ); + assert.notEqual( + result.evidence?.binding?.requestFingerprint, + evidence.binding?.requestFingerprint, + ); +}); + +test("partial impact totals without identities give a lower bound and never add together", async (t) => { + const { project, task, client } = await fixture(t); + const evidence = await collectEvidence( + { + call: (checkout, tool, args) => + tool === "get_impact" + ? Promise.resolve({ + found: true, + target: { node_id: args.target }, + risk: "UNKNOWN", + total_affected: args.target === "load" ? 11 : 14, + affected_files: [], + affected_processes: [], + _meta: graphMeta(), + }) + : client.call(checkout, tool, args), + }, + project, + task, + ); + assert.equal(evidence.state, "partial"); + assert.equal(evidence.affected, 14); + assert.equal(evidence.affectedFiles, undefined); + assert.equal(evidence.affectedProcesses, undefined); + assert.equal(evidence.impact?.incomplete, true); +}); + +test("an epic cannot adopt measurements from another checkout", async (t) => { + const { project, task, client } = await fixture(t); + project.analysisCheckout = "owned-worktree-v1"; + const evidence = await collectEvidence(client, project, task); + assert.equal(evidence.state, "partial"); + assert.match(evidence.note, /different checkout/); + assert.deepEqual(evidence.symbols, []); + assert.equal(evidence.impact?.affectedSymbols, undefined); +}); diff --git a/tests/routing.test.ts b/tests/routing.test.ts index df616ca..33cc746 100644 --- a/tests/routing.test.ts +++ b/tests/routing.test.ts @@ -1,6 +1,12 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { planRoute, qualifyTier, routingInputs } from "../runtime/router.ts"; +import { + assignedHarness, + planRoute, + qualifyTier, + routingInputs, +} from "../runtime/router.ts"; +import { compileRoutingCalibration } from "../runtime/routing-calibration.ts"; import { cursorCatalog } from "../src/cursor-models.ts"; import { initialState } from "../src/seed.ts"; import type { Evidence, HarnessRuntime } from "../src/shared.ts"; @@ -36,6 +42,222 @@ export const catalog: HarnessRuntime[] = ["codex", "claude", "cursor"].map( }), ); +test("story assignment and story model supersede the default harness's global pin", () => { + const { + tasks: [story], + settings, + } = initialState(); + const workspace = { + ...settings, + defaultHarness: "codex" as const, + model: "codex-extreme", + }; + const task = { + ...story, + assignment: "manual" as const, + harness: "claude" as const, + }; + assert.equal(assignedHarness(task, workspace), "claude"); + assert.equal( + planRoute(task, measured, catalog, workspace).model, + "claude-fast", + ); + assert.equal( + planRoute( + { ...task, modelOverride: "claude-frontier" }, + measured, + catalog, + workspace, + ).model, + "claude-frontier", + ); + assert.equal( + planRoute({ ...task, assignment: "auto" }, measured, catalog, workspace) + .model, + "codex-extreme", + ); + const local = { ...workspace, localModel: true, model: "qwen-local" }; + assert.equal(planRoute(task, measured, catalog, local).localModel, undefined); + assert.equal( + planRoute({ ...task, assignment: "auto" }, measured, catalog, local) + .localModel, + true, + ); +}); + +test("a qualifying model anywhere in the connected catalog precedes the preferred harness's default", () => { + const { + tasks: [story], + settings, + } = initialState(); + const task = { + ...story, + assignment: "auto" as const, + title: "Fix the board", + scope: ["src/components/View.tsx"], + }; + const [codex, , cursor] = catalog; + const defaultOnly = { + ...cursor, + models: [ + { + id: "custom", + label: "Default", + source: "acp" as const, + isDefault: true, + }, + ], + }; + const available = { + ...codex, + models: codex.models.filter((model) => model.tier === "frontier"), + }; + const evidence = { ...measured, affected: 70 }; + const route = planRoute(task, evidence, [defaultOnly, available], settings); + assert.equal(route.model, "codex-frontier"); + assert.equal(route.selection?.method, "envelope"); + const fallback = planRoute(task, evidence, [defaultOnly], settings); + assert.equal(fallback.model, "custom"); + assert.equal(fallback.status, "provisional"); +}); + +test("a public signature edit carries impact risk independently of AST effort", () => { + const { + tasks: [story], + settings, + } = initialState(); + const task = { + ...story, + assignment: "auto" as const, + title: "Change the public API signature", + description: "Change the exported signature of `render`.", + }; + const route = planRoute(task, measured, catalog, settings); + assert.equal(route.selection?.workTier, "fast"); + assert.equal(route.selection?.impactTier, "frontier"); + assert.equal(route.tier, "frontier"); + const readOnly = planRoute( + { + ...task, + title: "Explain the public API", + description: "Explain how `render` works. Do not change it.", + }, + { ...measured, affected: 900 }, + catalog, + settings, + ); + assert.equal(readOnly.selection?.impactTier, null); + assert.equal(readOnly.tier, "fast"); +}); + +test("catalog fingerprint and effort remain stable across discovery ordering", () => { + const { + tasks: [story], + settings, + } = initialState(); + const task = { ...story, assignment: "auto" as const }; + const withEfforts = catalog.map((runtime) => ({ + ...runtime, + models: runtime.models.map((model) => ({ + ...model, + efforts: ["high", "low"], + })), + })); + const reversed = [...withEfforts] + .reverse() + .map((runtime) => ({ + ...runtime, + models: [...runtime.models] + .reverse() + .map((model) => ({ ...model, efforts: [...model.efforts].reverse() })), + })); + const first = planRoute(task, measured, withEfforts, settings); + const second = planRoute(task, measured, reversed, settings); + assert.equal( + first.selection?.catalogFingerprint, + second.selection?.catalogFingerprint, + ); + assert.deepEqual( + [first.harness, first.model, first.effort], + [second.harness, second.model, second.effort], + ); +}); + +test("matched controlled outcomes can select a cheaper eligible configuration", () => { + const { + tasks: [story], + settings, + } = initialState(); + const task = { + ...story, + assignment: "auto" as const, + title: "Fix rendering", + description: "Fix a rendering bug.", + }; + const fast = { + harness: "codex", + model: "gpt-test-6-fast", + effort: "low", + } as const; + const cheaper = { + harness: "claude", + model: "claude-sonnet-9-1", + effort: "low", + } as const; + const available: HarnessRuntime[] = [fast, cheaper].map((candidate) => ({ + id: candidate.harness, + available: true, + path: "fixture", + name: candidate.harness, + models: [ + { + id: candidate.model, + label: candidate.model, + source: "cli", + tier: candidate === fast ? "fast" : "balanced", + efforts: [candidate.effort], + }, + ], + })); + const profile = compileRoutingCalibration( + Array.from({ length: 75 }, (_, index) => + [fast, cheaper].map((candidate) => ({ + repoId: `fixture-${index}`, + storyId: "fixture", + revision: "a".repeat(40), + cohort: { + kind: "fix" as const, + tier: "fast" as const, + coverage: "measured" as const, + }, + candidate, + observedModel: candidate.model, + observedEffort: candidate.effort, + execution: "completed" as const, + checks: "passed" as const, + blindReview: "passed" as const, + acceptance: "accepted" as const, + totalCostMicros: candidate === cheaper ? 100 : 200, + totalTokens: 500, + totalDurationMs: 1000, + })), + ).flat(), + ["fixture-74"], + ); + assert.equal( + planRoute(task, measured, available, settings).model, + fast.model, + ); + const calibrated = planRoute(task, measured, available, settings, profile); + assert.equal(calibrated.model, cheaper.model); + assert.equal(calibrated.selection?.method, "calibration"); + assert.equal(calibrated.selection?.calibrationDigest, profile.digest); + assert.equal( + planRoute(task, measured, available.slice(0, 1), settings, profile).model, + fast.model, + ); +}); + test("each envelope admits its exact boundary and escalates above it", () => { const base = { ...routingInputs(measured), @@ -118,14 +340,53 @@ test("unavailable catalogs produce an actionable failure rather than a fabricate }); test("Cursor routing uses live session variants for automatic routes and validates saved overrides", () => { const state = initialState(); - const task = { ...state.tasks[0], assignment: "manual" as const, harness: "cursor" as const }; + const task = { + ...state.tasks[0], + assignment: "manual" as const, + harness: "cursor" as const, + }; const grok = "grok-4.7[context=256k,reasoning_effort=high,fast=true]"; - const offered = cursorCatalog({models:{availableModels:[{modelId:"other",name:"Other"},{modelId:grok,name:"Grok 4.7"}]}}); - const runtimes = [{...catalog[2], models: offered}]; - assert.equal(planRoute(task, undefined, runtimes, state.settings).model, grok); - assert.equal(planRoute({...task,modelOverride:"grok-4.7-high"}, measured, runtimes, state.settings).model, grok); - assert.throws(() => planRoute({...task,modelOverride:"grok-4.7-xhigh"}, measured, runtimes, state.settings), /Worker assignment/); - assert.equal(planRoute({...task,modelOverride:"other"}, measured, runtimes, state.settings).model, "other"); + const offered = cursorCatalog({ + models: { + availableModels: [ + { modelId: "other", name: "Other" }, + { modelId: grok, name: "Grok 4.7" }, + ], + }, + }); + const runtimes = [{ ...catalog[2], models: offered }]; + assert.equal( + planRoute(task, undefined, runtimes, state.settings).model, + grok, + ); + assert.equal( + planRoute( + { ...task, modelOverride: "grok-4.7-high" }, + measured, + runtimes, + state.settings, + ).model, + grok, + ); + assert.throws( + () => + planRoute( + { ...task, modelOverride: "grok-4.7-xhigh" }, + measured, + runtimes, + state.settings, + ), + /Worker assignment/, + ); + assert.equal( + planRoute( + { ...task, modelOverride: "other" }, + measured, + runtimes, + state.settings, + ).model, + "other", + ); }); test("local inference requires an explicit installed model name", () => { const state = initialState(); @@ -143,13 +404,40 @@ test("local inference requires an explicit installed model name", () => { test("empty remote catalogs use the provider default while explicit pins must be available", () => { const state = initialState(); for (const id of ["claude", "codex", "cursor"] as const) { - const runtime = { ...catalog.find(runtime => runtime.id === id)!, models: [] }; - const task = { ...state.tasks[0], harness: id, assignment: "manual" as const }; - const defaults = { claude: "default", codex: "Codex default", cursor: "Cursor default" }; - assert.equal(planRoute(task, measured, [runtime], state.settings).model, defaults[id]); - assert.throws(() => planRoute({ ...task, modelOverride: "old-id" }, measured, [runtime], state.settings), /cannot confirm|no longer offers/); + const runtime = { + ...catalog.find((runtime) => runtime.id === id)!, + models: [], + }; + const task = { + ...state.tasks[0], + harness: id, + assignment: "manual" as const, + }; + const defaults = { + claude: "default", + codex: "Codex default", + cursor: "Cursor default", + }; + assert.equal( + planRoute(task, measured, [runtime], state.settings).model, + defaults[id], + ); + assert.throws( + () => + planRoute( + { ...task, modelOverride: "old-id" }, + measured, + [runtime], + state.settings, + ), + /cannot confirm|no longer offers/, + ); } - const local = planRoute(state.tasks[0], measured, [catalog[0]], { ...state.settings, model: "local-ollama", localModel: true }); + const local = planRoute(state.tasks[0], measured, [catalog[0]], { + ...state.settings, + model: "local-ollama", + localModel: true, + }); assert.equal(local.model, "local-ollama"); }); From e2cb2de1d941c8bf06fe661f6a44d314d3fa801b Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Fri, 20 Nov 2026 23:57:55 +0100 Subject: [PATCH 2/4] Classify ambiguous briefs locally and route with maintainability --- docs/routing-measurement.md | 47 ++++ runtime/app.ts | 6 +- runtime/qualification.ts | 40 ++- runtime/router.ts | 59 ++++- runtime/routing-calibration.ts | 21 +- runtime/routing-intent.ts | 29 ++- runtime/routing-language-model.ts | 248 ++++++++++++++++++ runtime/story-route.ts | 59 ++++- runtime/workers.ts | 6 +- scripts/routing-language-benchmark.ts | 236 +++++++++++++++++ scripts/routing-language-train.ts | 322 ++++++++++++++++++++++++ src/routing-signals.ts | 6 + src/shared.ts | 5 +- tests/routing-calibration.test.ts | 8 + tests/routing-language-model.test.ts | 171 +++++++++++++ tests/routing-language-training.test.ts | 91 +++++++ tests/routing-qualification.test.ts | 72 ++++++ tests/routing.test.ts | 131 +++++++++- tests/story-route.test.ts | 59 ++++- 19 files changed, 1582 insertions(+), 34 deletions(-) create mode 100644 runtime/routing-language-model.ts create mode 100644 scripts/routing-language-benchmark.ts create mode 100644 scripts/routing-language-train.ts create mode 100644 tests/routing-language-model.test.ts create mode 100644 tests/routing-language-training.test.ts diff --git a/docs/routing-measurement.md b/docs/routing-measurement.md index c158e27..a5da34c 100644 --- a/docs/routing-measurement.md +++ b/docs/routing-measurement.md @@ -84,6 +84,10 @@ policy names. Each route is the selected candidate or `null` for an abstention. The execution states are `running`, `completed` and `failed`. For checks and blind review, use `passed`, `failed` or `unverified`. For acceptance, use `accepted`, `rejected` or `pending`. +For a cohort routed with inferred wording, copy `languageModelDigest` from +the route's wording evidence. For an edit with an observed maintainability index +below 10, include `lowMaintainability: true`. These optional cohort fields bind +outcome estimates to the evidence used to make those decisions. Keep the raw experiment file local. The evaluator reads measurements and emits aggregates. It launches no workers and makes no network calls. @@ -129,6 +133,49 @@ conversation, its provider takes priority unless a story or workspace choice specifies another provider. The story brief remains the routing input for that pass. +Memtrace returns the native maintainability index alongside AST complexity. +The lowest verified index for the measured functions is shown in the story's +routing explanation. An edit with a measured index below 10 has a balanced +minimum. This guard does not raise an already higher tier. The native index +includes cyclomatic complexity in its formula. Keep it as an independent input +and use separate evaluation cohorts for these edits. [Maintainability index bands](https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-maintainability-index-range-and-meaning?view=visualstudio) + +## Train the optional local wording classifier + +Create a local JSON file with `version: 1`, `calibrationRepoIds`, +`heldOutRepoIds`, and `stories`. Each story needs a `repoId`, `storyId`, +`title`, `description`, and a human-labeled `kinds` array made from +`explain`, `research`, `test`, `fix`, `implement`, `refactor`, and `rename`. +Keep complete repositories in separate training, calibration, and held-out +groups. A calibration or held-out repository must have stories in the file. +Separate mixed intentions into multiple labels. Include short briefs, dictation +errors, and constraints with multiple clauses. Keep the labeled source file +private. It contains real story text. + +```sh +node --import tsx scripts/routing-language-train.ts path/to/labeled-stories.json path/to/new/routing-language.json +``` + +Read the held-out report before enabling the profile. To enable it, place the +generated `routing-language.json` in the MemCode data folder shown in Settings. +Planning and worker startup read it on demand and reuse the compiled weights +until the file changes. Move the file out of that folder to go back to the rules. +Rules handle explicit intent and constraints. The classifier helps when the rules +find no action and may abstain. Its intent scores describe wording evidence. +The chance of first-pass acceptance comes from the separate outcome evaluation. +No training snapshots are preinstalled. + +The classifier runs inside MemCode's local runtime. It creates no extra model +process and makes no network calls. A profile is bounded to 256 KiB on disk +and at most 448 KiB in packed weights. Maintainability uses an existing Memtrace +response. Measure cold parsing and warm classifier time on the current machine +with the following command. Giving it a profile path benchmarks that snapshot. +Omitting the path runs a synthetic maximum-size profile to measure overhead. + +```sh +node --expose-gc --import tsx scripts/routing-language-benchmark.ts +``` + ## Planning and privacy Locally authored entity transitions measure creation, deletion, completion and diff --git a/runtime/app.ts b/runtime/app.ts index fe7f3a2..820bdbd 100644 --- a/runtime/app.ts +++ b/runtime/app.ts @@ -27,7 +27,7 @@ import { WorkerManager } from "./workers"; import { PreviewManager } from "./preview"; import { localURL } from "./urls"; import { discoverHarnesses } from "./catalog"; -import { planDefinedStory, readRoutingCalibration } from "./story-route"; +import { planDefinedStory, readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { qualificationRequestFingerprint } from "./qualification"; import { registerPlanning } from "./planning"; import { registerPlanningControls } from "./planning-controls"; @@ -772,13 +772,14 @@ export async function createRuntime( if (isActive(current)) throw new Error(activeRouteError); const measurement = { ...current, scope: current.scope?.slice() }; const measuredRequest = qualificationRequestFingerprint(measurement); - const [installed, evidence, calibration] = await Promise.all([ + const [installed, evidence, calibration, languageModel] = await Promise.all([ discover(), engine.qualify( epicAnalysisProject(project(measurement.projectId), measurement), measurement, ), readRoutingCalibration(store.dir), + readRoutingLanguage(store.dir), ]); const latest = task(id); if (isActive(latest)) throw new Error(activeRouteError); @@ -791,6 +792,7 @@ export async function createRuntime( installed, store.state, calibration, + languageModel, ); latest.evidence = evidence; latest.route = route; diff --git a/runtime/qualification.ts b/runtime/qualification.ts index c7ed805..b57bc78 100644 --- a/runtime/qualification.ts +++ b/runtime/qualification.ts @@ -370,6 +370,14 @@ const measureNumber = (value: unknown): number | undefined => ? value : undefined; +function withoutMaintainability(symbols: Evidence["symbols"]) { + return symbols.map((symbol) => { + if (symbol.maintainabilityIndex === undefined) return symbol; + const { maintainabilityIndex: _, ...measurements } = symbol; + return measurements; + }); +} + function qualityMatches( row: QualityRow, target: { name: string; file: string; line: number; scopePath?: string }, @@ -485,12 +493,25 @@ export async function collectEvidence( ); if (matching.length !== 1) return; const row = matching[0]; + const ast = row.complexity_source === "ast"; + const maintainability = measureNumber(row.maintainability_index); measuredMetrics.set(target, { cognitive: measureNumber(row.cognitive_complexity), cyclomatic: measureNumber(row.complexity), nesting: measureNumber(row.max_nesting), - metricSource: - row.complexity_source === "ast" ? "ast" : "estimated", + metricSource: ast ? "ast" : "estimated", + ...(ast && + row.quality_metrics_v === 1 && + row.name === target.name && + row.file_path && + row.kind === target.kind && + (!target.nodeId || + !row.node_id || + row.node_id === target.nodeId) && + maintainability !== undefined && + maintainability <= 100 + ? { maintainabilityIndex: maintainability } + : {}), }); }), ); @@ -592,9 +613,21 @@ export async function collectEvidence( incomplete = true; } } + const maintainabilityCurrent = + firstIndex.ready && + !!firstIndex.revision && + index.ready && + !!index.revision && + binding?.index === "current" && + !missingPublication && + !deadline.signal.aborted; return { state: incomplete ? "partial" : "measured", - symbols: changedPublication ? [] : symbols, + symbols: changedPublication + ? [] + : maintainabilityCurrent + ? symbols + : withoutMaintainability(symbols), // A union containing rows from two publications is not an observation. impact: changedPublication ? { @@ -808,6 +841,7 @@ export async function refreshEvidence( ...evidence, state: "partial", incomplete: true, + symbols: withoutMaintainability(evidence.symbols), note: freshness.reason, binding: { ...current, diff --git a/runtime/router.ts b/runtime/router.ts index e501f8e..11b61c9 100644 --- a/runtime/router.ts +++ b/runtime/router.ts @@ -23,6 +23,7 @@ import type { WorkItem, } from "../src/shared"; import { analyzeRoutingIntent } from "./routing-intent"; +import type { RoutingLanguageModel } from "./routing-language-model"; import type { RoutingRequestSignals } from "../src/routing-signals"; import { estimateRoutingCandidates, @@ -108,10 +109,27 @@ export function routingInputs( ): RouteDecision["inputs"] { const symbols = evidence?.symbols ?? []; const ast = symbols.filter((symbol) => symbol.metricSource === "ast"); + const maintainability = ast + .map((symbol) => symbol.maintainabilityIndex) + .filter( + (value): value is number => + typeof value === "number" && + Number.isFinite(value) && + value >= 0 && + value <= 100, + ); return { cognitive: maximum(ast.map((s) => s.cognitive)), cyclomatic: maximum(ast.map((s) => s.cyclomatic)), nesting: maximum(ast.map((s) => s.nesting)), + ...(maintainability.length + ? { + maintainability: { + lowest: Math.min(...maintainability), + measuredSymbols: maintainability.length, + }, + } + : {}), affected: evidence?.affected ?? null, processes: evidence?.affectedProcesses ?? null, moduleRoots: new Set(symbols.map((s) => moduleRoot(s.file))).size, @@ -132,8 +150,15 @@ export function routingInputs( const within = (observed: number | null | undefined, limit: number) => observed == null || observed <= limit; +// The normalized 0–9 band is a conservative signal for edits. Raising the +// minimum once avoids adding cyclomatic complexity again through its MI weight. +const lowMaintainability = (input: RouteDecision["inputs"]) => + !input.request?.readOnly && + input.maintainability !== undefined && + input.maintainability.lowest < 10; + function taskTiers(input: RouteDecision["inputs"]) { - const workTier: ModelTier = + const measuredWorkTier: ModelTier = envelopes.find( (envelope) => within(input.cognitive, envelope.cognitive) && @@ -142,6 +167,10 @@ function taskTiers(input: RouteDecision["inputs"]) { within(input.scope?.confirmedTargets, envelope.targets) && input.moduleRoots <= envelope.roots, )?.tier ?? "extreme"; + const workTier = + lowMaintainability(input) && measuredWorkTier === "fast" + ? "balanced" + : measuredWorkTier; const impactTier: ModelTier | null = input.request?.readOnly ? null @@ -326,6 +355,12 @@ function describeInputs(inputs: RouteDecision["inputs"]): string[] { if (request) { const kinds = request.kinds.filter((kind) => kind !== "unknown"); if (kinds.length) reasons.push(`Request intent · ${kinds.join(", ")}.`); + if (request.language) + reasons.push( + request.language.outcome === "classified" + ? "The local wording model classified this brief." + : "The local wording model abstained. Routing uses the available story and source evidence.", + ); if (request.fileScopeOnly) reasons.push("The brief limits edits to its named scope."); if (request.preserveBehavior) @@ -348,6 +383,17 @@ function describeInputs(inputs: RouteDecision["inputs"]): string[] { reasons.push( `AST maxima · cognitive ${inputs.cognitive}, cyclomatic ${inputs.cyclomatic ?? "unknown"}, nesting ${inputs.nesting ?? "unknown"}.`, ); + if (inputs.maintainability) { + const { lowest, measuredSymbols } = inputs.maintainability; + const symbols = measuredSymbols === 1 ? "function" : "functions"; + reasons.push( + `Lowest native maintainability index · ${Number(lowest.toFixed(1))}/100 across ${measuredSymbols} measured ${symbols}.`, + ); + if (lowMaintainability(inputs)) + reasons.push( + "Low maintainability sets a balanced minimum for this edit.", + ); + } if (request?.readOnly) reasons.push( "This request is read-only. Source complexity informs the route.", @@ -381,8 +427,9 @@ export function planRoute( runtimes: HarnessRuntime[], settings: Settings, calibration?: RoutingCalibration, + languageModel?: RoutingLanguageModel, ): RouteDecision { - const request = analyzeRoutingIntent(task).signals; + const request = analyzeRoutingIntent(task, languageModel).signals; const inputs = routingInputs(evidence, request); const { tier, workTier, impactTier, complete } = taskTiers(inputs); const reasons = describeInputs(inputs); @@ -497,6 +544,12 @@ export function planRoute( kind: kinds.length > 1 ? "mixed" : (kinds[0] ?? "unknown"), tier, coverage: complete ? ("measured" as const) : ("partial" as const), + ...(request.language?.outcome === "classified" + ? { languageModelDigest: request.language.digest } + : {}), + ...(lowMaintainability(inputs) + ? { lowMaintainability: true as const } + : {}), }; const target = reliabilityTarget[tier]; const estimate = @@ -560,7 +613,7 @@ export function planRoute( `${runtime.name} / ${model.label}${effortBound ? ` at ${level} effort` : " with provider-configured effort"}.`, ); return { - policyVersion: "memcode-evidence-v3", + policyVersion: "memcode-evidence-v4", tier, harness: runtime.id, model: model.id, diff --git a/runtime/routing-calibration.ts b/runtime/routing-calibration.ts index 4a831e8..1faf76a 100644 --- a/runtime/routing-calibration.ts +++ b/runtime/routing-calibration.ts @@ -18,6 +18,11 @@ const cohortSchema = z.strictObject({ kind: z.string().regex(/^[a-z][a-z0-9_-]{0,39}$/), tier: z.enum(["fast", "balanced", "frontier", "extreme"]), coverage: z.enum(["measured", "partial"]), + languageModelDigest: z + .string() + .regex(/^[a-f0-9]{64}$/) + .optional(), + lowMaintainability: z.literal(true).optional(), }); const nonnegative = z.int().nonnegative(); const estimateSchema = z.strictObject({ @@ -93,8 +98,20 @@ export const routingEvaluationSchema = z.strictObject({ }); export type RoutingEvaluation = z.infer; -const cohortKey = ({ kind, tier, coverage }: RoutingCohort) => - JSON.stringify([kind, tier, coverage]); +const cohortKey = ({ + kind, + tier, + coverage, + languageModelDigest, + lowMaintainability, +}: RoutingCohort) => + JSON.stringify([ + kind, + tier, + coverage, + languageModelDigest ?? null, + lowMaintainability ?? false, + ]); const candidateKey = ({ harness, model, diff --git a/runtime/routing-intent.ts b/runtime/routing-intent.ts index 46547de..eefacaf 100644 --- a/runtime/routing-intent.ts +++ b/runtime/routing-intent.ts @@ -3,6 +3,10 @@ import type { RoutingRequestKind, RoutingRequestSignals, } from "../src/routing-signals"; +import { + predictRoutingLanguage, + type RoutingLanguageModel, +} from "./routing-language-model"; interface PathReference { file: string; @@ -208,6 +212,7 @@ function parseReferences(text: string) { export function analyzeRoutingIntent( task: Pick, + model?: RoutingLanguageModel, ): RoutingIntentAnalysis { const text = `${task.title.slice(0, 500)}\n${task.description.slice(0, 6000)}` .replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)/g, " ") @@ -233,6 +238,12 @@ export function analyzeRoutingIntent( return request ? [request] : []; }); const kinds = unique(requests, (request) => request, requestPatterns.length); + const prediction = + model && !kinds.length + ? predictRoutingLanguage(model, task.title, task.description) + : undefined; + const learned = !!prediction?.accepted.length; + if (prediction) kinds.push(...prediction.accepted); if (!kinds.length) kinds.push(task.kind ? fallbackKind[task.kind] : "unknown"); @@ -250,9 +261,9 @@ export function analyzeRoutingIntent( return { signals: { kinds, - readOnly: kinds.every( - (kind) => kind === "explain" || kind === "research", - ), + readOnly: + !learned && + kinds.every((kind) => kind === "explain" || kind === "research"), fileScopeOnly: fileConstraint.test(affirmative), preserveBehavior: behaviorConstraint.test(prose), publicContract: changesPublicContract @@ -260,6 +271,18 @@ export function analyzeRoutingIntent( : preserveContract.test(prose) ? "preserve" : "unspecified", + ...(prediction && model + ? { + language: { + digest: model.digest, + outcome: learned ? "classified" : "abstained", + scores: prediction.scores.map(({ kind, probability }) => ({ + kind, + score: Math.round(probability * 1_000) / 1_000, + })), + }, + } + : {}), }, references, searchQuery, diff --git a/runtime/routing-language-model.ts b/runtime/routing-language-model.ts new file mode 100644 index 0000000..e2b761a --- /dev/null +++ b/runtime/routing-language-model.ts @@ -0,0 +1,248 @@ +import { createHash } from "node:crypto"; +import { z } from "zod"; +import type { RoutingRequestKind } from "../src/routing-signals"; + +export const routingLanguageKinds = [ + "explain", + "research", + "test", + "fix", + "implement", + "refactor", + "rename", +] as const satisfies readonly RoutingRequestKind[]; + +export type RoutingLanguageKind = (typeof routingLanguageKinds)[number]; +export const RUNTIME_LANGUAGE_FEATURE_COUNT = 16_384; +export const MAX_ROUTING_LANGUAGE_FEATURES = 512; +export const MAX_ROUTING_LANGUAGE_WEIGHTS = 1_024; +export const MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES = 256 * 1_024; +const featuresPerFamily = RUNTIME_LANGUAGE_FEATURE_COUNT / 2; +const familyMask = featuresPerFamily - 1; +const hashOffset = 2_166_136_261; +const hashPrime = 16_777_619; +const version = "memcode-routing-language-v1"; + +// The trainer and desktop share these bounds and feature indices. +function lexicalWords(text: string, limit: number, wordCount: number) { + return ( + text + .slice(0, limit) + .normalize("NFKC") + .replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)/g, " ") + .replace(/`[^`\r\n]*`/g, " reference ") + .replace(/\b(?:[a-z][a-z0-9+.-]{1,15}:\/\/|www\.)\S+/gi, " reference ") + .replace( + /(? word.slice(0, 48)); +} + +function addHash(hash: number, text: string) { + for (let index = 0; index < text.length; index++) + hash = Math.imul(hash ^ text.charCodeAt(index), hashPrime); + return hash; +} + +export function extractRoutingLanguageFeatures( + title: string, + description: string, +) { + const documents = [ + lexicalWords(title, 256, 32), + lexicalWords(description, 2_800, 96), + ]; + const indices = new Set(); + for (const words of documents) { + let previous: string | undefined; + for (const word of words) { + indices.add(addHash(hashOffset, word) & familyMask); + if (previous) + indices.add( + addHash(addHash(addHash(hashOffset, previous), " "), word) & + familyMask, + ); + previous = word; + } + } + // Prefix and suffix markers retain useful spelling shapes at word boundaries. + subwords: for (const word of documents.flat()) { + if (indices.size >= MAX_ROUTING_LANGUAGE_FEATURES) break; + const padded = "^" + word + "$"; + for (let start = 0; start <= padded.length - 3; start++) { + let hash = hashOffset; + for (let end = start; end < Math.min(start + 5, padded.length); end++) { + hash = Math.imul(hash ^ padded.charCodeAt(end), hashPrime); + if (end - start < 2) continue; + indices.add(featuresPerFamily + (hash & familyMask)); + if (indices.size >= MAX_ROUTING_LANGUAGE_FEATURES) break subwords; + } + } + } + return [...indices].sort((left, right) => left - right); +} + +const coefficient = z.number().min(-64).max(64); +const labelSchema = z.strictObject({ + kind: z.enum(routingLanguageKinds), + bias: coefficient, + threshold: z.number().min(0.5).max(1), + minFeatures: z.int().min(1).max(16), + weights: z + .array( + z.tuple([ + z.int().nonnegative().lt(RUNTIME_LANGUAGE_FEATURE_COUNT), + coefficient.refine((value) => Math.fround(value) !== 0), + ]), + ) + .min(1) + .max(MAX_ROUTING_LANGUAGE_WEIGHTS), +}); +const profileSchema = z.strictObject({ + version: z.literal(version), + labels: z.array(labelSchema).min(1).max(routingLanguageKinds.length), +}); +const snapshotSchema = profileSchema.extend({ + digest: z.string().regex(/^[a-f0-9]{64}$/), +}); + +export type RoutingLanguageLabel = z.infer; +export type RoutingLanguageSnapshot = z.infer; +export interface RoutingLanguageModel { + readonly digest: string; + readonly labels: readonly { + kind: RoutingLanguageKind; + bias: number; + minFeatures: number; + threshold: number; + weights: Float32Array; + }[]; +} + +function orderedProfile( + labels: RoutingLanguageLabel[], +): z.infer { + const ordered = [...labels].sort( + (left, right) => + routingLanguageKinds.indexOf(left.kind) - + routingLanguageKinds.indexOf(right.kind), + ); + if (new Set(ordered.map(({ kind }) => kind)).size !== ordered.length) + throw Error("Each intent can appear only once in the language profile."); + return { + version, + labels: ordered.map(({ kind, bias, minFeatures, threshold, weights }) => { + if (new Set(weights.map(([index]) => index)).size !== weights.length) + throw Error("Each language feature can appear only once per intent."); + return { + kind, + bias: Math.fround(bias), + minFeatures, + threshold, + weights: weights + .map(([index, value]): [number, number] => [ + index, + Math.fround(value), + ]) + .sort(([left], [right]) => left - right), + }; + }), + }; +} + +function profileDigest(profile: z.infer) { + return createHash("sha256").update(JSON.stringify(profile)).digest("hex"); +} + +export function createRoutingLanguageSnapshot( + labels: RoutingLanguageLabel[], +): RoutingLanguageSnapshot { + const profile = orderedProfile( + profileSchema.parse({ version, labels }).labels, + ); + const snapshot = { ...profile, digest: profileDigest(profile) }; + if (JSON.stringify(snapshot).length > MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES) + throw Error("The language profile exceeds the desktop size limit."); + return snapshot; +} + +export function loadRoutingLanguageModel( + value: unknown, +): RoutingLanguageModel | undefined { + const parsed = snapshotSchema.safeParse(value); + if (!parsed.success) return; + try { + const profile = orderedProfile(parsed.data.labels); + if (profileDigest(profile) !== parsed.data.digest) return; + return { + digest: parsed.data.digest, + labels: profile.labels.map(({ weights, ...label }) => { + // A bounded packed table lets inference visit only the request's active features. + const table = new Float32Array(RUNTIME_LANGUAGE_FEATURE_COUNT); + for (const [index, value] of weights) table[index] = value; + return { ...label, weights: table }; + }), + }; + } catch { + return; + } +} + +export function scoreRoutingLanguageFeatures( + model: RoutingLanguageModel, + features: readonly number[], +) { + const accepted: RoutingLanguageKind[] = []; + const scores = model.labels.map( + ({ kind, bias, minFeatures, threshold, weights }) => { + let logit = bias; + let matchedFeatures = 0; + let supportingFeatures = 0; + for ( + let index = 0; + index < Math.min(features.length, MAX_ROUTING_LANGUAGE_FEATURES); + index++ + ) { + const weight = weights[features[index]]; + if (!weight) continue; + logit += weight; + matchedFeatures++; + if (weight > 0) supportingFeatures++; + } + const probability = 1 / (1 + Math.exp(-logit)); + if ( + supportingFeatures && + matchedFeatures >= minFeatures && + probability >= threshold + ) + accepted.push(kind); + return { kind, probability, matchedFeatures, supportingFeatures }; + }, + ); + return { scores, accepted }; +} + +export function predictRoutingLanguage( + model: RoutingLanguageModel, + title: string, + description: string, +) { + return scoreRoutingLanguageFeatures( + model, + extractRoutingLanguageFeatures(title, description), + ); +} diff --git a/runtime/story-route.ts b/runtime/story-route.ts index ac45afb..54773b5 100644 --- a/runtime/story-route.ts +++ b/runtime/story-route.ts @@ -1,4 +1,4 @@ -import { open } from "node:fs/promises"; +import { open, stat } from "node:fs/promises"; import { join } from "node:path"; import type { Evidence, @@ -12,25 +12,66 @@ import { loadRoutingCalibration, type RoutingCalibration, } from "./routing-calibration"; +import { + MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES, + loadRoutingLanguageModel, + type RoutingLanguageModel, +} from "./routing-language-model"; -export async function readRoutingCalibration(dataDir: string) { +async function readSnapshot( + path: string, + byteLimit: number, + load: (value: unknown) => T | undefined, +): Promise { try { - const file = await open(join(dataDir, "routing-calibration.json"), "r"); + const file = await open(path, "r"); try { const info = await file.stat(); - if (!info.isFile() || !info.size || info.size > 1_000_000) return; + if (!info.isFile() || !info.size || info.size > byteLimit) return; const buffer = Buffer.alloc(info.size + 1); const { bytesRead } = await file.read(buffer); if (bytesRead === info.size) - return loadRoutingCalibration( - JSON.parse(buffer.toString("utf8", 0, bytesRead)), - ); + return load(JSON.parse(buffer.toString("utf8", 0, bytesRead))); } finally { await file.close(); } } catch { - // An optional local calibration snapshot must never block a story. + // A missing or invalid optional snapshot must never block a story. + } +} + +export function readRoutingCalibration(dataDir: string) { + return readSnapshot( + join(dataDir, "routing-calibration.json"), + 1_000_000, + loadRoutingCalibration, + ); +} + +const languageByteLimit = MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES; +let languageCache: + | { + path: string; + stamp: string; + loading: Promise; + } + | undefined; + +export async function readRoutingLanguage(dataDir: string) { + const path = join(dataDir, "routing-language.json"); + const info = await stat(path, { bigint: true }).catch(() => undefined); + if (!info?.isFile() || info.size < 1n || info.size > languageByteLimit) { + if (languageCache?.path === path) languageCache = undefined; + return; } + const stamp = `${info.ino}:${info.size}:${info.ctimeNs}:${info.mtimeNs}`; + if (languageCache?.path !== path || languageCache.stamp !== stamp) + languageCache = { + path, + stamp, + loading: readSnapshot(path, languageByteLimit, loadRoutingLanguageModel), + }; + return languageCache.loading; } /** @@ -44,6 +85,7 @@ export function planDefinedStory( runtimes: HarnessRuntime[], state: AppState, calibration?: RoutingCalibration, + languageModel?: RoutingLanguageModel, ) { return planRoute( task, @@ -51,5 +93,6 @@ export function planDefinedStory( connectedRuntimes(state, runtimes), state.settings, calibration, + languageModel, ); } diff --git a/runtime/workers.ts b/runtime/workers.ts index 054f569..26cb089 100644 --- a/runtime/workers.ts +++ b/runtime/workers.ts @@ -27,7 +27,7 @@ import { commandIdentity } from "./commands"; import type { MemtraceEngine } from "./memtrace"; import { discoverHarnesses } from "./catalog"; import { assignedHarness, planRoute } from "./router"; -import { readRoutingCalibration } from "./story-route"; +import { readRoutingCalibration, readRoutingLanguage } from "./story-route"; import { assertWorkerConnected, connectedRuntimes } from "./worker-connections"; import { EpicWorkspace } from "./epic-workspace"; import { epicAnalysisProject } from "./epic-checkout"; @@ -826,10 +826,11 @@ export class WorkerManager { await progress("Measuring task scope and checking available workers"); const workspace = task.run.workspace!; const preferred = assignedHarness(task, permissionSettings); - const [evidence, catalog, calibration, previousSessionId] = await Promise.all([ + const [evidence, catalog, calibration, languageModel, previousSessionId] = await Promise.all([ this.engine.qualify(analysisProject, task), this.catalog(preferred), readRoutingCalibration(this.dataDir), + readRoutingLanguage(this.dataDir), previousProvider && (!preferred || preferred === previousProvider.harness) ? resumableProviderSession(previousProvider, { ...task, harness: previousProvider.harness }, workspace) : undefined, @@ -863,6 +864,7 @@ export class WorkerManager { pool, permissionSettings, calibration, + languageModel, ); if (canContinue && !preferred) task.route.reasons.push("Continuing this story’s verified local provider conversation."); diff --git a/scripts/routing-language-benchmark.ts b/scripts/routing-language-benchmark.ts new file mode 100644 index 0000000..9dbd7d6 --- /dev/null +++ b/scripts/routing-language-benchmark.ts @@ -0,0 +1,236 @@ +import { readFile, stat } from "node:fs/promises"; +import { release } from "node:os"; +import { performance } from "node:perf_hooks"; +import { analyzeRoutingIntent } from "../runtime/routing-intent"; +import { + createRoutingLanguageSnapshot, + extractRoutingLanguageFeatures, + loadRoutingLanguageModel, + MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES, + MAX_ROUTING_LANGUAGE_WEIGHTS, + RUNTIME_LANGUAGE_FEATURE_COUNT, + routingLanguageKinds, + scoreRoutingLanguageFeatures, +} from "../runtime/routing-language-model"; + +const brief = [ + { + title: "Preserve the list selection on refresh", + description: + "When I refresh the board, my selected item disappears. Keep the public API unchanged. Add a regression test around `src/components/List.tsx:20`.", + }, + { + title: "Where is the request cancellation handled?", + description: + "Walk through the worker lifecycle and explain the timeouts. Do not change any files.", + }, + { + title: "Pull request validation in the background", + description: + "Refactor the status check so it can run without blocking. Rename the private helper `resolveStatus` to make it clearer.", + }, + { + title: "Setup stalls", + description: + "On a clean install the first connection says `socket timeout`. Research how long the handshake should take and propose acceptance criteria.", + }, +]; +const adjectives = [ + "isolated", + "parallel", + "initial", + "updated", + "archived", + "concurrent", + "visible", + "periodic", + "stale", + "persisted", + "readable", + "restored", + "focused", + "ephemeral", + "bounded", + "synthesized", + "aggregated", + "selected", + "historical", + "nested", + "scheduled", + "versioned", +]; +const nouns = [ + "session", + "workspace", + "checkout", + "story", + "terminal", + "snapshot", + "reference", + "plan", + "handoff", + "report", + "conversation", + "metadata", + "transcript", + "worker", + "artifact", + "fallback", + "request", + "task", + "dependency", + "module", +]; +const longBrief = { + title: "Reconcile worker and project state across desktop restart", + description: adjectives + .flatMap((adjective) => + nouns.map((noun) => `verify the ${adjective} ${noun}`), + ) + .join(". ") + .slice(0, 6000), +}; + +function syntheticSnapshot() { + // Populate the size limit and force representative matching lookups. + // These artificial parameters are for timing only. + const used = new Set( + [...brief, longBrief].flatMap(({ title, description }) => + extractRoutingLanguageFeatures(title, description), + ), + ); + const features = [...used].slice(0, MAX_ROUTING_LANGUAGE_WEIGHTS); + for ( + let index = 0; + features.length < MAX_ROUTING_LANGUAGE_WEIGHTS && + index < RUNTIME_LANGUAGE_FEATURE_COUNT; + index++ + ) + if (!used.has(index)) features.push(index); + return createRoutingLanguageSnapshot( + routingLanguageKinds.map((kind, label) => ({ + kind, + threshold: 0.8, + minFeatures: 2, + bias: (label - 3) / 12, + weights: features.map((feature, index) => [ + feature, + (((index + label) % 2 ? 1 : -1) * ((index % 7) + 1)) / 100, + ]), + })), + ); +} + +function collectGarbage() { + if (global.gc) for (let i = 0; i < 3; i++) global.gc(); +} + +function latency(samples: number[]) { + samples.sort((a, b) => a - b); + const percentile = (fraction: number) => + Number(samples[Math.ceil(samples.length * fraction) - 1].toFixed(4)); + return { + iterations: samples.length, + p50Ms: percentile(0.5), + p95Ms: percentile(0.95), + p99Ms: percentile(0.99), + }; +} + +if (process.argv.length > 3) + throw Error( + "Usage: node --expose-gc --import tsx scripts/routing-language-benchmark.ts [model.json]", + ); +const path = process.argv[2]; +if (path) { + const info = await stat(path); + if (!info.isFile() || info.size > MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES) + throw Error( + `Use a model snapshot of at most ${MAX_ROUTING_LANGUAGE_SNAPSHOT_BYTES / 1024} KiB.`, + ); +} +const archive = path + ? await readFile(path, "utf8") + : JSON.stringify(syntheticSnapshot()); +collectGarbage(); +const before = process.memoryUsage(); +const start = performance.now(); +const model = loadRoutingLanguageModel(JSON.parse(archive)); +const loadMs = Number((performance.now() - start).toFixed(3)); +if (!model) + throw Error("The routing language snapshot did not pass runtime validation."); +collectGarbage(); +const after = process.memoryUsage(); + +function sample(inputs: typeof brief, rounds: number) { + const rules: number[] = [], + featuresOnly: number[] = [], + inference: number[] = []; + const scoredFeatures = inputs.map(({ title, description }) => + extractRoutingLanguageFeatures(title, description), + ); + function measure(fn: () => T, samples: number[], collecting: boolean) { + const start = performance.now(); + const result = fn(); + if (collecting) samples.push(performance.now() - start); + return result; + } + for (let index = 0; index < 500 + rounds; index++) { + const input = inputs[index % inputs.length]; + const collecting = index >= 500; + measure(() => analyzeRoutingIntent(input), rules, collecting); + measure( + () => extractRoutingLanguageFeatures(input.title, input.description), + featuresOnly, + collecting, + ); + measure( + () => + scoreRoutingLanguageFeatures( + model!, + scoredFeatures[index % inputs.length], + ), + inference, + collecting, + ); + } + const perPass = featuresOnly.map( + (duration, index) => duration + inference[index], + ); + return { + rules: latency(rules), + additionalFeatures: latency(featuresOnly), + additionalScoring: latency(inference), + additionalClassifier: latency(perPass), + maxObservedFeatures: Math.max( + ...scoredFeatures.map((features) => features.length), + ), + }; +} + +const deltaKiB = (key: keyof NodeJS.MemoryUsage) => + Number(((after[key] - before[key]) / 1024).toFixed(1)); +console.log( + JSON.stringify( + { + platform: `${process.platform} ${process.arch} ${release()}`, + node: process.version, + architecture: path + ? "provided snapshot" + : "synthetic maximum-size weights", + snapshotBytes: Buffer.byteLength(archive), + parseAndValidateMs: loadMs, + retainedMemoryKiB: global.gc + ? { + heapUsed: deltaKiB("heapUsed"), + arrayBuffers: deltaKiB("arrayBuffers"), + rss: deltaKiB("rss"), + } + : null, + brief: sample(brief, 3000), + longBrief: sample([longBrief], 1500), + }, + null, + 2, + ), +); diff --git a/scripts/routing-language-train.ts b/scripts/routing-language-train.ts new file mode 100644 index 0000000..7ac8f5e --- /dev/null +++ b/scripts/routing-language-train.ts @@ -0,0 +1,322 @@ +import { readFile, stat, writeFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { z } from "zod"; +import { analyzeRoutingIntent } from "../runtime/routing-intent"; +import { + createRoutingLanguageSnapshot, + extractRoutingLanguageFeatures, + loadRoutingLanguageModel, + MAX_ROUTING_LANGUAGE_WEIGHTS, + RUNTIME_LANGUAGE_FEATURE_COUNT, + routingLanguageKinds, + scoreRoutingLanguageFeatures, + type RoutingLanguageKind, + type RoutingLanguageLabel, + type RoutingLanguageModel, +} from "../runtime/routing-language-model"; + +const id = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/); +const maxTrainingBytes = 32 * 1024 * 1024; +const minFeatures = 2; +const thresholdOptions = [0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]; +const routingLanguageCorpusSchema = z.strictObject({ + version: z.literal(1), + calibrationRepoIds: z.array(id).min(1).max(1000), + heldOutRepoIds: z.array(id).min(1).max(1000), + stories: z + .array( + z.strictObject({ + repoId: id, + storyId: id, + title: z.string().trim().min(1).max(500), + description: z.string().max(6000), + kinds: z + .array(z.enum(routingLanguageKinds)) + .max(routingLanguageKinds.length), + }), + ) + .min(1) + .max(10000), +}); + +type Story = z.infer["stories"][number]; +type Example = Story & { features: number[] }; + +const compare = (left: string, right: string) => + left < right ? -1 : left > right ? 1 : 0; + +function splitCorpus(raw: unknown) { + const parsed = routingLanguageCorpusSchema.safeParse(raw); + if (!parsed.success) { + const fields = parsed.error.issues + .slice(0, 10) + .map((issue) => issue.path.join(".")); + throw Error( + `Invalid routing language corpus fields: ${fields.join(", ") || "input"}`, + ); + } + const { stories, calibrationRepoIds, heldOutRepoIds } = parsed.data; + const calibrationRepos = new Set(calibrationRepoIds); + const heldOutRepos = new Set(heldOutRepoIds); + const repos = new Set(stories.map((story) => story.repoId)); + if ( + calibrationRepos.size !== calibrationRepoIds.length || + heldOutRepos.size !== heldOutRepoIds.length + ) + throw Error("Duplicate repositories in the corpus partition list."); + if (heldOutRepoIds.some((id) => calibrationRepos.has(id))) + throw Error("Calibration and held-out repositories must be disjoint."); + if ([...calibrationRepos, ...heldOutRepos].some((id) => !repos.has(id))) + throw Error( + "Every declared calibration and held-out repository needs labeled stories.", + ); + + const train: Example[] = [], + calibration: Example[] = [], + heldOut: Example[] = []; + const known = new Set(); + for (const story of stories.sort( + (a, b) => compare(a.repoId, b.repoId) || compare(a.storyId, b.storyId), + )) { + const key = `${story.repoId}/${story.storyId}`; + if (known.has(key)) throw Error("Duplicate labeled story."); + if (new Set(story.kinds).size !== story.kinds.length) + throw Error("Each intent label may appear only once per story."); + known.add(key); + const entry = { + ...story, + features: extractRoutingLanguageFeatures(story.title, story.description), + }; + const split = calibrationRepos.has(story.repoId) + ? calibration + : heldOutRepos.has(story.repoId) + ? heldOut + : train; + split.push(entry); + } + if (!train.length) + throw Error( + "The corpus needs training stories outside the calibration and held-out repositories.", + ); + return { train, calibration, heldOut }; +} + +// One binary logistic regression per label permits independent requests in one +// brief. Full-batch AdaGrad plus a fixed story order makes the fit reproducible. +function fitLabel( + kind: RoutingLanguageKind, + examples: Example[], +): RoutingLanguageLabel | undefined { + const positives = examples.reduce( + (count, row) => count + Number(row.kinds.includes(kind)), + 0, + ); + const negatives = examples.length - positives; + if (positives < 2 || negatives < 2) return; + + const values = new Float64Array(RUNTIME_LANGUAGE_FEATURE_COUNT); + const gradients = new Float64Array(values.length); + const squaredGradients = new Float64Array(values.length); + let bias = Math.log((positives + 1) / (negatives + 1)); + let squaredBiasGradient = 0; + const target = examples.map((row) => Number(row.kinds.includes(kind))); + const inverseCount = 1 / examples.length; + for (let epoch = 0; epoch < 48; epoch++) { + gradients.fill(0); + let biasGradient = 0; + for (const [index, row] of examples.entries()) { + let logit = bias; + for (const feature of row.features) logit += values[feature]; + const error = (1 / (1 + Math.exp(-logit)) - target[index]) * inverseCount; + biasGradient += error; + for (const feature of row.features) gradients[feature] += error; + } + squaredBiasGradient += biasGradient ** 2; + bias -= (0.16 * biasGradient) / Math.sqrt(squaredBiasGradient + 1e-8); + for (let index = 0; index < values.length; index++) { + const gradient = gradients[index] + 0.002 * values[index]; + squaredGradients[index] += gradient ** 2; + values[index] -= + (0.16 * gradient) / Math.sqrt(squaredGradients[index] + 1e-8); + } + } + + const weights: RoutingLanguageLabel["weights"] = []; + for (const [feature, weight] of values.entries()) + if (Math.abs(weight) >= 0.0001) + weights.push([feature, Math.fround(weight)]); + weights.sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]) || a[0] - b[0]); + const retained = weights.slice(0, MAX_ROUTING_LANGUAGE_WEIGHTS); + if (retained.length) + return { + kind, + bias: Math.fround(bias), + weights: retained, + threshold: 0.55, + minFeatures, + }; +} + +const counts = (rows: Example[]) => ({ + stories: rows.length, + repositories: new Set(rows.map((row) => row.repoId)).size, +}); + +function predictedKinds(sample: Example, model?: RoutingLanguageModel) { + return analyzeRoutingIntent(sample, model).signals.kinds.filter( + (kind) => kind !== "unknown", + ); +} + +function evaluate( + examples: Example[], + predict: (sample: Example) => readonly RoutingLanguageKind[], +) { + const summary = routingLanguageKinds.map((kind) => ({ + kind, + truePositive: 0, + falsePositive: 0, + falseNegative: 0, + })); + let abstained = 0, + exact = 0; + for (const example of examples) { + const guesses = predict(example); + if (!guesses.length) abstained++; + if ( + guesses.length === example.kinds.length && + guesses.every((kind) => example.kinds.includes(kind)) + ) + exact++; + for (const label of summary) { + const picked = guesses.includes(label.kind); + const desired = example.kinds.includes(label.kind); + if (picked && desired) label.truePositive++; + if (picked && !desired) label.falsePositive++; + if (!picked && desired) label.falseNegative++; + } + } + return { + ...counts(examples), + coverage: examples.length ? 1 - abstained / examples.length : null, + abstained, + exactStoryMatch: examples.length ? exact / examples.length : null, + labels: summary.map((label) => { + const picked = label.truePositive + label.falsePositive; + const desired = label.truePositive + label.falseNegative; + return { + ...label, + precision: picked ? label.truePositive / picked : null, + recall: desired ? label.truePositive / desired : null, + }; + }), + }; +} + +export function trainRoutingLanguage(raw: unknown) { + const { train, calibration, heldOut } = splitCorpus(raw); + const fits = routingLanguageKinds + .map((kind) => fitLabel(kind, train)) + .filter((label) => label !== undefined); + const provisional = fits.length + ? loadRoutingLanguageModel(createRoutingLanguageSnapshot(fits)) + : undefined; + if (!provisional) + throw Error( + "No intent had enough positive and negative training examples.", + ); + // At runtime the learned model is called only for briefs the rules leave + // unclassified. Fit confidence thresholds on those briefs as well. + const observed = calibration + .filter((row) => !predictedKinds(row).length) + .map((row) => ({ + row, + scores: scoreRoutingLanguageFeatures(provisional, row.features).scores, + })); + const labels: RoutingLanguageLabel[] = []; + const calibrationEvidence = []; + for (const fit of fits) { + // Select the broadest supported threshold, using calibration repositories + // only. Held-out labels never influence weights or threshold selection. + for (const threshold of thresholdOptions) { + const selected = observed.filter(({ scores }) => + scores.some( + (score) => + score.kind === fit.kind && + score.probability >= threshold && + score.matchedFeatures >= minFeatures && + score.supportingFeatures > 0, + ), + ); + if (selected.length < 12) continue; + const repositories = new Set(selected.map(({ row }) => row.repoId)).size; + const correct = selected.filter(({ row }) => + row.kinds.includes(fit.kind), + ).length; + if (repositories < 2 || correct / selected.length < 0.9) continue; + labels.push({ ...fit, threshold }); + calibrationEvidence.push({ + kind: fit.kind, + threshold, + repositories, + selected: selected.length, + correct, + }); + break; + } + } + if (!labels.length) + throw Error( + "No intent met the calibration evidence threshold. No model was produced.", + ); + const snapshot = createRoutingLanguageSnapshot(labels); + const model = loadRoutingLanguageModel(snapshot); + if (!model) + throw Error("The trained language model did not pass runtime validation."); + const heldOutFallback = heldOut.filter((row) => !predictedKinds(row).length); + return { + snapshot, + report: { + train: counts(train), + calibration: { + ...counts(calibration), + fallbackEligible: observed.length, + evidence: calibrationEvidence, + }, + heldOut: { + learnedOnFallback: evaluate( + heldOutFallback, + (sample) => + scoreRoutingLanguageFeatures(model, sample.features).accepted, + ), + combined: evaluate(heldOut, (sample) => predictedKinds(sample, model)), + rules: evaluate(heldOut, (sample) => predictedKinds(sample)), + }, + omittedLabels: routingLanguageKinds.filter( + (kind) => !labels.some((label) => label.kind === kind), + ), + }, + }; +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + if (process.argv.length !== 4) + throw Error( + "Usage: node --import tsx scripts/routing-language-train.ts ", + ); + const [input, output] = process.argv.slice(2); + const inputFile = await stat(input); + if (!inputFile.isFile() || inputFile.size > maxTrainingBytes) + throw Error("Use a labeled-story corpus file of at most 32 MiB."); + const { snapshot, report } = trainRoutingLanguage( + JSON.parse(await readFile(input, "utf8")), + ); + await writeFile(output, JSON.stringify(snapshot), { + encoding: "utf8", + flag: "wx", + }); + console.log(JSON.stringify({ digest: snapshot.digest, ...report }, null, 2)); +} diff --git a/src/routing-signals.ts b/src/routing-signals.ts index 82d7978..270c3b4 100644 --- a/src/routing-signals.ts +++ b/src/routing-signals.ts @@ -15,4 +15,10 @@ export interface RoutingRequestSignals { fileScopeOnly: boolean; preserveBehavior: boolean; publicContract: "change" | "preserve" | "unspecified"; + /** Local classification evidence. Prompt text and feature values stay out of the route. */ + language?: { + digest: string; + outcome: "classified" | "abstained"; + scores: { kind: Exclude; score: number }[]; + }; } diff --git a/src/shared.ts b/src/shared.ts index a2ed44b..e0b0ee9 100644 --- a/src/shared.ts +++ b/src/shared.ts @@ -68,7 +68,7 @@ export interface HarnessRuntime { note?: string; } export interface RouteDecision { - policyVersion: "memcode-envelope-v2" | "memcode-evidence-v3"; + policyVersion: "memcode-envelope-v2" | "memcode-evidence-v3" | "memcode-evidence-v4"; tier: ModelTier; harness: Harness; model: string; @@ -96,6 +96,7 @@ export interface RouteDecision { cognitive: number | null; cyclomatic: number | null; nesting: number | null; + maintainability?: { lowest: number; measuredSymbols: number }; affected: number | null; processes: number | null; moduleRoots: number; @@ -167,6 +168,8 @@ export interface Evidence { cognitive?: number; cyclomatic?: number; nesting?: number; + /** Native AST index for this function, on a verified graph publication. */ + maintainabilityIndex?: number; metricSource?: "ast" | "estimated"; }>; affected?: number; diff --git a/tests/routing-calibration.test.ts b/tests/routing-calibration.test.ts index 4458034..6266079 100644 --- a/tests/routing-calibration.test.ts +++ b/tests/routing-calibration.test.ts @@ -105,6 +105,14 @@ test("calibration is input-order stable, excludes held-out repositories, and cho ]), [], ); + assert.deepEqual( + estimateRoutingCandidates(calibration, { ...cohort, languageModelDigest: "a".repeat(64) }, [cheap]), + [], + ); + assert.deepEqual( + estimateRoutingCandidates(calibration, { ...cohort, lowMaintainability: true }, [cheap]), + [], + ); }); test("missing proof and pending reviews remain unresolved, while failures and observed fallbacks count against first-pass acceptance", () => { diff --git a/tests/routing-language-model.test.ts b/tests/routing-language-model.test.ts new file mode 100644 index 0000000..d6f0f20 --- /dev/null +++ b/tests/routing-language-model.test.ts @@ -0,0 +1,171 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + createRoutingLanguageSnapshot, + extractRoutingLanguageFeatures, + loadRoutingLanguageModel, + MAX_ROUTING_LANGUAGE_FEATURES, + predictRoutingLanguage, + RUNTIME_LANGUAGE_FEATURE_COUNT, + scoreRoutingLanguageFeatures, + type RoutingLanguageLabel, +} from "../runtime/routing-language-model"; + +const label: RoutingLanguageLabel = { + kind: "fix", + bias: -1, + threshold: 0.75, + minFeatures: 2, + weights: [ + [2, 1.25], + [123, 1.25], + [101, -3], + ], +}; + +test("language features are normalized, content-masked and capped", () => { + assert.deepEqual( + extractRoutingLanguageFeatures( + "Add `CustomerId`", + "Check src/internal.ts:55", + ), + extractRoutingLanguageFeatures( + "add `OtherId`", + "check resources\\private.py:24", + ), + ); + assert.deepEqual( + extractRoutingLanguageFeatures( + "Prep WORK", + "open https://example.com/path", + ), + extractRoutingLanguageFeatures( + "prep work", + "open https://others.dev/local", + ), + ); + assert.deepEqual( + extractRoutingLanguageFeatures( + "Investigate", + "line\n```\nlarge ignored span\n```", + ), + extractRoutingLanguageFeatures("investigate", "line"), + ); + const varied = [ + "alternating generators become moderately expensive", + "plausible compatibility diagnosis started linguistically", + "normalization pipeline reproduces identifier structure", + ].join(" "); + const indices = extractRoutingLanguageFeatures( + varied.repeat(500), + varied.repeat(800), + ); + assert.ok(indices.length <= MAX_ROUTING_LANGUAGE_FEATURES); + assert.equal(new Set(indices).size, indices.length); + assert.ok( + indices.every( + (index) => index >= 0 && index < RUNTIME_LANGUAGE_FEATURE_COUNT, + ), + ); + assert.ok( + indices.every( + (index, offset) => offset === 0 || index > indices[offset - 1], + ), + ); +}); + +test("snapshot canonicalization is stable and packed weights reproduce the expected logits", () => { + const another: RoutingLanguageLabel = { + ...label, + kind: "test", + threshold: 0.9, + }; + const snapshot = createRoutingLanguageSnapshot([label, another]); + const reordered = createRoutingLanguageSnapshot([ + another, + { ...label, weights: [...label.weights].reverse() }, + ]); + assert.equal(reordered.digest, snapshot.digest); + const model = loadRoutingLanguageModel(JSON.parse(JSON.stringify(snapshot))); + assert.ok(model); + assert.equal( + model.labels.reduce((sum, item) => sum + item.weights.byteLength, 0), + 128 * 1024, + ); + const result = scoreRoutingLanguageFeatures(model, [2, 123]); + assert.deepEqual(result.accepted, ["fix"]); + assert.deepEqual( + result.scores.map(({ probability }) => probability), + [1 / (1 + Math.exp(-1.5)), 1 / (1 + Math.exp(-1.5))], + ); + assert.deepEqual( + scoreRoutingLanguageFeatures(model, [2, 101, 123]).accepted, + [], + ); +}); + +test("evidence limits abstain with sparse matches, negative-only matches or no words", () => { + const model = loadRoutingLanguageModel( + createRoutingLanguageSnapshot([ + { + kind: "research", + bias: 12, + threshold: 0.75, + minFeatures: 2, + weights: [ + [2, -0.1], + [123, -0.1], + [127, 2], + ], + }, + ]), + ); + assert.ok(model); + assert.deepEqual(scoreRoutingLanguageFeatures(model, [2, 123]).accepted, []); + assert.deepEqual(scoreRoutingLanguageFeatures(model, [127]).accepted, []); + assert.deepEqual(predictRoutingLanguage(model, "", "").accepted, []); + const matched = scoreRoutingLanguageFeatures(model, [2, 123, 127]); + assert.deepEqual(matched.accepted, ["research"]); + assert.equal(matched.scores[0].supportingFeatures, 1); +}); + +test("tampered, duplicate and malformed coefficients fail profile validation", () => { + const snapshot = createRoutingLanguageSnapshot([label]); + assert.equal( + loadRoutingLanguageModel({ ...snapshot, runtime: "invalid" }), + undefined, + ); + assert.equal( + loadRoutingLanguageModel({ + ...snapshot, + labels: [{ ...label, threshold: 0.9 }], + }), + undefined, + ); + assert.equal( + loadRoutingLanguageModel({ + ...snapshot, + labels: [ + { ...label, weights: [[RUNTIME_LANGUAGE_FEATURE_COUNT + 1, 3]] }, + ], + }), + undefined, + ); + assert.throws( + () => createRoutingLanguageSnapshot([label, label]), + /only once/, + ); + assert.throws( + () => + createRoutingLanguageSnapshot([ + { + ...label, + weights: [ + [1, 1.5], + [1, 2], + ], + }, + ]), + /only once/, + ); +}); diff --git a/tests/routing-language-training.test.ts b/tests/routing-language-training.test.ts new file mode 100644 index 0000000..c6a654c --- /dev/null +++ b/tests/routing-language-training.test.ts @@ -0,0 +1,91 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { loadRoutingLanguageModel } from "../runtime/routing-language-model"; +import { trainRoutingLanguage } from "../scripts/routing-language-train"; + +function corpus() { + const stories = [ + "train-a", + "train-b", + "calibrate-a", + "calibrate-b", + "held-a", + ].flatMap((repoId) => + Array.from({ length: 24 }, (_, index) => ({ + repoId, + storyId: `story-${index}`, + title: + index % 2 + ? "Scheduling helper cleanup" + : "A walkthrough of retry ordering", + description: + index % 2 + ? "The scheduling code needs a cleanup of duplicated shared functions with the same behavior." + : "I would appreciate a clear walkthrough of the sequence of retries.", + kinds: index % 2 ? ["refactor"] : ["explain"], + })), + ); + return { + version: 1, + calibrationRepoIds: ["calibrate-a", "calibrate-b"], + heldOutRepoIds: ["held-a"], + stories, + }; +} + +test("training is reproducible and held-out labels do not tune the snapshot", () => { + const source = corpus(); + const first = trainRoutingLanguage(source); + assert.ok(loadRoutingLanguageModel(first.snapshot)); + assert.deepEqual(first.report.train, { stories: 48, repositories: 2 }); + assert.equal(first.report.calibration.stories, 48); + assert.equal(first.report.calibration.fallbackEligible, 48); + assert.equal(first.report.heldOut.learnedOnFallback.stories, 24); + assert.equal(first.report.heldOut.combined.exactStoryMatch, 1); + assert.equal(first.report.heldOut.rules.abstained, 24); + + const reordered = trainRoutingLanguage({ + ...source, + stories: [...source.stories].reverse(), + }); + assert.deepEqual(first, reordered); + const changed = trainRoutingLanguage({ + ...source, + stories: source.stories.map((example) => + example.repoId === "held-a" ? { ...example, kinds: [] } : example, + ), + }); + assert.equal(changed.snapshot.digest, first.snapshot.digest); + assert.equal(changed.report.heldOut.combined.exactStoryMatch, 0); +}); + +test("partitions are by repository, disjoint, and reject duplicate labels and stories", () => { + const source = corpus(); + assert.throws( + () => trainRoutingLanguage({ ...source, heldOutRepoIds: ["calibrate-a"] }), + /disjoint/, + ); + assert.throws( + () => trainRoutingLanguage({ ...source, heldOutRepoIds: ["unknown"] }), + /labeled stories/, + ); + assert.throws( + () => + trainRoutingLanguage({ + ...source, + stories: [...source.stories, source.stories[0]], + }), + /Duplicate labeled story/, + ); + assert.throws( + () => + trainRoutingLanguage({ + ...source, + stories: source.stories.map((story) => ({ + ...story, + kinds: ["explain", "explain"], + })), + }), + /once per story/, + ); +}); diff --git a/tests/routing-qualification.test.ts b/tests/routing-qualification.test.ts index 8a447ae..65263fb 100644 --- a/tests/routing-qualification.test.ts +++ b/tests/routing-qualification.test.ts @@ -140,6 +140,9 @@ async function fixture(t: TestContext, changePublication = false) { cognitive_complexity: 4, complexity: 2, max_nesting: 1, + quality_metrics_v: 1, + maintainability_index: + args.function_name === "loadBoard" ? 0 : 72.4, }, }; if (tool === "get_impact") { @@ -173,6 +176,16 @@ test("exact line and symbol qualification deduplicates callers, files and flows" evidence.symbols.map((symbol) => symbol.name), ["loadBoard", "saveBoard"], ); + assert.deepEqual( + evidence.symbols.map((symbol) => symbol.maintainabilityIndex), + [0, 72.4], + ); + assert.equal( + requests.filter( + (request) => request.name === "get_function_quality_metrics", + ).length, + 2, + ); assert.deepEqual(evidence.impact, { targetCount: 2, observedTargets: 2, @@ -218,6 +231,65 @@ test("a mixed publication discards grouped impact and AST metrics", async (t) => assert.deepEqual(evidence.symbols, []); }); +test("invalid, estimated, or versionless maintainability stays unknown", async (t) => { + const { project, task, client } = await fixture(t); + for (const overrides of [ + { maintainability_index: 101 }, + { maintainability_index: undefined }, + { complexity_source: "estimated" }, + { quality_metrics_v: undefined }, + { node_id: "different-symbol" }, + ]) { + const evidence = await collectEvidence( + { + async call(checkout, name, args) { + const response = await client.call(checkout, name, args); + if (name !== "get_function_quality_metrics") return response; + return { + ...response, + function: { ...response.function, ...overrides }, + }; + }, + }, + project, + task, + ); + assert.equal(evidence.symbols.length, 2); + assert.ok( + evidence.symbols.every( + (symbol) => symbol.maintainabilityIndex === undefined, + ), + ); + } +}); + +test("a stale index excludes maintainability from both fresh reads and cached story evidence", async (t) => { + const { project, task, client } = await fixture(t); + const evidence = await collectEvidence(client, project, task); + const staleClient = { + async call(checkout: Project, name: string, args: Record) { + const response = await client.call(checkout, name, args); + return name === "get_query_revision" + ? { + ...response, + ready: false, + mismatched_files: 1, + mismatched_paths: ["src/board.ts"], + } + : response; + }, + }; + const reevaluated = await collectEvidence(staleClient, project, task); + assert.equal(reevaluated.state, "partial"); + assert.equal(reevaluated.symbols[0].cognitive, 4); + assert.equal(reevaluated.symbols[0].maintainabilityIndex, undefined); + const [refreshed] = await refreshEvidence(staleClient, project, [ + { ...task, evidence }, + ]); + assert.equal(refreshed.action, "stale"); + assert.equal(refreshed.evidence?.symbols[0].maintainabilityIndex, undefined); +}); + test("a changed work request refreshes evidence on the same checkout", async (t) => { const { project, task, client } = await fixture(t); const evidence = await collectEvidence(client, project, task); diff --git a/tests/routing.test.ts b/tests/routing.test.ts index 33cc746..e712939 100644 --- a/tests/routing.test.ts +++ b/tests/routing.test.ts @@ -7,6 +7,11 @@ import { routingInputs, } from "../runtime/router.ts"; import { compileRoutingCalibration } from "../runtime/routing-calibration.ts"; +import { + createRoutingLanguageSnapshot, + extractRoutingLanguageFeatures, + loadRoutingLanguageModel, +} from "../runtime/routing-language-model.ts"; import { cursorCatalog } from "../src/cursor-models.ts"; import { initialState } from "../src/seed.ts"; import type { Evidence, HarnessRuntime } from "../src/shared.ts"; @@ -42,6 +47,118 @@ export const catalog: HarnessRuntime[] = ["codex", "claude", "cursor"].map( }), ); +test("a native low maintainability score sets a one-time edit floor and zero remains visible", () => { + const { + tasks: [story], + settings, + } = initialState(); + const evidence = { + ...measured, + symbols: [{ ...measured.symbols[0], maintainabilityIndex: 0 }], + }; + const task = { + ...story, + assignment: "auto" as const, + title: "Fix rendering", + description: "Fix the card.", + }; + const route = planRoute(task, evidence, catalog, settings); + assert.equal(route.selection?.workTier, "balanced"); + assert.equal(route.selection?.impactTier, "fast"); + assert.deepEqual(route.inputs.maintainability, { + lowest: 0, + measuredSymbols: 1, + }); + const readOnly = planRoute( + { ...task, title: "Explain rendering", description: "" }, + evidence, + catalog, + settings, + ); + assert.equal(readOnly.selection?.workTier, "fast"); + assert.equal(readOnly.inputs.maintainability?.lowest, 0); + const alreadyComplex = { + ...evidence, + symbols: [{ ...evidence.symbols[0], cognitive: 120 }], + }; + assert.equal( + planRoute(task, alreadyComplex, catalog, settings).selection?.workTier, + "frontier", + ); + const invalid = { + ...evidence, + symbols: [{ ...evidence.symbols[0], maintainabilityIndex: -1 }], + }; + assert.equal( + planRoute(task, invalid, catalog, settings).inputs.maintainability, + undefined, + ); +}); + +test("local wording classifies ambiguous requests while explicit rules and impact remain authoritative", () => { + const { + tasks: [story], + settings, + } = initialState(); + const title = "Coverage for desktop cards"; + const description = + "Regression cases around the planner. Keep behavior unchanged."; + const weights: [number, number][] = extractRoutingLanguageFeatures( + title, + description, + ) + .slice(0, 4) + .map((index) => [index, 3]); + const snapshot = createRoutingLanguageSnapshot([ + { kind: "test", bias: -1, minFeatures: 2, threshold: 0.9, weights }, + ]); + const model = loadRoutingLanguageModel(snapshot); + assert.ok(model); + const task = { + ...story, + assignment: "auto" as const, + title, + description, + kind: "feature" as const, + }; + const baseline = planRoute(task, measured, catalog, settings); + const route = planRoute(task, measured, catalog, settings, undefined, model); + assert.equal(baseline.harness, "cursor"); + assert.equal(route.harness, "codex"); + assert.deepEqual(route.inputs.request?.kinds, ["test"]); + assert.equal(route.inputs.request?.preserveBehavior, true); + assert.equal(route.inputs.request?.language?.outcome, "classified"); + assert.equal(route.inputs.request?.language?.digest, snapshot.digest); + const explicit = planRoute( + { ...task, title: "Explain the cards" }, + measured, + catalog, + settings, + undefined, + model, + ); + assert.deepEqual(explicit.inputs.request?.kinds, ["explain"]); + assert.equal(explicit.inputs.request?.readOnly, true); + assert.equal(explicit.inputs.request?.language, undefined); + const readOnlyGuess = loadRoutingLanguageModel( + createRoutingLanguageSnapshot([ + { kind: "explain", bias: -1, minFeatures: 2, threshold: 0.9, weights }, + ]), + ); + assert.ok(readOnlyGuess); + const risky = planRoute( + task, + { ...measured, affected: 70 }, + catalog, + settings, + undefined, + readOnlyGuess, + ); + assert.deepEqual(risky.inputs.request?.kinds, ["explain"]); + assert.equal(risky.inputs.request?.readOnly, false); + assert.equal(risky.selection?.impactTier, "frontier"); +}); + test("story assignment and story model supersede the default harness's global pin", () => { const { tasks: [story], @@ -163,14 +280,12 @@ test("catalog fingerprint and effort remain stable across discovery ordering", ( efforts: ["high", "low"], })), })); - const reversed = [...withEfforts] - .reverse() - .map((runtime) => ({ - ...runtime, - models: [...runtime.models] - .reverse() - .map((model) => ({ ...model, efforts: [...model.efforts].reverse() })), - })); + const reversed = [...withEfforts].reverse().map((runtime) => ({ + ...runtime, + models: [...runtime.models] + .reverse() + .map((model) => ({ ...model, efforts: [...model.efforts].reverse() })), + })); const first = planRoute(task, measured, withEfforts, settings); const second = planRoute(task, measured, reversed, settings); assert.equal( diff --git a/tests/story-route.test.ts b/tests/story-route.test.ts index badf213..81de2e2 100644 --- a/tests/story-route.test.ts +++ b/tests/story-route.test.ts @@ -1,11 +1,15 @@ import { test, mock } from "node:test"; import assert from "node:assert/strict"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, rm, rmdir, unlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createRuntime } from "../runtime/app.ts"; import { MemtraceEngine } from "../runtime/memtrace.ts"; -import { planDefinedStory } from "../runtime/story-route.ts"; +import { planDefinedStory, readRoutingLanguage } from "../runtime/story-route.ts"; +import { + createRoutingLanguageSnapshot, + extractRoutingLanguageFeatures, +} from "../runtime/routing-language-model.ts"; import { initialState } from "../src/seed.ts"; import { harnessIds, type Evidence, type HarnessRuntime, type WorkItem } from "../src/shared.ts"; @@ -47,6 +51,29 @@ function connectedState(ids = catalog.map(runtime => runtime.id)) { return state; } +test("the optional local wording model is cached, reloaded on change, and discarded when invalid", async () => { + const dir = await mkdtemp(join(tmpdir(), "memcode-routing-language-")); + const path = join(dir, "routing-language.json"); + const label = { kind: "test" as const, bias: -1, minFeatures: 1, threshold: 0.9, weights: [[1, 4]] as [number, number][] }; + try { + assert.equal(await readRoutingLanguage(dir), undefined); + const first = createRoutingLanguageSnapshot([label]); + await writeFile(path, JSON.stringify(first)); + const [during, same] = await Promise.all([readRoutingLanguage(dir), readRoutingLanguage(dir)]); + assert.equal(during?.digest, first.digest); + assert.strictEqual(during, same); + assert.strictEqual(await readRoutingLanguage(dir), during); + const replacement = createRoutingLanguageSnapshot([{ ...label, kind: "rename" }]); + await writeFile(path, JSON.stringify(replacement)); + assert.equal((await readRoutingLanguage(dir))?.digest, replacement.digest); + await writeFile(path, "{"); + assert.equal(await readRoutingLanguage(dir), undefined); + } finally { + await unlink(path).catch(() => {}); + await rmdir(dir); + } +}); + test("every nonempty connection combination routes only within its approvals, independently of discovery order", () => { const all: HarnessRuntime[] = harnessIds.map(id => ({ id, name: id, available: true, path: "fixture", models: [{ id: id + "-default", label: id, source: "acp", isDefault: true, tier: "extreme" }] })); for (let mask = 1; mask < 1 << all.length; mask++) { @@ -150,6 +177,34 @@ test("defining a story records the assignee and leaves the worker idle", async ( assert.equal(stored.run.state, "idle"); assert.equal(stored.stage, "planned"); assert.equal(qualify.mock.callCount(), 1); + + const title = "Coverage for desktop cards"; + const description = "Regression cases around the planner. Keep behavior unchanged."; + const snapshot = createRoutingLanguageSnapshot([{ + kind: "test", + bias: -1, + minFeatures: 2, + threshold: 0.95, + weights: extractRoutingLanguageFeatures(title, description) + .slice(0, 4) + .map((index) => [index, 4]), + }]); + await writeFile(join(dir, "routing-language.json"), JSON.stringify(snapshot)); + const classified = (await runtime.request("task:create", { + projectId: project.id, title, description, + priority: "medium", harness: "codex", assignment: "auto", + })) as WorkItem; + const classifiedDeadline = Date.now() + 2000; + let classifiedStory = runtime.store.state.tasks.find((item) => item.id === classified.id); + while (!classifiedStory?.route && Date.now() < classifiedDeadline) { + await new Promise((resolve) => setTimeout(resolve, 20)); + classifiedStory = runtime.store.state.tasks.find((item) => item.id === classified.id); + } + assert.equal(classifiedStory?.route?.inputs.request?.language?.digest, snapshot.digest); + assert.deepEqual(classifiedStory?.route?.inputs.request?.kinds, ["test"]); + assert.equal(classifiedStory?.route?.harness, "codex"); + assert.equal(classifiedStory?.run.state, "idle"); + assert.equal(qualify.mock.callCount(), 2); } finally { qualify.mock.restore(); await runtime.close(); From 1c217762c5cf151b1244d408d827e4aa0eef8bfb Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:43:28 +0100 Subject: [PATCH 3/4] Stabilize Windows goal and runbook test fixtures [skip ci] --- tests/context-preparation.test.ts | 3 ++- tests/goal-update.test.ts | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/context-preparation.test.ts b/tests/context-preparation.test.ts index 8bb69cb..ea69e3d 100644 --- a/tests/context-preparation.test.ts +++ b/tests/context-preparation.test.ts @@ -159,11 +159,12 @@ async function preparingFixture() { (state.fleetDeclarations ?? []).filter((item) => !item.recordedAt).length, async cleanup() { await manager.close(); + await running; assert.ok( within(tmpdir(), root) && basename(root).startsWith("memcode-preparation-test-"), ); - await rm(root, { recursive: true, force: true }); + await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }, }; } diff --git a/tests/goal-update.test.ts b/tests/goal-update.test.ts index 655fd3a..1b9af94 100644 --- a/tests/goal-update.test.ts +++ b/tests/goal-update.test.ts @@ -83,7 +83,7 @@ test("updating a goal saves its work, brings in the newer dev and clears the war const result = await f.updates.updateFromBase("e1"); assert.deepEqual(result, { merged: true, savedWork: true }); assert.equal( - await readFile(join(f.goal, "news.ts"), "utf8"), + (await readFile(join(f.goal, "news.ts"), "utf8")).replaceAll("\r\n", "\n"), "export const fromDev = 1;\n", "the teammate's dev change is now in the goal", ); @@ -133,7 +133,7 @@ test("a conflicting update is undone, keeps the goal's work and names the files" ); assert.equal(await git(f.goal, ["status", "--porcelain"]), ""); assert.equal( - await readFile(join(f.goal, "app.ts"), "utf8"), + (await readFile(join(f.goal, "app.ts"), "utf8")).replaceAll("\r\n", "\n"), "export const version = 2;\n", "the goal's own change is kept", ); From 5c87e74f1e402678f61be41153249e0eecc3a7dc Mon Sep 17 00:00:00 2001 From: Alex Holmberg <113964069+Alex793x@users.noreply.github.com> Date: Sat, 21 Nov 2026 07:49:25 +0100 Subject: [PATCH 4/4] Exercise beta.20 startup and stabilize Windows follow-up fixtures [skip ci] --- scripts/tauri-smoke.mjs | 10 ++++- tests/queued-followups.test.ts | 77 ++++++++++++++++++++++++++++++---- 2 files changed, 78 insertions(+), 9 deletions(-) diff --git a/scripts/tauri-smoke.mjs b/scripts/tauri-smoke.mjs index bab40df..dcdde67 100644 --- a/scripts/tauri-smoke.mjs +++ b/scripts/tauri-smoke.mjs @@ -140,6 +140,14 @@ try { ); assert.ok(Array.isArray(result.state.projects)); await expect(page.locator(".app-shell")).toBeVisible({ timeout: 20000 }); + if (process.env.MEMCODE_TEST_BUNDLED_RUNTIME === "1") { + const explore = page.getByRole("button", { + name: "Explore without signing in for now", + exact: true, + }); + await expect(explore).toBeVisible(); + await explore.click(); + } if ( !result.state.onboarding || (result.state.onboarding.step === "welcome" && @@ -182,7 +190,7 @@ try { await productTour.getByRole("button", { name: "Back to Docs" }).click(); await page .getByRole("navigation", { name: "Guide topics" }) - .getByRole("button", { name: "Code review", exact: true }) + .getByRole("button", { name: "Review the work", exact: true }) .click(); const figure = page.getByRole("figure", { name: "Example task review" }); await figure.getByRole("button", { name: "Before & after" }).click(); diff --git a/tests/queued-followups.test.ts b/tests/queued-followups.test.ts index 8447cfe..e88da35 100644 --- a/tests/queued-followups.test.ts +++ b/tests/queued-followups.test.ts @@ -24,14 +24,30 @@ const note = (text: string): Message => ({ async function until( predicate: () => boolean | Promise, label: string, + diagnostics?: () => string, ) { const deadline = Date.now() + 15000; while (!(await predicate())) { - if (Date.now() >= deadline) throw Error("Timed out: " + label); + if (Date.now() >= deadline) + throw Error(`Timed out: ${label}${diagnostics ? `\n${diagnostics()}` : ""}`); await new Promise((resolve) => setTimeout(resolve, 15)); } } +function workerDiagnostics(task: WorkItem) { + return JSON.stringify({ + harness: task.harness, + state: task.run.state, + error: task.run.error, + activity: task.run.activity, + childOutput: task.messages + .filter((message) => message.role === "tool") + .slice(-3) + .map((message) => message.text.slice(-2000)), + followupStates: task.messages.map((message) => message.followupState).filter(Boolean), + }); +} + async function fixture( harnesses: Harness[] = ["codex"], options: { @@ -64,7 +80,51 @@ async function fixture( ]); await writeFile( stub, - `import{readFile,writeFile,mkdir,access,rename}from'node:fs/promises';import{join}from'node:path';const id=process.env.MEMCODE_TASK_ID,dir=join('.memcode','gates',id);await mkdir(dir,{recursive:true});const log=join(dir,'runs.json'),runs=JSON.parse(await readFile(log,'utf8').catch(()=>'[]'));let stdin='';for await(const data of process.stdin)stdin+=data;const prompt=stdin||await readFile(join('.memcode','workers',id,'brief.md'),'utf8');const index=runs.length+1;runs.push({index,prompt,at:Date.now()});await writeFile(log+'.tmp',JSON.stringify(runs));await rename(log+'.tmp',log);const release=join(dir,index+'.release');let ready=false;for(let n=0;n<1500;n++){try{await access(release);ready=true;break;}catch{}await new Promise(r=>setTimeout(r,10));}if(!ready)process.exit(8);console.log(JSON.stringify({type:'item.completed',item:{type:'agent_message',text:'Fixture pass '+index+' finished; no model ran.'}}));process.exit(${options.fail ? 7 : 0});`, + `import { readFile, writeFile, mkdir, access, rename } from 'node:fs/promises'; +import { join } from 'node:path'; +import { setTimeout as wait } from 'node:timers/promises'; +const id = process.env.MEMCODE_TASK_ID; +const dir = join('.memcode', 'gates', id); +await mkdir(dir, { recursive: true }); +const log = join(dir, 'runs.json'); +const runs = JSON.parse(await readFile(log, 'utf8').catch(() => '[]')); +let stdin = ''; +for await (const data of process.stdin) stdin += data; +const prompt = stdin || await readFile(join('.memcode', 'workers', id, 'brief.md'), 'utf8'); +const index = runs.length + 1; +runs.push({ index, prompt, at: Date.now() }); +const temporary = log + '.tmp'; +await writeFile(temporary, JSON.stringify(runs)); +// The test polls runs.json. Windows can refuse replacement until its read finishes. +const retryDelays = [25, 50, 100, 200, 400, 800, 1000]; +for (let attempt = 0; ; attempt++) { + try { + await rename(temporary, log); + break; + } catch (error) { + if (process.platform !== 'win32' || + !['EPERM', 'EACCES', 'EBUSY'].includes(error.code) || + attempt >= retryDelays.length) + throw error; + await wait(retryDelays[attempt]); + } +} +const release = join(dir, index + '.release'); +let ready = false; +for (let attempt = 0; attempt < 1500; attempt++) { + try { + await access(release); + ready = true; + break; + } catch {} + await wait(10); +} +if (!ready) process.exit(8); +console.log(JSON.stringify({ + type: 'item.completed', + item: { type: 'agent_message', text: 'Fixture pass ' + index + ' finished; no model ran.' }, +})); +process.exit(${options.fail ? 7 : 0});`, ); const project: Project = { id: "queue-project", @@ -265,11 +325,11 @@ test("a follow-up can reuse a verified older save, but never an unverified provi task.run.measurements = {modelIds: [], modelSource: source === "changed provider" ? "claude-assistant" : "codex-thread"}; if (source === "different checkout") task.run.workspace = join(f.root, "previous-repo"); f.enqueue(task, "Run the follow-up on the correct workspace."); - try { - await until(async () => (await f.runs(task)).length === 2, "queued pass started"); - } catch (cause) { - throw new Error(`Queued legacy follow-up (${source}) failed: ${JSON.stringify({ state: task.run.state, error: task.run.error, activity: task.run.activity })}`, { cause }); - } + await until( + async () => (await f.runs(task)).length === 2, + `queued pass started (${source})`, + () => workerDiagnostics(task), + ); assert.deepEqual(f.resumedSessions, [undefined, source === "matching legacy" ? "original-local-session" : undefined]); await f.release(task, 2); await until(() => task.run.state === "finished", "queued pass finished"); @@ -350,7 +410,8 @@ test("all three adapters automatically coalesce busy follow-ups after Fleet clea await f.release(task, 1); await until( async () => (await f.runs(task)).length === 2, - "automatic next pass", + `automatic next pass (${provider})`, + () => workerDiagnostics(task), ); const passes = await f.runs(task); assert.notEqual(task.run.workspace, f.repo);