Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 130 additions & 2 deletions docs/routing-measurement.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,136 @@ 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`.
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.

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.

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

Expand Down
10 changes: 10 additions & 0 deletions runtime/agents/calibrated-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { AgentSessionOptions } from "./types";

export function assertCalibratedConfiguration(
options: Pick<AgentSessionOptions, "calibratedModel" | "effort">,
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.");
}
11 changes: 8 additions & 3 deletions runtime/agents/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any>;
const bounded = (value: unknown, limit = 16000): string =>
Expand Down Expand Up @@ -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),
],
Expand Down Expand Up @@ -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({
Expand Down
1 change: 1 addition & 0 deletions runtime/agents/codex-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.`);
Expand Down
7 changes: 6 additions & 1 deletion runtime/agents/codex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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." });
Expand Down Expand Up @@ -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");
Expand Down
6 changes: 6 additions & 0 deletions runtime/agents/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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" &&
Expand Down
2 changes: 2 additions & 0 deletions runtime/agents/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
32 changes: 23 additions & 9 deletions runtime/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, readRoutingLanguage } from "./story-route";
import { qualificationRequestFingerprint } from "./qualification";
import { registerPlanning } from "./planning";
import { registerPlanningControls } from "./planning-controls";
import { ensureTaskEpic } from "./epic-workspace";
Expand Down Expand Up @@ -769,20 +770,33 @@ 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, 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);
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,
languageModel,
);
latest.harness = latest.route.harness;
latest.evidence = evidence;
latest.route = route;
latest.harness = route.harness;
latest.updatedAt = now();
await changed();
};
Expand Down
Loading