diff --git a/.github/workflows/nightly-production-probe.yml b/.github/workflows/nightly-production-probe.yml index 1b26be02..71bea34b 100644 --- a/.github/workflows/nightly-production-probe.yml +++ b/.github/workflows/nightly-production-probe.yml @@ -68,6 +68,7 @@ jobs: rm -f artifacts/model-fleet/model-fleet-probe.json rm -f artifacts/model-fleet/free-router-fleet-probe.json rm -f artifacts/model-fleet/free-router-structured-probe.json + rm -f artifacts/model-fleet/receipt-*.json rm -rf artifacts/close-all-gaps-20260722/acceptance/ui-qa - name: Set up Node.js uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 @@ -121,6 +122,17 @@ jobs: MODEL_FLEET_PROBE_URL: https://nodeslide.vercel.app/ MODEL_FLEET_PROBE_WORKFLOW_RUN_URL: ${{ steps.deployed.outputs.url }} run: npm run capture:free-router:structured:prod + - name: Capture the routed-executor split receipt for a manual operator probe + id: executor_split + if: always() && github.event_name == 'workflow_dispatch' + continue-on-error: true + env: + CONVEX_DEPLOY_KEY: ${{ secrets.CONVEX_DEPLOY_KEY }} + GITHUB_TOKEN: ${{ github.token }} + MODEL_FLEET_PROBE_COMMIT_SHA: ${{ steps.deployed.outputs.sha }} + MODEL_FLEET_PROBE_URL: https://nodeslide.vercel.app/ + MODEL_FLEET_PROBE_WORKFLOW_RUN_URL: ${{ steps.deployed.outputs.url }} + run: node scripts/capture-model-fleet-probe.mjs --function runExecutorSplit --schema nodeslide.executor-split-probe/v1 --output artifacts/model-fleet/receipt-${{ steps.deployed.outputs.sha }}.json - name: Capture the production UI QA matrix id: ui_qa if: always() && github.event_name == 'workflow_dispatch' @@ -153,6 +165,7 @@ jobs: artifacts/model-fleet/model-fleet-probe.json artifacts/model-fleet/free-router-fleet-probe.json artifacts/model-fleet/free-router-structured-probe.json + artifacts/model-fleet/receipt-*.json artifacts/close-all-gaps-20260722/acceptance/ui-qa if-no-files-found: warn include-hidden-files: false @@ -163,10 +176,11 @@ jobs: OFFERED_FLEET: ${{ steps.offered_fleet.outcome }} FREE_TEXT_FLEET: ${{ steps.free_text_fleet.outcome }} FREE_STRUCTURED_FLEET: ${{ steps.free_structured_fleet.outcome }} + EXECUTOR_SPLIT: ${{ steps.executor_split.outcome }} UI_QA: ${{ steps.ui_qa.outcome }} shell: bash run: | - for outcome in "$OFFERED_FLEET" "$FREE_TEXT_FLEET" "$FREE_STRUCTURED_FLEET" "$UI_QA"; do + for outcome in "$OFFERED_FLEET" "$FREE_TEXT_FLEET" "$FREE_STRUCTURED_FLEET" "$EXECUTOR_SPLIT" "$UI_QA"; do if [[ "$outcome" != "success" ]]; then echo "::error::At least one bounded production evidence matrix is incomplete." exit 1 diff --git a/.qa/models/claude-opus-5-5/benchmark-summary.md b/.qa/models/claude-opus-5-5/benchmark-summary.md new file mode 100644 index 00000000..8ef46900 --- /dev/null +++ b/.qa/models/claude-opus-5-5/benchmark-summary.md @@ -0,0 +1,13 @@ +# Claude Opus 5.5 benchmark summary + +Evidence: 0/0 evaluated runs across 0 briefs and 0 directions on deck-gym-v1. + +- Live routes: 0 +- Degraded routes: 0 +- Live claim gate: 0/0 +- Mean claim coverage: 0 +- Qualified score: 0 +- Estimated text overflows: 0 +- Export success: 0 + +These findings describe observed behavior only. Cognitive and tool-orchestration claims remain low confidence until plan and tool traces are captured. diff --git a/.qa/models/claude-opus-5-5/capability-card.yaml b/.qa/models/claude-opus-5-5/capability-card.yaml new file mode 100644 index 00000000..b88424f5 --- /dev/null +++ b/.qa/models/claude-opus-5-5/capability-card.yaml @@ -0,0 +1,37 @@ +schema_version: nodeslide.model-capability-card/v1 +profile_version: 1 +model: anthropic/claude-opus-5.5 +label: Claude Opus 5.5 +evidence_window: + attempted_runs: 0 + evaluated_runs: 0 + completed_exports: 0 + briefs: 0 + directions: 0 + harness_version: "deck-gym-v1" +observed_metrics: + live_routes: 0 + degraded_routes: 0 + live_claim_passes: 0 + mean_claim_coverage: 0 + mean_live_claim_coverage: 0 + mean_qualified_score: 0 + mean_raw_score: 0 + estimated_text_overflows: 0 + export_success_rate: 0 +failure_counts: +best_roles: + - "no full-deck role until a live-route ablation passes" +avoid_roles: + - "full-deck generator" + - "fallback authority" + - "final taste judge" +required_scaffolding: + - "no-generic-fallback" + - "independent route verification" +confidence: + cognitive_behavior: "low — no plan or reasoning traces captured" + tool_execution: "low — only browser creation and export were observed" + artifact_quality: "none — no evaluated runs" + routing_recommendation: "low" +status: "provisional — requires skill-on versus skill-off ablation" diff --git a/.qa/models/claude-opus-5-5/findings.jsonl b/.qa/models/claude-opus-5-5/findings.jsonl new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/.qa/models/claude-opus-5-5/findings.jsonl @@ -0,0 +1 @@ + diff --git a/.qa/models/claude-sonnet-5-5/benchmark-summary.md b/.qa/models/claude-sonnet-5-5/benchmark-summary.md new file mode 100644 index 00000000..ba4d4d60 --- /dev/null +++ b/.qa/models/claude-sonnet-5-5/benchmark-summary.md @@ -0,0 +1,13 @@ +# Claude Sonnet 5.5 benchmark summary + +Evidence: 0/0 evaluated runs across 0 briefs and 0 directions on deck-gym-v1. + +- Live routes: 0 +- Degraded routes: 0 +- Live claim gate: 0/0 +- Mean claim coverage: 0 +- Qualified score: 0 +- Estimated text overflows: 0 +- Export success: 0 + +These findings describe observed behavior only. Cognitive and tool-orchestration claims remain low confidence until plan and tool traces are captured. diff --git a/.qa/models/claude-sonnet-5-5/capability-card.yaml b/.qa/models/claude-sonnet-5-5/capability-card.yaml new file mode 100644 index 00000000..697ecbc9 --- /dev/null +++ b/.qa/models/claude-sonnet-5-5/capability-card.yaml @@ -0,0 +1,37 @@ +schema_version: nodeslide.model-capability-card/v1 +profile_version: 1 +model: anthropic/claude-sonnet-5.5 +label: Claude Sonnet 5.5 +evidence_window: + attempted_runs: 0 + evaluated_runs: 0 + completed_exports: 0 + briefs: 0 + directions: 0 + harness_version: "deck-gym-v1" +observed_metrics: + live_routes: 0 + degraded_routes: 0 + live_claim_passes: 0 + mean_claim_coverage: 0 + mean_live_claim_coverage: 0 + mean_qualified_score: 0 + mean_raw_score: 0 + estimated_text_overflows: 0 + export_success_rate: 0 +failure_counts: +best_roles: + - "no full-deck role until a live-route ablation passes" +avoid_roles: + - "full-deck generator" + - "fallback authority" + - "final taste judge" +required_scaffolding: + - "no-generic-fallback" + - "independent route verification" +confidence: + cognitive_behavior: "low — no plan or reasoning traces captured" + tool_execution: "low — only browser creation and export were observed" + artifact_quality: "none — no evaluated runs" + routing_recommendation: "low" +status: "provisional — requires skill-on versus skill-off ablation" diff --git a/.qa/models/claude-sonnet-5-5/findings.jsonl b/.qa/models/claude-sonnet-5-5/findings.jsonl new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/.qa/models/claude-sonnet-5-5/findings.jsonl @@ -0,0 +1 @@ + diff --git a/.qa/models/gemini-3-8-flash/benchmark-summary.md b/.qa/models/gemini-3-8-flash/benchmark-summary.md new file mode 100644 index 00000000..ded87857 --- /dev/null +++ b/.qa/models/gemini-3-8-flash/benchmark-summary.md @@ -0,0 +1,13 @@ +# Gemini 3.8 Flash benchmark summary + +Evidence: 0/0 evaluated runs across 0 briefs and 0 directions on deck-gym-v1. + +- Live routes: 0 +- Degraded routes: 0 +- Live claim gate: 0/0 +- Mean claim coverage: 0 +- Qualified score: 0 +- Estimated text overflows: 0 +- Export success: 0 + +These findings describe observed behavior only. Cognitive and tool-orchestration claims remain low confidence until plan and tool traces are captured. diff --git a/.qa/models/gemini-3-8-flash/capability-card.yaml b/.qa/models/gemini-3-8-flash/capability-card.yaml new file mode 100644 index 00000000..11122b2a --- /dev/null +++ b/.qa/models/gemini-3-8-flash/capability-card.yaml @@ -0,0 +1,37 @@ +schema_version: nodeslide.model-capability-card/v1 +profile_version: 1 +model: google/gemini-3.8-flash +label: Gemini 3.8 Flash +evidence_window: + attempted_runs: 0 + evaluated_runs: 0 + completed_exports: 0 + briefs: 0 + directions: 0 + harness_version: "deck-gym-v1" +observed_metrics: + live_routes: 0 + degraded_routes: 0 + live_claim_passes: 0 + mean_claim_coverage: 0 + mean_live_claim_coverage: 0 + mean_qualified_score: 0 + mean_raw_score: 0 + estimated_text_overflows: 0 + export_success_rate: 0 +failure_counts: +best_roles: + - "no full-deck role until a live-route ablation passes" +avoid_roles: + - "full-deck generator" + - "fallback authority" + - "final taste judge" +required_scaffolding: + - "no-generic-fallback" + - "independent route verification" +confidence: + cognitive_behavior: "low — no plan or reasoning traces captured" + tool_execution: "low — only browser creation and export were observed" + artifact_quality: "none — no evaluated runs" + routing_recommendation: "low" +status: "provisional — requires skill-on versus skill-off ablation" diff --git a/.qa/models/gemini-3-8-flash/findings.jsonl b/.qa/models/gemini-3-8-flash/findings.jsonl new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/.qa/models/gemini-3-8-flash/findings.jsonl @@ -0,0 +1 @@ + diff --git a/.qa/models/gpt-6-1-sol/benchmark-summary.md b/.qa/models/gpt-6-1-sol/benchmark-summary.md new file mode 100644 index 00000000..8c2067bf --- /dev/null +++ b/.qa/models/gpt-6-1-sol/benchmark-summary.md @@ -0,0 +1,13 @@ +# GPT-6.1 Sol benchmark summary + +Evidence: 0/0 evaluated runs across 0 briefs and 0 directions on deck-gym-v1. + +- Live routes: 0 +- Degraded routes: 0 +- Live claim gate: 0/0 +- Mean claim coverage: 0 +- Qualified score: 0 +- Estimated text overflows: 0 +- Export success: 0 + +These findings describe observed behavior only. Cognitive and tool-orchestration claims remain low confidence until plan and tool traces are captured. diff --git a/.qa/models/gpt-6-1-sol/capability-card.yaml b/.qa/models/gpt-6-1-sol/capability-card.yaml new file mode 100644 index 00000000..95e236fe --- /dev/null +++ b/.qa/models/gpt-6-1-sol/capability-card.yaml @@ -0,0 +1,37 @@ +schema_version: nodeslide.model-capability-card/v1 +profile_version: 1 +model: openai/gpt-6.1-sol +label: GPT-6.1 Sol +evidence_window: + attempted_runs: 0 + evaluated_runs: 0 + completed_exports: 0 + briefs: 0 + directions: 0 + harness_version: "deck-gym-v1" +observed_metrics: + live_routes: 0 + degraded_routes: 0 + live_claim_passes: 0 + mean_claim_coverage: 0 + mean_live_claim_coverage: 0 + mean_qualified_score: 0 + mean_raw_score: 0 + estimated_text_overflows: 0 + export_success_rate: 0 +failure_counts: +best_roles: + - "no full-deck role until a live-route ablation passes" +avoid_roles: + - "full-deck generator" + - "fallback authority" + - "final taste judge" +required_scaffolding: + - "no-generic-fallback" + - "independent route verification" +confidence: + cognitive_behavior: "low — no plan or reasoning traces captured" + tool_execution: "low — only browser creation and export were observed" + artifact_quality: "none — no evaluated runs" + routing_recommendation: "low" +status: "provisional — requires skill-on versus skill-off ablation" diff --git a/.qa/models/gpt-6-1-sol/findings.jsonl b/.qa/models/gpt-6-1-sol/findings.jsonl new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/.qa/models/gpt-6-1-sol/findings.jsonl @@ -0,0 +1 @@ + diff --git a/.tours/01-primary-user-flow.tour b/.tours/01-primary-user-flow.tour index df4347da..0294a8d4 100644 --- a/.tours/01-primary-user-flow.tour +++ b/.tours/01-primary-user-flow.tour @@ -15,7 +15,7 @@ }, { "file": "src/domains/nodeslide/components/NodeSlideLanding.tsx", - "line": 104, + "line": 107, "description": "**The primary user action.**\n\nThis is where a free-form paragraph becomes a structured request. The person typed one sentence; the generator needs an audience, a purpose and success criteria, so `start` supplies sensible defaults rather than interrogating the user with a form.\n\nEverything downstream can therefore assume a complete request shape. Note `route: 'free'` — it is the only route this release accepts, and the server rejects the others." }, { diff --git a/.tours/02-agent-execution.tour b/.tours/02-agent-execution.tour index 987acda6..87d46194 100644 --- a/.tours/02-agent-execution.tour +++ b/.tours/02-agent-execution.tour @@ -15,17 +15,17 @@ }, { "file": "mcp/src/lib/nodeslideTools.ts", - "line": 414, + "line": 417, "description": "**A coding agent is a first-class user.**\n\nThis is not a second backend. Each MCP tool validates its arguments with Zod and then calls the *same* Convex function the browser calls.\n\nOne write path means an agent cannot bypass the version check — which is the entire safety argument for letting an agent edit a deck at all." }, { "file": "mcp/src/lib/nodeslideTools.ts", - "line": 430, + "line": 433, "description": "**Read tools declare themselves read-only.**\n\n`readOnlyHint: true`, `destructiveHint: false`, `openWorldHint: false` — these annotations are how the calling agent's host decides whether to ask a human first.\n\nThe description also states what the tool will *not* do: it never returns the owner key." }, { "file": "mcp/src/lib/nodeslideTools.ts", - "line": 540, + "line": 543, "description": "**The write tool proposes; it does not commit.**\n\nIt returns an `unappliedProposalReceipt`. Committing is a *separate* tool — `nodeslide.accept_proposal`, a few lines below — which is described as an 'Explicit review action'.\n\nAn agent can produce a proposal; accepting it is its own deliberate call. That asymmetry is the product, not a limitation of the integration." }, { diff --git a/artifacts/node-gym/nodeslide-deck-gym-v2/configuration-validation.json b/artifacts/node-gym/nodeslide-deck-gym-v2/configuration-validation.json index 819370c9..237b9681 100644 --- a/artifacts/node-gym/nodeslide-deck-gym-v2/configuration-validation.json +++ b/artifacts/node-gym/nodeslide-deck-gym-v2/configuration-validation.json @@ -1,7 +1,7 @@ { "schemaVersion": "nodekit.gym-config-validation/v1", "gymVersion": "nodeslide-deck-gym-v2", - "configDigest": "sha256:e7aef1f13cccfbe86c11146d4c960ac8b29b2464ed1df2a0235cc77b478b3939", + "configDigest": "sha256:57379ad92e0c766a41718c76a4807cec9589ebb89d91d8c0cec89a7daff28903", "status": "passed", "matrixSize": 720, "failures": [] diff --git a/artifacts/node-gym/nodeslide-deck-gym-v2/matrix.json b/artifacts/node-gym/nodeslide-deck-gym-v2/matrix.json index bbba8c4d..e63a76a0 100644 --- a/artifacts/node-gym/nodeslide-deck-gym-v2/matrix.json +++ b/artifacts/node-gym/nodeslide-deck-gym-v2/matrix.json @@ -1,7 +1,7 @@ { "schemaVersion": "nodekit.gym-matrix/v1", "gymVersion": "nodeslide-deck-gym-v2", - "configDigest": "sha256:e7aef1f13cccfbe86c11146d4c960ac8b29b2464ed1df2a0235cc77b478b3939", + "configDigest": "sha256:57379ad92e0c766a41718c76a4807cec9589ebb89d91d8c0cec89a7daff28903", "runCount": 720, "pairedComparisonReady": true, "promotionAutoApply": false, @@ -1193,7 +1193,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -1232,7 +1237,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -1271,7 +1281,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -1310,7 +1325,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -1349,7 +1369,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -1388,7 +1413,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -1427,7 +1457,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -1466,7 +1501,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -1505,7 +1545,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -1544,7 +1589,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -1583,7 +1633,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -1622,7 +1677,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -1661,7 +1721,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -1700,7 +1765,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -1739,7 +1809,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -4703,7 +4778,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -4742,7 +4822,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -4781,7 +4866,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -4820,7 +4910,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -4859,7 +4954,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -4898,7 +4998,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -4937,7 +5042,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -4976,7 +5086,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -5015,7 +5130,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -5054,7 +5174,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -5093,7 +5218,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -5132,7 +5262,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -5171,7 +5306,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -5210,7 +5350,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -5249,7 +5394,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -8213,7 +8363,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -8252,7 +8407,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -8291,7 +8451,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -8330,7 +8495,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -8369,7 +8539,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -8408,7 +8583,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -8447,7 +8627,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -8486,7 +8671,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -8525,7 +8715,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -8564,7 +8759,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -8603,7 +8803,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -8642,7 +8847,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -8681,7 +8891,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -8720,7 +8935,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -8759,7 +8979,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -11723,7 +11948,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -11762,7 +11992,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -11801,7 +12036,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -11840,7 +12080,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -11879,7 +12124,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -11918,7 +12168,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -11957,7 +12212,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -11996,7 +12256,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -12035,7 +12300,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -12074,7 +12344,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -12113,7 +12388,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -12152,7 +12432,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -12191,7 +12476,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -12230,7 +12520,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -12269,7 +12564,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -15233,7 +15533,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -15272,7 +15577,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -15311,7 +15621,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -15350,7 +15665,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -15389,7 +15709,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -15428,7 +15753,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -15467,7 +15797,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -15506,7 +15841,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -15545,7 +15885,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -15584,7 +15929,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -15623,7 +15973,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -15662,7 +16017,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -15701,7 +16061,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -15740,7 +16105,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -15779,7 +16149,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -18743,7 +19118,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -18782,7 +19162,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -18821,7 +19206,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -18860,7 +19250,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -18899,7 +19294,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -18938,7 +19338,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -18977,7 +19382,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -19016,7 +19426,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -19055,7 +19470,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -19094,7 +19514,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -19133,7 +19558,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -19172,7 +19602,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -19211,7 +19646,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -19250,7 +19690,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -19289,7 +19734,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -22253,7 +22703,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -22292,7 +22747,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -22331,7 +22791,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -22370,7 +22835,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -22409,7 +22879,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -22448,7 +22923,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -22487,7 +22967,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -22526,7 +23011,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -22565,7 +23055,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -22604,7 +23099,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -22643,7 +23143,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -22682,7 +23187,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -22721,7 +23231,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -22760,7 +23275,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -22799,7 +23319,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -25763,7 +26288,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -25802,7 +26332,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -25841,7 +26376,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "light-director", @@ -25880,7 +26420,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -25919,7 +26464,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -25958,7 +26508,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "structured-planner", @@ -25997,7 +26552,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -26036,7 +26596,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -26075,7 +26640,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "bounded-executor", @@ -26114,7 +26684,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -26153,7 +26728,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -26192,7 +26772,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "repair-specialist", @@ -26231,7 +26816,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -26270,7 +26860,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", @@ -26309,7 +26904,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, "harness": { "id": "router-robustness", diff --git a/benchmarks/deck-gym/v2/gym.json b/benchmarks/deck-gym/v2/gym.json index f893e746..8581f043 100644 --- a/benchmarks/deck-gym/v2/gym.json +++ b/benchmarks/deck-gym/v2/gym.json @@ -298,7 +298,12 @@ "provider": "openrouter", "route": "openai/gpt-oss-20b:free", "returnedModelRequired": true, - "cohort": "small-legacy" + "cohort": "small-legacy", + "execution": { + "disabled": true, + "since": "2026-10-10", + "reason": "unlisted on OpenRouter (GET /api/v1/models, 2026-10-10)" + } }, { "id": "google/gemma-4-26b-a4b-it:free", diff --git a/convex/lib/nodeslideEditVerifyAction.test.ts b/convex/lib/nodeslideEditVerifyAction.test.ts index c70995c4..9dc191b9 100644 --- a/convex/lib/nodeslideEditVerifyAction.test.ts +++ b/convex/lib/nodeslideEditVerifyAction.test.ts @@ -272,7 +272,7 @@ describe('proposeEdit B4 tool loop messages', () => { }, telemetry: { provider: 'openrouter', - model: 'google/gemini-3.5-flash', + model: 'deepseek/deepseek-v4.1-flash-1017', inputTokens: 5, outputTokens: 3, costMicroUsd: 1, @@ -336,7 +336,9 @@ describe('proposeEdit B4 tool loop messages', () => { const executorStep = steps.find((step) => step.toolName === 'executor'); const verifyStep = steps.find((step) => step.toolName === 'verify'); expect(plannerStep?.spanModel).toBe('moonshotai/kimi-k3'); - expect(executorStep?.spanModel).toBe('google/gemini-3.5-flash'); + // Executor moved off Gemini 3.5 Flash (Google deprecated it on 2026-10-08) to 'google/gemini-3.8-flash' + // (SPEC A.2.8), then to the paid DeepSeek V4.1 Flash dated id (SPEC "Homen decisions", 2026-11-06). + expect(executorStep?.spanModel).toBe('deepseek/deepseek-v4.1-flash-1017'); expect(verifyStep?.message).toContain('shadow snapshot'); }); }); diff --git a/convex/lib/nodeslideExecutorSplitProbe.ts b/convex/lib/nodeslideExecutorSplitProbe.ts new file mode 100644 index 00000000..4e209211 --- /dev/null +++ b/convex/lib/nodeslideExecutorSplitProbe.ts @@ -0,0 +1,349 @@ +import { createHash } from 'node:crypto'; +import { + type DeckSnapshot, + type NodeSlideAgentModelId, + type PatchScope, + nodeSlideAgentModel, +} from '../../shared/nodeslide'; +import { NODESLIDE_RUN_BUDGET_BOUNDS } from '../../shared/nodeslideRunBudget'; +import { + type NodeSlideBudgetLedgerClient, + createNodeSlideBudgetedEditDispatch, + nodeSlideProviderBudgetId, +} from './nodeslideBudgetedProvider'; +import { type NodeSlideEditPlanningRequest, planNodeSlideEditRouted } from './nodeslideEditPlanner'; +import { nodeslideStableId } from './nodeslideIds'; +import { + type NodeSlideProviderResult, + type NodeSlideProviderTelemetry, + callNodeSlideFreeJson, +} from './nodeslideProvider'; +import { NODESLIDE_ROUTING_EXECUTOR_MODEL } from './nodeslideRoutingPolicy'; +import { buildGoldenNodeSlide } from './nodeslideSeed'; + +/** + * Candidate-bound executor receipt for the routed copy executor (SPEC Part A, section A.2.8). + * + * Situation: NodeSlide's edit planner is a premium model; when its plan rewrites two or more text + * elements it hands the wording to a cheap "executor" model. Google retired the executor + * (Gemini 3.5 Flash) on 2026-10-08, so the executor id changed (to gemini-3.8-flash, SPEC A.2.8, then + * to the paid deepseek/deepseek-v4.1-flash-1017, SPEC "Homen decisions" 2026-11-06). The only honest + * proof that the new executor really runs is one edit turn that is split exactly that way, through the same + * reserve-before-dispatch provider production uses, with the model name the provider echoed back + * (not the one we asked for) written into the receipt. Create-and-export journeys never reach the + * executor, so they cannot stand in for this. + * + * The receipt is data only. Whether it counts as evidence is decided by `executorSplitReceiptFailures` + * (scripts/lib/model-fleet-receipt-core.mjs), which also compares the build identity with the tested + * commit, because only the caller knows which commit was tested. It carries the fields Part A rule 3 + * asks of every receipt (candidate, echoed models, one row per span, revision, constant hash, ledger + * accounting, dispatch policy) so that review can reject it on the same grounds as any other. + * + * The probe turns the provider's second completion off (`maxRetries: 0` reaches + * `callNodeSlideFreeJson`, which then makes exactly one request per span: no JSON-repair call, no + * schema-compatibility retry) and no code path in the edit planner re-dispatches to another model + * (its only fallback is deterministic and issues no request). `dispatchPolicy` in the receipt is + * therefore the policy that was enforced, a constant, not a count of what happened; each row's + * `dispatches` is the observed count and must be exactly 1 (`executorSplitReceiptFailures`). + * Every dispatch is recorded as it returns, so a failed run still reports the requests it made. + */ +export const NODESLIDE_EXECUTOR_SPLIT_PROBE_SCHEMA = 'nodeslide.executor-split-probe/v1' as const; + +/** Premium per PREMIUM_PLANNER_PATTERNS (nodeslideRoutingPolicy.ts), so the split is granted. */ +export const NODESLIDE_EXECUTOR_SPLIT_PLANNER_MODEL = 'moonshotai/kimi-k3' as const; + +export const NODESLIDE_EXECUTOR_SPLIT_PROBE_COMMAND = + 'npx convex run nodeslideModelProbe:runExecutorSplit' as const; + +/** + * The cap must cover what the ledger reserves BEFORE the first dispatch: the kimi-k3 planner at + * 3 / 15 USD per million tokens (about 114,000 input / 4,400 output estimated tokens, 0.408756 USD) + * plus the deepseek-v4.1-flash-1017 executor at 0.15 / 0.60 (107,010 / 4,000 tokens, 0.018452 USD), + * 0.427208 USD together (0.504014 USD with the earlier gemini-3.8-flash executor). The earlier 0.25 USD + * default refused the planner's reservation, so the probe never dispatched (SPEC D3, Homen 2026-10-16: + * 0.55 USD on dev and on the nightly probe). `convex/nodeslideExecutorSplitProbeBudget.test.ts` checks + * this number against the real ledger. + */ +export const NODESLIDE_EXECUTOR_SPLIT_DEFAULT_BUDGET_USD = 0.55 as const; + +/** SPEC A.0.3: paid dispatches without a retry or a cross-model fallback. Enforced, then recorded. */ +export const NODESLIDE_EXECUTOR_SPLIT_DISPATCH_POLICY = { + maxRetries: 0, + crossModelFallback: false, +} as const; + +export interface NodeSlideExecutorSplitSpan { + toolName: 'planner' | 'executor'; + spanModel: string; + /** The model string the provider returned, never the one requested. */ + responseModel: string | null; + usage: { inputTokens: number; outputTokens: number }; + costMicroUsd: number; +} + +/** Part A rule 3 row: one per span, in the same order as `spans`. */ +export interface NodeSlideExecutorSplitRow { + toolName: 'planner' | 'executor'; + requestedModel: string; + /** What the repo's resolver chose for the request. */ + resolvedModel: string; + /** The model string the provider returned; null when it returned none. */ + echoedModel: string | null; + usage: { inputTokens: number; outputTokens: number }; + costUsd: number; + /** True when the provider served a model other than the one requested. */ + fallbackUsed: boolean; + /** Model calls issued for this span; the receipt is rejected unless exactly 1. */ + dispatches: number; +} + +export interface NodeSlideExecutorSplitProbeReceipt { + schemaVersion: typeof NODESLIDE_EXECUTOR_SPLIT_PROBE_SCHEMA; + command: typeof NODESLIDE_EXECUTOR_SPLIT_PROBE_COMMAND; + /** The model under test: the routed copy executor. The planner is a fixture. */ + candidateIds: string[]; + echoedModels: string[]; + rows: NodeSlideExecutorSplitRow[]; + routing: { + plannerModel: string; + executorModel: string | null; + reason: string; + executorOutcome: string | null; + }; + spans: NodeSlideExecutorSplitSpan[]; + /** The deployment's stamped commit, as the tested revision (the caller compares it to its own). */ + testedCommit: string | null; + /** sha256 of the executor constant (`NODESLIDE_ROUTING_EXECUTOR_MODEL`) this build routes to. */ + constantSha256: string; + budget: { + maxUsd: number; + /** Sum of the ledger's reservation quotes: the worst case the ledger authorized. */ + estimateUsd: number; + /** The ledger's settled actual spend for the probe's budget. */ + spentUsd: number; + /** Model calls issued across both spans. */ + requests: number; + /** The first ledger refusal, or null; a stop is an incomplete run, never a pass. */ + stoppedBy: string | null; + plannedOperations: number; + refusals: string[]; + }; + /** The policy enforced on every dispatch (not an observed count); rejected unless it is {0, false}. */ + dispatchPolicy: { maxRetries: number; crossModelFallback: boolean }; + buildIdentity: { schemaVersion: string; commitSha: string | null } | null; + startedAt: string; + environment: { runtime: string; node: string }; +} + +export function executorSplitProbeBudgetUsd(env: Record): number { + const raw = env['NODESLIDE_PROBE_BUDGET_USD']; + if (raw === undefined || raw === '') return NODESLIDE_EXECUTOR_SPLIT_DEFAULT_BUDGET_USD; + const parsed = Number(raw); + // An unparsable or non-positive ceiling is refused, never silently replaced by a larger one. + if (!Number.isFinite(parsed) || parsed <= 0) { + throw new Error('NODESLIDE_PROBE_BUDGET_USD must be a positive number of US dollars.'); + } + return Math.min(NODESLIDE_RUN_BUDGET_BOUNDS.maxCostUsd.default, parsed); +} + +function probeFixture(): { + snapshot: DeckSnapshot; + scope: PatchScope; + slideId: string; +} { + const snapshot = buildGoldenNodeSlide('executor-split-probe', 1_700_000_000_000).snapshot; + const bySlide = new Map(); + for (const element of snapshot.elements) { + if (element.kind !== 'text' || element.locked) continue; + bySlide.set(element.slideId, [...(bySlide.get(element.slideId) ?? []), element]); + } + const pair = [...bySlide.values()].find((elements) => elements.length >= 2); + if (!pair) throw new Error('The probe deck fixture needs a slide with two unlocked text blocks.'); + const targets = pair.slice(0, 2); + const slideId = targets[0]?.slideId as string; + return { + snapshot, + slideId, + scope: { + kind: 'elements', + deckId: snapshot.deck.id, + slideIds: [slideId], + elementIds: targets.map((element) => element.id), + operationMode: 'copy', + }, + }; +} + +/** + * Wraps the ledger so the probe can report what the ledger authorized: each reservation's quote is + * the worst case it admitted for that call. The wrapper adds nothing to the dispatch. + */ +function recordingLedger(ledger: NodeSlideBudgetLedgerClient) { + const quotesMicroUsd: number[] = []; + const client: NodeSlideBudgetLedgerClient = { + ...ledger, + reserve: async (args) => { + const view = await ledger.reserve(args); + if (view.call) quotesMicroUsd.push(view.call.quoteMicroUsd); + return view; + }, + }; + return { client, quotesMicroUsd }; +} + +const usd = (microUsd: number) => microUsd / 1_000_000; + +export async function runNodeSlideExecutorSplitProbe(args: { + ledger: NodeSlideBudgetLedgerClient; + buildIdentity: { schemaVersion: string; commitSha: string | null } | null; + budgetUsd: number; + now?: () => number; +}): Promise { + const now = args.now ?? Date.now; + const startedAt = new Date(now()).toISOString(); + const { snapshot, scope, slideId } = probeFixture(); + const slide = snapshot.slides.find((candidate) => candidate.id === slideId); + if (!slide) throw new Error('The probe deck fixture lost its slide.'); + const budget = { maxCostUsd: args.budgetUsd }; + // A fresh run id per invocation: a replayed id would return the recorded result without spending. + const runId = nodeslideStableId( + 'nsrun_probe_executor_split', + String(now()), + NODESLIDE_EXECUTOR_SPLIT_PLANNER_MODEL, + ); + const refusals: string[] = []; + // Every dispatch, recorded as it returns: a failed planner that still made requests is on the books. + const dispatched: { + toolName: 'planner' | 'executor'; + telemetry: NodeSlideProviderTelemetry; + }[] = []; + const ledger = recordingLedger(args.ledger); + const dispatch = createNodeSlideBudgetedEditDispatch({ + runId, + budget, + metered: true, + ledger: ledger.client, + dispatch: (request, dependencies) => + callNodeSlideFreeJson(request, { + dispatchPolicy: { + ...dependencies?.dispatchPolicy, + maxRetries: NODESLIDE_EXECUTOR_SPLIT_DISPATCH_POLICY.maxRetries, + }, + }), + }); + const request: NodeSlideEditPlanningRequest = { + deckId: snapshot.deck.id, + instruction: + 'Rewrite both listed text elements as crisp one-sentence executive statements. Emit one replace_text per element and a copyBriefs entry for each.', + baseDeckVersion: snapshot.deck.version, + baseSlideVersions: { [slideId]: slide.version }, + baseElementVersions: Object.fromEntries( + snapshot.elements + .filter((element) => element.slideId === slideId) + .map((element) => [element.id, element.version]), + ), + scope, + designBehavior: 'preserve', + referenceUse: 'context_only', + providerMode: 'openrouter_free', + providerModel: NODESLIDE_EXECUTOR_SPLIT_PLANNER_MODEL, + providerEffort: 'low', + }; + const outcome = await planNodeSlideEditRouted( + { snapshot, scopedComment: null, request }, + { + callProvider: async (providerRequest) => { + const result: NodeSlideProviderResult = await dispatch(providerRequest); + if (!result.ok) refusals.push(result.reason); + if (result.telemetry) { + dispatched.push({ + toolName: + providerRequest.jsonSchema?.name === 'nodeslide_copy_execution' + ? 'executor' + : 'planner', + telemetry: result.telemetry, + }); + } + return result; + }, + }, + ); + const routing = outcome.ok ? outcome.routing : undefined; + const spans = dispatched.map((entry) => span(entry.toolName, entry.telemetry)); + const rows = dispatched.map((entry) => row(entry.toolName, entry.telemetry)); + // The ledger's own books for this probe's budget: what it settled, not what the rows say. + const books = await args.ledger.replay({ budgetId: nodeSlideProviderBudgetId(runId) }); + const requests = rows.reduce((total, entry) => total + entry.dispatches, 0); + const echoedModels = [ + ...new Set(rows.map((entry) => entry.echoedModel).filter((model) => model !== null)), + ] as string[]; + return { + schemaVersion: NODESLIDE_EXECUTOR_SPLIT_PROBE_SCHEMA, + command: NODESLIDE_EXECUTOR_SPLIT_PROBE_COMMAND, + candidateIds: [NODESLIDE_ROUTING_EXECUTOR_MODEL], + echoedModels, + rows, + routing: outcome.ok + ? { + plannerModel: routing?.plannerModel ?? NODESLIDE_EXECUTOR_SPLIT_PLANNER_MODEL, + executorModel: routing?.executorModel ?? null, + reason: routing?.reason ?? 'not_routed', + executorOutcome: routing?.executorOutcome ?? null, + } + : { + plannerModel: NODESLIDE_EXECUTOR_SPLIT_PLANNER_MODEL, + executorModel: null, + reason: 'planner_failed', + executorOutcome: null, + }, + spans, + testedCommit: args.buildIdentity?.commitSha ?? null, + constantSha256: `sha256:${createHash('sha256').update(NODESLIDE_ROUTING_EXECUTOR_MODEL).digest('hex')}`, + budget: { + maxUsd: args.budgetUsd, + estimateUsd: usd(ledger.quotesMicroUsd.reduce((total, quote) => total + quote, 0)), + spentUsd: usd(books?.budget.actualMicroUsd ?? 0), + requests, + stoppedBy: refusals[0] ?? null, + plannedOperations: outcome.ok ? outcome.operations.length : 0, + refusals, + }, + dispatchPolicy: { ...NODESLIDE_EXECUTOR_SPLIT_DISPATCH_POLICY }, + buildIdentity: args.buildIdentity, + startedAt, + environment: { runtime: 'convex-node-action', node: process.version }, + }; +} + +function span( + toolName: 'planner' | 'executor', + telemetry: NodeSlideProviderTelemetry, +): NodeSlideExecutorSplitSpan { + return { + toolName, + spanModel: telemetry.requestedModel ?? telemetry.model, + responseModel: telemetry.echoedModel ?? null, + usage: { inputTokens: telemetry.inputTokens, outputTokens: telemetry.outputTokens }, + costMicroUsd: telemetry.costMicroUsd, + }; +} + +function row( + toolName: 'planner' | 'executor', + telemetry: NodeSlideProviderTelemetry, +): NodeSlideExecutorSplitRow { + const requestedModel = telemetry.requestedModel ?? telemetry.model; + const echoedModel = telemetry.echoedModel ?? null; + return { + toolName, + requestedModel, + // `telemetry.model` becomes the echoed model after a call; the resolver's choice is the catalog + // row's upstream id for the requested route. + resolvedModel: nodeSlideAgentModel(requestedModel as NodeSlideAgentModelId).upstreamId, + echoedModel, + usage: { inputTokens: telemetry.inputTokens, outputTokens: telemetry.outputTokens }, + costUsd: usd(telemetry.costMicroUsd), + fallbackUsed: echoedModel !== null && echoedModel !== requestedModel, + dispatches: telemetry.attempts?.length ?? 1, + }; +} diff --git a/convex/lib/nodeslideProvider.requestShape.test.ts b/convex/lib/nodeslideProvider.requestShape.test.ts new file mode 100644 index 00000000..c1e705ed --- /dev/null +++ b/convex/lib/nodeslideProvider.requestShape.test.ts @@ -0,0 +1,490 @@ +/** + * Request-shape proof for the 2026-10 model refresh (SPEC Part A rule 6, section A.2.8). + * + * Situation: a user picks Claude Sonnet 5.5, Claude Opus 5.5, Gemini 3.8 Flash or GPT-6.1 Sol in + * the NodeSlide model picker, or the edit planner hands bulk copy work to the routed executor. + * Those vendors reject some parameters outright (a 400, not a warning): sampling parameters on + * Claude 5.5 and GPT-6, a disabled thinking block on Opus 5.5, Gemini's deprecated sampling. The + * wrong wire id is just as fatal. Nothing here calls a provider: the real request is built by this + * repo's own provider code (pi-ai plus `nodeSlideProviderPayload`) and the HTTP transport is a fake + * `fetch` that records what would have been sent. + * + * Wire ids are SPEC section 1.2, `openrouter` column, and nothing else. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + NODESLIDE_AGENT_MODELS, + NODESLIDE_DEFAULT_REASONING_EFFORT, + NODESLIDE_OFFERED_AGENT_MODELS, + NODESLIDE_OPENROUTER_EDIT_CONSENT, + type NodeSlideAgentModelId, + nodeSlideAgentModel, + nodeSlideDefaultReasoningEffort, + nodeSlideEffortForModel, + nodeSlideModelSupportsReasoningEffort, +} from '../../shared/nodeslide'; +import { nodeSlideModelPricing } from '../../shared/nodeslideRunBudget'; +import { + callNodeSlideFreeJson, + nodeSlideModelProbeProfile, + openrouterProviderWithOverrides, + probeNodeSlideModelOnce, +} from './nodeslideProvider'; +import { validateNodeSlideProviderChoice } from './nodeslideProviderConsent'; +import { + NODESLIDE_ROUTING_EXECUTOR_MODEL, + resolveNodeSlideRouting, +} from './nodeslideRoutingPolicy'; +import { + NODESLIDE_OPENROUTER_BRIEF_CONSENT, + validateNodeSlideBriefProviderChoice, +} from './nodeslideValidators'; + +// The first provider call in this file pays for the cold pi-ai catalog/lazy-transport import. It took +// 6565 ms under a loaded `npm run check` against the 5 s default (round 1, review defect 11), so this +// file gets an explicit budget instead of depending on machine load. Only the timeout moves; every +// assertion is unchanged. +vi.setConfig({ testTimeout: 30_000 }); + +/** SPEC section 1.2, `openrouter` column. */ +const WIRE_ID = { + sonnet55: 'anthropic/claude-sonnet-5.5', + opus55: 'anthropic/claude-opus-5.5', + gemini38Flash: 'google/gemini-3.8-flash', + gpt61Sol: 'openai/gpt-6.1-sol', +} as const satisfies Record; + +/** Keys a Claude 5.5 / GPT-6 / Gemini 3.6+ request must never carry (SPEC section 1.3). */ +const FORBIDDEN_SAMPLING_KEYS = ['temperature', 'top_p', 'top_k'] as const; +const FORBIDDEN_LEGACY_KEYS = [ + 'thinking', + 'budget_tokens', + 'thinking_budget', + 'candidate_count', + 'logprobs', + 'top_logprobs', + 'prefill', + // Forced tool choice is a 400 on Sonnet 5.5 and Opus 5.5 (SPEC 1.3), and GPT-6.1 tools need the + // Responses API, not Chat Completions. NodeSlide's JSON calls offer no tools, so neither key may appear. + 'tool_choice', + 'tools', +] as const; +/** SPEC 1.3: low..max are accepted; `none` and `minimal` are rejected on the new rows. */ +const ACCEPTED_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const; + +interface CapturedRequest { + url: string; + body: Record; +} + +const sseDone = [ + 'data: {"id":"gen-fake","model":"fake/echo","choices":[{"index":0,"delta":{"role":"assistant","content":"{\\"ok\\":true}"},"finish_reason":null}]}\n\n', + 'data: {"id":"gen-fake","model":"fake/echo","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}\n\n', + 'data: [DONE]\n\n', +].join(''); + +const originalKey = process.env['OPENROUTER_API_KEY']; +let captured: CapturedRequest[] = []; + +beforeEach(() => { + captured = []; + // A fake key so pi-ai builds the request; the transport below never leaves the process. + process.env['OPENROUTER_API_KEY'] = 'sk-or-test-fake-not-a-credential'; + vi.stubGlobal('fetch', async (input: unknown, init?: { body?: unknown }) => { + const url = + typeof input === 'string' ? input : ((input as { url?: string }).url ?? String(input)); + captured.push({ url, body: JSON.parse(String(init?.body ?? '{}')) as Record }); + return new Response(sseDone, { status: 200, headers: { 'content-type': 'text/event-stream' } }); + }); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + if (originalKey === undefined) Reflect.deleteProperty(process.env, 'OPENROUTER_API_KEY'); + else process.env['OPENROUTER_API_KEY'] = originalKey; +}); + +function expectNoForbiddenKeys(body: Record) { + for (const key of [...FORBIDDEN_SAMPLING_KEYS, ...FORBIDDEN_LEGACY_KEYS]) { + expect(Object.keys(body), `request must not carry "${key}"`).not.toContain(key); + } + // Prefill is an assistant turn at the end of the conversation (a 400 on every new row), not a key. + const messages = (body['messages'] ?? []) as { role?: string }[]; + expect(messages.length, 'request carries messages').toBeGreaterThan(0); + expect(messages.at(-1)?.role, 'request must not end on an assistant message (prefill)').not.toBe( + 'assistant', + ); + // A disabled reasoning block is a 400 on Opus 5.5 and Sonnet 5.5; effort must be explicit, and one + // the vendors accept. + const reasoning = body['reasoning'] as { enabled?: boolean; effort?: string } | undefined; + expect(reasoning?.enabled).toBeUndefined(); + // OpenRouter encodes a thinking budget as reasoning.max_tokens (budget_tokens is a 400 on Claude 5.5, + // SPEC 1.3), so effort is the only key the reasoning block may carry. + expect(Object.keys(reasoning ?? {}), 'reasoning must carry only effort').toEqual(['effort']); + expect(ACCEPTED_EFFORTS as readonly string[]).toContain(reasoning?.effort); +} + +describe('the forbidden-shape guard itself', () => { + // Round 1 (Codex): injecting toolChoice:'required' into the provider left every test passing. + // These feed the guard a request that carries each forbidden shape and require it to object. + const clean = { + model: 'x', + messages: [{ role: 'user', content: 'hi' }], + reasoning: { effort: 'high' }, + }; + it('accepts a clean request', () => { + expect(() => expectNoForbiddenKeys(clean)).not.toThrow(); + }); + it.each([ + ['a forced tool_choice', { ...clean, tool_choice: 'required' }], + ['an offered tool list', { ...clean, tools: [{ type: 'function' }] }], + ['a sampling parameter', { ...clean, temperature: 0 }], + [ + 'an assistant prefill turn', + { ...clean, messages: [...clean.messages, { role: 'assistant', content: '{' }] }, + ], + ['a disabled reasoning block', { ...clean, reasoning: { enabled: false, effort: 'high' } }], + ['a reasoning token budget', { ...clean, reasoning: { effort: 'medium', max_tokens: 1024 } }], + ['effort "none"', { ...clean, reasoning: { effort: 'none' } }], + ['effort "minimal"', { ...clean, reasoning: { effort: 'minimal' } }], + ['an arbitrary effort string', { ...clean, reasoning: { effort: 'banana' } }], + ])('rejects %s', (_label, body) => { + expect(() => expectNoForbiddenKeys(body)).toThrow(); + }); +}); + +describe('the new catalog rows build refresh-safe requests', () => { + for (const [label, modelId] of Object.entries(WIRE_ID) as [string, NodeSlideAgentModelId][]) { + it(`${label}: probe request carries the SPEC 1.2 wire id and none of the forbidden keys`, async () => { + const route = nodeSlideAgentModel(modelId); + // The row must exist (an unknown id throws: it no longer falls back to the first catalog row). + expect(route.id).toBe(modelId); + expect(route.upstreamId).toBe(modelId); + expect(route.provider).toBe('openrouter'); + expect(route.supportsTemperature).toBe(false); + expect(route.productionEnabled).toBe(true); + + await probeNodeSlideModelOnce(modelId); + + expect(captured).toHaveLength(1); + const [request] = captured; + expect(request?.url).toBe('https://openrouter.ai/api/v1/chat/completions'); + expect(request?.body['model']).toBe(modelId); + expectNoForbiddenKeys(request?.body ?? {}); + const budgetKey = ['max_tokens', 'max_completion_tokens'].find( + (key) => key in (request?.body ?? {}), + ); + expect(budgetKey).toBeDefined(); + expect(request?.body[budgetKey as string]).toBe( + nodeSlideModelProbeProfile(modelId).maxTokens, + ); + }); + } + + it('Opus 5.5 defaults to its own row effort (medium) and every request names one', async () => { + // SPEC A.2.8: Opus 5.5 defaults to medium on the vendor side (Opus 5 was high), "explicit per + // row". The catalog row carries defaultEffort 'medium'; the provider sends it explicitly so + // the vendor default never applies. (Round 1 asserted 'high' here and locked in the wrong value.) + expect(nodeSlideDefaultReasoningEffort(WIRE_ID.opus55)).toBe('medium'); + await callNodeSlideFreeJson({ + systemPrompt: 'Return JSON.', + userText: '{}', + maxTokens: 500, + model: WIRE_ID.opus55, + }); + expect(captured.length).toBeGreaterThan(0); + for (const request of captured) { + expect(request.body['model']).toBe(WIRE_ID.opus55); + expect((request.body['reasoning'] as { effort: string }).effort).toBe('medium'); + expectNoForbiddenKeys(request.body); + } + }); + + it('an explicit caller effort is kept as given, Opus 5.5 included', async () => { + await callNodeSlideFreeJson({ + systemPrompt: 'Return JSON.', + userText: '{}', + maxTokens: 500, + model: WIRE_ID.opus55, + reasoningEffort: 'high', + }); + expect(captured.length).toBeGreaterThan(0); + for (const request of captured) { + expect((request.body['reasoning'] as { effort: string }).effort).toBe('high'); + } + }); + + it('every defaulting boundary agrees: only Opus 5.5 differs from the global high default', () => { + for (const row of NODESLIDE_OFFERED_AGENT_MODELS) { + const id = row.id as NodeSlideAgentModelId; + const expected = id === WIRE_ID.opus55 ? 'medium' : NODESLIDE_DEFAULT_REASONING_EFFORT; + expect(nodeSlideDefaultReasoningEffort(id), id).toBe(expected); + expect(nodeSlideModelSupportsReasoningEffort(id, expected), id).toBe(true); + // Public create boundary and public edit/variation consent boundary, no caller effort. + expect( + validateNodeSlideBriefProviderChoice( + 'openrouter_free', + NODESLIDE_OPENROUTER_BRIEF_CONSENT, + id, + ), + `create ${id}`, + ).toMatchObject({ providerEffort: expected }); + expect( + validateNodeSlideProviderChoice( + 'propose_edit', + 'openrouter_free', + NODESLIDE_OPENROUTER_EDIT_CONSENT, + id, + ), + `edit ${id}`, + ).toMatchObject({ providerEffort: expected }); + } + // An explicit effort passes through both boundaries untouched. + expect( + validateNodeSlideBriefProviderChoice( + 'openrouter_free', + NODESLIDE_OPENROUTER_BRIEF_CONSENT, + WIRE_ID.opus55, + 'high', + ), + ).toMatchObject({ providerEffort: 'high' }); + }); + + it('a picker with no chosen effort shows the row default; a chosen effort is kept across rows', () => { + // Untouched (null): each row's own default, so switching rows follows it. Opus 5.5 = medium. + expect(nodeSlideEffortForModel(WIRE_ID.opus55, null)).toBe('medium'); + expect(nodeSlideEffortForModel(WIRE_ID.sonnet55, null)).toBe('high'); + expect(nodeSlideEffortForModel('moonshotai/kimi-k3', null)).toBe('high'); + // Chosen: kept on any row that supports it, including an effort equal to the PREVIOUS row's + // default (round 3: Sonnet 5.5 'high' chosen on purpose, then Opus 5.5, used to become 'medium'). + expect(nodeSlideEffortForModel(WIRE_ID.sonnet55, 'high')).toBe('high'); + expect(nodeSlideEffortForModel(WIRE_ID.opus55, 'high')).toBe('high'); + expect(nodeSlideEffortForModel(WIRE_ID.sonnet55, 'medium')).toBe('medium'); + expect(nodeSlideEffortForModel(WIRE_ID.opus55, 'medium')).toBe('medium'); + expect(nodeSlideEffortForModel(WIRE_ID.opus55, 'xhigh')).toBe('xhigh'); + expect(nodeSlideEffortForModel(WIRE_ID.opus55, 'low')).toBe('low'); + // A chosen effort the row does not support falls to that row's default; the choice itself is + // not lost (the picker still holds it), so returning to a supporting row shows it again. + expect(nodeSlideEffortForModel('moonshotai/kimi-k3', 'xhigh')).toBe('high'); + // A stale or foreign saved value is no choice at all. + expect(nodeSlideEffortForModel(WIRE_ID.opus55, 'not-an-effort')).toBe('medium'); + expect(nodeSlideEffortForModel('moonshotai/kimi-k3', 'not-an-effort')).toBe('high'); + }); + + it('every offered row is a priced, temperature-free-or-declared route', () => { + for (const row of NODESLIDE_OFFERED_AGENT_MODELS) { + const id = row.id as NodeSlideAgentModelId; + if ( + id.startsWith('anthropic/claude-') || + id === WIRE_ID.gpt61Sol || + id === WIRE_ID.gemini38Flash + ) { + expect(row.supportsTemperature, `${id} rejects sampling parameters`).toBe(false); + } + } + }); +}); + +describe('Claude rows keep the OpenRouter chat-completions endpoint under pi-ai 1.1.0', () => { + it('pins every bundled anthropic-messages OpenRouter row to /api/v1 chat-completions', () => { + // pi-ai 1.1.0 ships these as api "anthropic-messages" at https://openrouter.ai/api; sent through + // this provider's chat-completions client that is POST /api/chat/completions, not an OpenRouter + // endpoint. The override must normalize them. + const claudeRows = openrouterProviderWithOverrides() + .getModels() + .filter((model) => model.id.startsWith('anthropic/claude-')); + expect(claudeRows.length).toBeGreaterThan(0); + for (const model of claudeRows) { + expect(model.api, model.id).toBe('openai-completions'); + expect(model.baseUrl, model.id).toBe('https://openrouter.ai/api/v1'); + } + }); + + it('keeps the pre-existing Claude rows (sonnet-5, fable-5) on a valid endpoint too', async () => { + for (const modelId of ['anthropic/claude-sonnet-5', 'anthropic/claude-fable-5'] as const) { + captured = []; + await probeNodeSlideModelOnce(modelId); + expect(captured[0]?.url, modelId).toBe('https://openrouter.ai/api/v1/chat/completions'); + expect(captured[0]?.body['model']).toBe(modelId); + expect(Object.keys(captured[0]?.body ?? {})).not.toContain('temperature'); + } + }); +}); + +describe('the routed executor (Homen 2026-11-06: paid DeepSeek V4.1 Flash, exception to D2)', () => { + // SPEC "Homen decisions", NodeSlide executor (2026-11-06). The executor was Gemini 3.8 Flash (SPEC A.2.8, + // after Google deprecated 3.5 Flash on 2026-10-08); Homen moved it to the exact dated OpenRouter id. + const EXECUTOR_WIRE_ID = 'deepseek/deepseek-v4.1-flash-1017'; + + it('routes bulk copy to DeepSeek V4.1 Flash 1017 and the request names exactly that id', async () => { + const decision = resolveNodeSlideRouting({ + task: 'edit_plan', + requestedModel: 'moonshotai/kimi-k3', + replaceTextOps: 3, + }); + expect(decision.reason).toBe('split_premium_planner_bulk_copy'); + expect(decision.executorModel).toBe(EXECUTOR_WIRE_ID); + expect(NODESLIDE_ROUTING_EXECUTOR_MODEL).toBe(EXECUTOR_WIRE_ID); + + await callNodeSlideFreeJson({ + systemPrompt: 'Rewrite the copy.', + userText: '{}', + maxTokens: 500, + model: decision.executorModel as NodeSlideAgentModelId, + reasoningEffort: 'low', + }); + expect(captured.length).toBeGreaterThan(0); + for (const request of captured) { + expect(request.url).toBe('https://openrouter.ai/api/v1/chat/completions'); + expect(request.body['model']).toBe(EXECUTOR_WIRE_ID); + // Not the undated alias, and not the previous executor. + expect(request.body['model']).not.toBe('deepseek/deepseek-v4.1-flash'); + expect(request.body['model']).not.toBe('google/gemini-3.8-flash'); + expect(request.body['reasoning']).toEqual({ effort: 'low' }); + expectNoForbiddenKeys(request.body); + } + }); + + it('sends the executor call the way the budgeted dispatch does: json_schema, max_price at the ledger row', async () => { + // nodeslideBudgetedProvider.ts hands the ledger row's rates to the dispatch policy as the OpenRouter + // max_price ceiling. The executor's copy schema rides as native json_schema (the row has no + // json_object flag), so require_parameters keeps the request on structured-output endpoints. + const pricing = nodeSlideModelPricing(NODESLIDE_ROUTING_EXECUTOR_MODEL); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') return; + await callNodeSlideFreeJson( + { + systemPrompt: 'Rewrite the copy.', + userText: '{}', + maxTokens: 500, + model: NODESLIDE_ROUTING_EXECUTOR_MODEL, + reasoningEffort: 'low', + jsonSchema: { name: 'nodeslide_copy_execution', schema: { type: 'object' } }, + }, + { + dispatchPolicy: { + maxOutputTokens: 500, + maxRetries: 0, + maxInputMicroUsdPerMillionTokens: pricing.inputMicroUsdPerMillionTokens, + maxOutputMicroUsdPerMillionTokens: pricing.outputMicroUsdPerMillionTokens, + }, + }, + ); + expect(captured).toHaveLength(1); + const body = captured[0]?.body ?? {}; + expect(body['model']).toBe(EXECUTOR_WIRE_ID); + expect((body['response_format'] as { type: string }).type).toBe('json_schema'); + // $0.15 in / $0.60 out per million tokens (OpenRouter public list, 2026-11-06). + expect(body['provider']).toMatchObject({ + require_parameters: true, + max_price: { prompt: 0.15, completion: 0.6 }, + }); + expectNoForbiddenKeys(body); + }); + + it('sends the edit patch to Gemini 3.8 Flash as json_object, decided by the catalog flag', async () => { + const editPatchSchema = { + name: 'nodeslide_edit_patch', + schema: { type: 'object', properties: { operations: { type: 'array' } } }, + }; + await callNodeSlideFreeJson({ + systemPrompt: 'Return a patch.', + userText: '{}', + maxTokens: 500, + model: WIRE_ID.gemini38Flash, + reasoningEffort: 'low', + jsonSchema: editPatchSchema, + }); + const first = captured[0]; + expect(first?.body['model']).toBe(WIRE_ID.gemini38Flash); + expect(first?.body['response_format']).toEqual({ type: 'json_object' }); + expectNoForbiddenKeys(first?.body ?? {}); + + // A different schema on the same row still uses native json_schema. + captured = []; + await callNodeSlideFreeJson({ + systemPrompt: 'Return JSON.', + userText: '{}', + maxTokens: 500, + model: WIRE_ID.gemini38Flash, + reasoningEffort: 'low', + jsonSchema: { name: 'other_schema', schema: { type: 'object' } }, + }); + expect((captured[0]?.body['response_format'] as { type: string }).type).toBe('json_schema'); + }); + + it('retires the deprecated Gemini 3.5 Flash row from the offered picker but keeps it resolvable', () => { + const retired = nodeSlideAgentModel('google/gemini-3.5-flash'); + expect(retired.id).toBe('google/gemini-3.5-flash'); + expect(retired.productionEnabled).toBe(false); + expect(NODESLIDE_OFFERED_AGENT_MODELS.map((row) => row.id)).not.toContain( + 'google/gemini-3.5-flash', + ); + }); + + it('removes gpt-oss-20b:free from the free-router candidates but keeps the row', () => { + const row = nodeSlideAgentModel('openai/gpt-oss-20b:free'); + expect(row.id).toBe('openai/gpt-oss-20b:free'); + expect(row.productionEnabled).toBe(false); + expect('freeRouterCandidate' in row).toBe(false); + expect(NODESLIDE_AGENT_MODELS.some((model) => model.id === 'openai/gpt-oss-20b:free')).toBe( + true, + ); + }); + + // OpenRouter's public list dropped the :free id on 2026-10-31 (the paid id remains). + it('removes nemotron-3-super:free from the free-router candidates but keeps the row', () => { + const row = nodeSlideAgentModel('nvidia/nemotron-3-super-120b-a12b:free'); + expect(row.id).toBe('nvidia/nemotron-3-super-120b-a12b:free'); + expect(row.productionEnabled).toBe(false); + expect('freeRouterCandidate' in row).toBe(false); + }); +}); + +// Codex round 3, defect 1. pi-ai sets `AssistantMessage.model = model.id` (the requested id) and keeps +// `responseModel` only when the provider's string differs, so a response that names no model used to +// read back as an echo of the requested one. The executor-split receipt (SPEC A.0.3 `echoedModel`) +// needs the provider's own string, or null. +describe('the provider echo is recorded separately from the requested model', () => { + const sse = (modelField: string) => + [ + `data: {"id":"gen-echo"${modelField},"choices":[{"index":0,"delta":{"role":"assistant","content":"{\\"ok\\":true}"},"finish_reason":null}]}\n\n`, + `data: {"id":"gen-echo"${modelField},"choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}}\n\n`, + 'data: [DONE]\n\n', + ].join(''); + const callWith = async (modelField: string) => { + vi.stubGlobal( + 'fetch', + async () => + new Response(sse(modelField), { + status: 200, + headers: { 'content-type': 'text/event-stream' }, + }), + ); + const result = await callNodeSlideFreeJson({ + systemPrompt: 'Return JSON.', + userText: '{}', + maxTokens: 500, + model: WIRE_ID.gemini38Flash, + }); + if (!result.ok) throw new Error(`call failed: ${result.reason}`); + return result.telemetry; + }; + + it('a response with no model field leaves echoedModel absent while actualModel still reads as the requested id', async () => { + const telemetry = await callWith(''); + expect(telemetry.echoedModel).toBeUndefined(); + // The defect: this is the value the probe used to copy into the receipt. + expect(telemetry.actualModel).toBe(WIRE_ID.gemini38Flash); + }); + + it('a response that echoes exactly the requested id is recorded, though pi-ai drops it', async () => { + const telemetry = await callWith(`,"model":"${WIRE_ID.gemini38Flash}"`); + expect(telemetry.echoedModel).toBe(WIRE_ID.gemini38Flash); + }); + + it('a response that names another model records that model', async () => { + const telemetry = await callWith(',"model":"google/gemini-3.6-flash"'); + expect(telemetry.echoedModel).toBe('google/gemini-3.6-flash'); + }); +}); diff --git a/convex/lib/nodeslideProvider.test.ts b/convex/lib/nodeslideProvider.test.ts index bdd7732e..411e0006 100644 --- a/convex/lib/nodeslideProvider.test.ts +++ b/convex/lib/nodeslideProvider.test.ts @@ -133,7 +133,18 @@ describe('NodeSlide named pi-ai JSON provider', () => { const provider = openrouterProviderWithOverrides(); const models = provider.getModels(); const overrideIds = NODESLIDE_OPENROUTER_MODEL_OVERRIDES.map((model) => model.id); - expect(overrideIds).toEqual(['moonshotai/kimi-k3']); + // The executor's dated id joined on 2026-11-06 (SPEC "Homen decisions"): pi-ai 1.1.0 has no row for it. + expect(overrideIds).toEqual(['moonshotai/kimi-k3', 'deepseek/deepseek-v4.1-flash-1017']); + const expectedCost: Record = { + 'moonshotai/kimi-k3': { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 0 }, + // OpenRouter public list, 2026-11-06T10:39:31Z. + 'deepseek/deepseek-v4.1-flash-1017': { + input: 0.15, + output: 0.6, + cacheRead: 0.003, + cacheWrite: 0, + }, + }; for (const override of NODESLIDE_OPENROUTER_MODEL_OVERRIDES) { const matches = models.filter((model) => model.id === override.id); // Exactly one entry per id: our current definition wins over stale @@ -141,7 +152,7 @@ describe('NodeSlide named pi-ai JSON provider', () => { expect(matches).toHaveLength(1); expect(matches[0]).toMatchObject({ reasoning: true, - cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 0 }, + cost: expectedCost[override.id], contextWindow: 1_048_576, compat: { supportsReasoningEffort: true, @@ -156,8 +167,14 @@ describe('NodeSlide named pi-ai JSON provider', () => { const models = openrouterProviderWithOverrides().getModels(); for (const id of [ 'anthropic/claude-fable-5', + 'anthropic/claude-sonnet-5.5', + 'anthropic/claude-opus-5.5', 'google/gemini-3.5-flash', + 'google/gemini-3.8-flash', 'google/gemini-3.1-pro-preview', + 'openai/gpt-6.1-sol', + // The executor (Homen 2026-11-06); pi-ai 1.1.0 has no row for it, so this is the override. + 'deepseek/deepseek-v4.1-flash-1017', ]) { expect(models.find((model) => model.id === id)).toMatchObject({ reasoning: true }); } @@ -377,6 +394,44 @@ describe('NodeSlide named pi-ai JSON provider', () => { expect(JSON.stringify(result)).not.toContain('still-not-json'); }); + it('maxRetries 0 makes exactly one completion: no JSON-repair call after malformed JSON', async () => { + const complete = vi + .fn() + .mockResolvedValueOnce(completion('not-json')) + .mockResolvedValueOnce(completion('{"operations":[{"op":"replace_text"}]}')); + + const result = await callNodeSlideFreeJson(request, { + complete, + dispatchPolicy: { maxRetries: 0 }, + }); + + expect(result).toMatchObject({ + ok: false, + telemetry: { attempts: [{ attempt: 'initial' }] }, + }); + expect(complete).toHaveBeenCalledTimes(1); + }); + + it('maxRetries 0 also turns off the schema-compatibility retry', async () => { + const complete = vi + .fn() + .mockResolvedValueOnce( + completion('', { + stopReason: 'error', + errorMessage: 'response_format JSON schema is not supported by this endpoint', + }), + ) + .mockResolvedValueOnce(completion('{"operations":[{"op":"replace_text"}]}')); + + const result = await callNodeSlideFreeJson(request, { + complete, + dispatchPolicy: { maxRetries: 0 }, + }); + + expect(result.ok).toBe(false); + expect(complete).toHaveBeenCalledTimes(1); + }); + it('uses the single repair attempt without native schema mode when a route rejects it', async () => { const complete = vi .fn() @@ -625,6 +680,19 @@ describe('NodeSlide named pi-ai JSON provider', () => { reasoningEffort: 'low', maxTokens: 256, }); + // The 2026-10 additions: adaptive thinking counts toward max_tokens, so the Claude 5.5 and + // GPT-6.1 probes get Fable's headroom instead of the 64-token default that starves them. + for (const id of [ + 'anthropic/claude-sonnet-5.5', + 'anthropic/claude-opus-5.5', + 'openai/gpt-6.1-sol', + ] as const) { + expect(nodeSlideModelProbeProfile(id)).toEqual({ reasoningEffort: 'low', maxTokens: 2_048 }); + } + expect(nodeSlideModelProbeProfile('google/gemini-3.8-flash')).toEqual({ + reasoningEffort: 'low', + maxTokens: 256, + }); }); it('returns a sanitized failed receipt when a fleet route times out', async () => { @@ -683,3 +751,58 @@ describe('NodeSlide named pi-ai JSON provider', () => { expect(JSON.stringify(result)).not.toContain('secret-456'); }); }); + +describe('unknown model ids fail closed (SPEC Part A rule 10)', () => { + // Round 1 (Codex): both ids below resolved to the first catalog row, the paid Nebius GLM route, + // and the unguarded probe returned status "passed" for them. + it('throws for an id the catalog does not carry instead of resolving to a paid default', () => { + expect(() => nodeSlideAgentModel('unknown-paid' as never)).toThrow(/not in the catalog/); + expect(() => nodeSlideAgentModel('vendor/model-nobody-sells' as never)).toThrow( + /not in the catalog/, + ); + }); + + it('resolves a free-looking unknown id to the free router row, never to a paid route', () => { + const route = nodeSlideAgentModel('vendor/unlisted-model:free' as never); + expect(route.id).toBe('openrouter/free'); + expect(route.provider).toBe('openrouter'); + expect(route.provider).not.toBe(nodeSlideAgentModel(NODESLIDE_NEBIUS_AGENT_MODEL).provider); + }); + + it('refuses a SPEC 1.2 verified free id the catalog does not serve instead of rerouting it', () => { + for (const id of ['nvidia/nemotron-3.5-lightning:free', 'apodex/apodex-1.1-mini:free']) + expect(() => nodeSlideAgentModel(id as never), id).toThrow(/not rerouted/); + }); + + it('resolves a "-free" suffix to the free router row too, and keeps lookalikes paid-unknown', async () => { + // SPEC A.0.10: free-looking is a "-free" OR ":free" suffix. 'foo-free' used to throw. + for (const id of ['foo-free', 'vendor/unlisted-model-free']) { + const route = nodeSlideAgentModel(id as never); + expect(route.id, id).toBe('openrouter/free'); + } + // Only a suffix counts: "free" elsewhere in the id is not free-looking. + for (const id of ['free-model', 'vendor/freedom', 'vendor/free-tier-pro']) + expect(() => nodeSlideAgentModel(id as never), id).toThrow(/not in the catalog/); + const complete = vi.fn(async () => completion('{"ok":true}')); + await probeNodeSlideModelOnce('foo-free' as never, { complete }); + for (const call of complete.mock.calls) { + expect(call[0]).toMatchObject({ provider: 'openrouter', model: 'openrouter/free' }); + } + }); + + it('the unguarded probe rejects an unknown paid id before any dispatch', async () => { + const complete = vi.fn(async () => completion('{"ok":true}')); + await expect(probeNodeSlideModelOnce('unknown-paid' as never, { complete })).rejects.toThrow( + /not in the catalog/, + ); + expect(complete).not.toHaveBeenCalled(); + }); + + it('the unguarded probe never sends a free-looking unknown id to a paid provider', async () => { + const complete = vi.fn(async () => completion('{"ok":true}')); + await probeNodeSlideModelOnce('unknown:free' as never, { complete }); + for (const call of complete.mock.calls) { + expect(call[0]).toMatchObject({ provider: 'openrouter', model: 'openrouter/free' }); + } + }); +}); diff --git a/convex/lib/nodeslideProvider.ts b/convex/lib/nodeslideProvider.ts index 4b99ce39..6b3ad14d 100644 --- a/convex/lib/nodeslideProvider.ts +++ b/convex/lib/nodeslideProvider.ts @@ -11,14 +11,16 @@ import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completio import { openrouterProvider } from '@earendil-works/pi-ai/providers/openrouter'; import { NODESLIDE_DEFAULT_AGENT_MODEL, - NODESLIDE_DEFAULT_REASONING_EFFORT, type NodeSlideAgentModelId, type NodeSlideExternalProvider, type NodeSlideReasoningEffort, isNodeSlideAgentModelId, nodeSlideAgentModel, + nodeSlideDefaultReasoningEffort, + nodeSlideEditPatchStructuredOutputMode, nodeSlideModelSupportsReasoningEffort, } from '../../shared/nodeslide'; +import { nodeSlideLedgerPricedCost } from '../../shared/nodeslideRunBudget'; export const NODESLIDE_NEBIUS_PROVIDER = 'nebius' as const; /** Backwards-compatible name for the default; requests may select any catalog model. */ @@ -66,10 +68,12 @@ function nebiusProvider() { }); } -// Kimi K3 is newer than pi-ai's bundled OpenRouter catalog, so we register the -// current OpenRouter contract explicitly instead of inheriting Moonshot-direct -// compatibility defaults. -const NODESLIDE_KIMI_K3: Model<'openai-completions'> = { +// Kimi K3 is registered explicitly so OpenRouter's normalized reasoning contract and our +// price (pricingAsOf = the verifiedAt of its ledger row, a held row: NODESLIDE_HELD_PRICE_VERIFIED_AT, +// 2026-10-15T23:08Z) win over bundled metadata instead of inheriting Moonshot-direct compatibility +// defaults. USD per million tokens; the agreement test in +// convex/nodeslideModelPricing.test.ts asserts these equal nodeSlideModelPricing('moonshotai/kimi-k3'). +export const NODESLIDE_KIMI_K3: Model<'openai-completions'> = { id: 'moonshotai/kimi-k3', name: 'MoonshotAI: Kimi K3', api: 'openai-completions', @@ -88,13 +92,42 @@ const NODESLIDE_KIMI_K3: Model<'openai-completions'> = { }, }; +/** + * The routed copy executor (SPEC "Homen decisions", 2026-11-06). pi-ai 1.1.0's bundled OpenRouter + * catalog has no row for the dated id (only deepseek/deepseek-v4.1-flash and :batch), so the route is + * registered here. Cost is the ledger row (USD per million tokens; pricingAsOf = + * NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT, 2026-11-06T10:39:31Z, https://openrouter.ai/api/v1/models: + * $0.15 in / $0.60 out, cache read $0.003); window and output cap from the same read. The agreement + * test in convex/nodeslideModelPricing.test.ts asserts these equal the ledger row. + */ +export const NODESLIDE_DEEPSEEK_V41_FLASH_1017: Model<'openai-completions'> = { + id: 'deepseek/deepseek-v4.1-flash-1017', + name: 'DeepSeek: DeepSeek V4.1 Flash (1017)', + api: 'openai-completions', + provider: 'openrouter', + baseUrl: 'https://openrouter.ai/api/v1', + reasoning: true, + input: ['text'], + cost: { input: 0.15, output: 0.6, cacheRead: 0.003, cacheWrite: 0 }, + contextWindow: 1_048_576, + maxTokens: 393_216, + compat: { + supportsDeveloperRole: false, + supportsReasoningEffort: true, + thinkingFormat: 'openrouter', + maxTokensField: 'max_tokens', + }, +}; + /** * Kimi is newer than the bundled catalog and OpenRouter exposes its reasoning - * effort through the normalized nested reasoning object. Other routes retain - * their bundled metadata and receive only efforts they advertise. + * effort through the normalized nested reasoning object; the executor's dated + * id is absent from it. Other routes retain their bundled metadata and receive + * only efforts they advertise. */ export const NODESLIDE_OPENROUTER_MODEL_OVERRIDES: readonly Model<'openai-completions'>[] = [ NODESLIDE_KIMI_K3, + NODESLIDE_DEEPSEEK_V41_FLASH_1017, ]; const OPENROUTER_CHAT_COMPLETIONS_BASE_URL = 'https://openrouter.ai/api/v1'; @@ -119,6 +152,21 @@ function asOpenRouterChatCompletionsRoute( } as typeof model; } +/** + * The run-budget ledger is the repo's price of record, so a response is priced (`usage.cost.total` -> + * `costMicroUsd`) at the ledger's rate: the bundled pi-ai catalog is an older snapshot and disagreed + * with it on glm-5.2 (0.171 / 7.2 against 0.7686 / 2.4156), so a near-ceiling output-heavy response + * would settle above the quote it was reserved at. `nodeSlideLedgerPricedCost` also caps the + * cached-read rate at the ledger's input rate, so a response served mostly from cache cannot settle + * above the quote either. Any above-threshold tier stays pi-ai's, and rows + * the ledger does not price (free, dynamic) are untouched. + */ +function priceFromLedger< + T extends { id: string; cost: { input: number; output: number; cacheRead: number } }, +>(model: T): T { + return { ...model, cost: nodeSlideLedgerPricedCost(model.id, model.cost) }; +} + export function openrouterProviderWithOverrides() { const builtin = openrouterProvider(); const overridden = new Map( @@ -127,6 +175,7 @@ export function openrouterProviderWithOverrides() { const models = builtin .getModels() .filter((model) => !overridden.has(model.id)) + .map(priceFromLedger) .map(asOpenRouterChatCompletionsRoute); return createProvider({ id: 'openrouter', @@ -156,6 +205,13 @@ export interface NodeSlideProviderTelemetry { actualProvider?: string; /** Provider-returned resolved model only; required to qualify production routes. */ actualModel?: string; + /** + * The `model` string the provider's response carried, verbatim (SPEC A.0.3 `echoedModel`). Absent + * when the provider sent none; never filled from the requested route. `model` and `actualModel` + * fall back to the requested id (pi-ai sets `AssistantMessage.model = model.id`), so neither can + * prove what the provider ran. + */ + echoedModel?: string; responseId?: string; /** Present for current model calls; optional keeps persisted and fixture telemetry compatible. */ reasoningEffort?: NodeSlideReasoningEffort; @@ -191,6 +247,13 @@ export interface NodeSlideDispatchPolicy { maxInputMicroUsdPerMillionTokens?: number; /** Provider-routing ceiling in integer micro-USD per million output tokens. */ maxOutputMicroUsdPerMillionTokens?: number; + /** + * `0` turns off every second completion for the call: the JSON-repair call and the + * structured-output compatibility retry. Absent keeps the default of one retry. It can only + * tighten, so no other value exists. The executor-split probe sets it because its receipt is + * rejected when a paid retry was enabled (SPEC A.0.3), not merely when one happened to run. + */ + maxRetries?: 0; } export interface NodeSlideJsonSchema { @@ -238,6 +301,8 @@ export interface NodeSlideCompletionResult { errorMessage?: string; provider?: string; model?: string; + /** The provider response's own `model` string, verbatim; absent when the response carried none. */ + echoedModel?: string; responseId?: string; costMicroUsd: number; inputTokens: number; @@ -402,8 +467,13 @@ export function nodeSlideModelProbeProfile(modelId: NodeSlideAgentModelId): { case 'z-ai/glm-5.2': return { reasoningEffort: 'high', maxTokens: 512 }; case 'anthropic/claude-fable-5': + case 'anthropic/claude-sonnet-5.5': + case 'anthropic/claude-opus-5.5': + case 'openai/gpt-6.1-sol': + // Adaptive thinking counts toward max_tokens; a one-character reply must survive it. return { reasoningEffort: 'low', maxTokens: 2_048 }; case 'google/gemini-3.5-flash': + case 'google/gemini-3.8-flash': case 'google/gemini-3.1-pro-preview': return { reasoningEffort: 'low', maxTokens: 256 }; default: @@ -425,10 +495,10 @@ export async function callNodeSlideFreeJson( ): Promise { const complete = dependencies.complete ?? completeNodeSlideWithPiAi; const selectedModel = args.model ?? NODESLIDE_DEFAULT_AGENT_MODEL; - const reasoningEffort = args.reasoningEffort ?? NODESLIDE_DEFAULT_REASONING_EFFORT; if (!isNodeSlideAgentModelId(selectedModel)) { return { ok: false, reason: 'Choose a supported NodeSlide agent model.' }; } + const reasoningEffort = args.reasoningEffort ?? nodeSlideDefaultReasoningEffort(selectedModel); if (!nodeSlideModelSupportsReasoningEffort(selectedModel, reasoningEffort)) { return { ok: false, @@ -453,8 +523,10 @@ export async function callNodeSlideFreeJson( const onTextDelta = dependencies.onTextDelta ?? args.onTextDelta; try { - // Exactly two model calls are possible: the initial completion and one JSON-repair completion. - for (let attempt = 0; attempt < 2; attempt += 1) { + // At most two model calls: the initial completion and one JSON-repair completion, unless the + // dispatch policy turned retries off (`maxRetries: 0`), which leaves exactly one. + const maxAttempts = dependencies.dispatchPolicy?.maxRetries === 0 ? 1 : 2; + for (let attempt = 0; attempt < maxAttempts; attempt += 1) { const repairAttempt = attempt === 1; const attemptTelemetry = startAttemptTelemetry(repairAttempt); telemetry.attempts?.push(attemptTelemetry); @@ -514,7 +586,7 @@ export async function callNodeSlideFreeJson( if (result.stopReason === 'error') { if ( - attempt === 0 && + attempt + 1 < maxAttempts && args.jsonSchema && structuredOutputMode === 'json_schema' && shouldRetryStructuredOutputCompatibility(result) @@ -552,7 +624,9 @@ export async function callNodeSlideFreeJson( } } return providerFailure( - `The ${routeLabel} route returned invalid JSON after one repair attempt.`, + maxAttempts === 1 + ? `The ${routeLabel} route returned invalid JSON and retries were disabled.` + : `The ${routeLabel} route returned invalid JSON after one repair attempt.`, telemetry, hasTelemetry, ); @@ -667,8 +741,12 @@ function preferredStructuredOutputMode( // OpenRouter's Gemini route accepts ordinary JSON schemas, but the edit planner's // dynamically scoped union is large enough to be rejected before token generation. // Keep the exact schema in the prompt and validate it locally; json_object only - // changes provider transport, never the accepted NodeSlide contract. - if (model === 'google/gemini-3.5-flash' && jsonSchema.name === 'nodeslide_edit_patch') { + // changes provider transport, never the accepted NodeSlide contract. The decision is a + // catalog flag (`structuredOutputMode`), stated per row, not a model-id literal. + if ( + jsonSchema.name === 'nodeslide_edit_patch' && + nodeSlideEditPatchStructuredOutputMode(model) === 'json_object' + ) { return 'json_object'; } return 'json_schema'; @@ -728,6 +806,7 @@ async function completeNodeSlideWithPiAi( ], }; const reasoningDisabled = request.provider === 'openrouter' && model.reasoning === false; + let echoedModel: string | undefined; const options = { signal: request.signal, maxTokens: request.maxTokens, @@ -737,6 +816,13 @@ async function completeNodeSlideWithPiAi( ...(reasoningDisabled ? {} : { reasoningEffort: request.reasoningEffort }), ...(request.supportsTemperature ? { temperature: 0 } : {}), ...(request.provider === 'openrouter' ? { headers: OPENROUTER_ATTRIBUTION_HEADERS } : {}), + // pi-ai keeps `AssistantMessage.responseModel` only when the chunk's model differs from the + // requested id, so an exact echo is indistinguishable from no echo there. Read the raw chunk. + onProviderStreamEvent: (chunk: unknown) => { + const echoed = (chunk as { model?: unknown } | null)?.model; + if (echoedModel === undefined && typeof echoed === 'string' && echoed.length > 0) + echoedModel = echoed; + }, onPayload: (payload: unknown) => nodeSlideProviderPayload(payload, request.jsonSchema, { provider: request.provider, @@ -767,10 +853,13 @@ async function completeNodeSlideWithPiAi( } else { result = await nodeSlideModels.complete(model, context, options); } - return completionResult(result); + return completionResult(result, echoedModel ?? result.responseModel); } -function completionResult(result: AssistantMessage): NodeSlideCompletionResult { +function completionResult( + result: AssistantMessage, + echoedModel: string | undefined, +): NodeSlideCompletionResult { const text = result.content .filter((block): block is TextContent => block.type === 'text') .map((block) => block.text) @@ -781,6 +870,7 @@ function completionResult(result: AssistantMessage): NodeSlideCompletionResult { ...(result.errorMessage ? { errorMessage: result.errorMessage } : {}), provider: result.provider, model: result.responseModel ?? result.model, + ...(echoedModel ? { echoedModel } : {}), ...(result.responseId ? { responseId: result.responseId } : {}), costMicroUsd: usdToMicroUsd(result.usage.cost.total), inputTokens: result.usage.input, @@ -993,6 +1083,11 @@ function addTelemetry( : telemetry.actualModel ? { actualModel: telemetry.actualModel } : {}), + ...(result.echoedModel + ? { echoedModel: result.echoedModel } + : telemetry.echoedModel + ? { echoedModel: telemetry.echoedModel } + : {}), ...(result.responseId ? { responseId: result.responseId } : telemetry.responseId diff --git a/convex/lib/nodeslideProviderConsent.ts b/convex/lib/nodeslideProviderConsent.ts index c05d7fda..327e2b25 100644 --- a/convex/lib/nodeslideProviderConsent.ts +++ b/convex/lib/nodeslideProviderConsent.ts @@ -1,5 +1,4 @@ import { - NODESLIDE_DEFAULT_REASONING_EFFORT, NODESLIDE_NEBIUS_REVIEW_CONSENT, NODESLIDE_NEBIUS_VARIATIONS_CONSENT, NODESLIDE_OPENROUTER_EDIT_CONSENT, @@ -12,6 +11,7 @@ import { isNodeSlideReasoningEffort, nodeSlideAgentModel, nodeSlideDefaultModelForProviderMode, + nodeSlideDefaultReasoningEffort, nodeSlideModelSupportsReasoningEffort, } from '../../shared/nodeslide'; @@ -100,7 +100,7 @@ export function validateNodeSlideProviderChoice( `The selected model is not available through ${providerName}.`, ); } - const selectedEffort = providerEffort ?? NODESLIDE_DEFAULT_REASONING_EFFORT; + const selectedEffort = providerEffort ?? nodeSlideDefaultReasoningEffort(selectedModel); if (!isNodeSlideReasoningEffort(selectedEffort)) { throw new NodeSlideProviderConsentError( 'invalid_request', diff --git a/convex/lib/nodeslideReviewUi.test.tsx b/convex/lib/nodeslideReviewUi.test.tsx index 06716af4..59f33419 100644 --- a/convex/lib/nodeslideReviewUi.test.tsx +++ b/convex/lib/nodeslideReviewUi.test.tsx @@ -147,12 +147,17 @@ describe('NodeSlide AI review inspector', () => { expect.arrayContaining([ 'Claude Sonnet 5 · Anthropic', 'Claude Fable 5 · Anthropic', - 'Gemini 3.5 Flash · Google', + 'Claude Sonnet 5.5 · Anthropic', + 'Claude Opus 5.5 · Anthropic', + // Gemini 3.5 Flash left the offered set: Google deprecated it on 2026-10-08. + 'Gemini 3.8 Flash · Google', 'Gemini 3.1 Pro · Google', 'GPT-5.6 Sol · OpenAI', 'GPT-5.6 Terra · OpenAI', + 'GPT-6.1 Sol · OpenAI', ]), ); + expect(modelLabels).not.toContain('Gemini 3.5 Flash · Google'); expect(markup).not.toMatch(/ai-provider-consent/); expect(createAiProviderRequest('nebius', false)).toBeNull(); @@ -182,6 +187,25 @@ describe('NodeSlide AI review inspector', () => { ).toMatchObject({ providerModel: 'anthropic/claude-sonnet-5' }); }); + it('an omitted effort takes the row default (Opus 5.5 medium); an explicit effort is kept', () => { + // SPEC A.2.8: Opus 5.5 defaults to medium, every other row to high. These builders are a + // defaulting boundary: they used to default every model to high. + for (const [model, effort] of [ + ['anthropic/claude-opus-5.5', 'medium'], + ['anthropic/claude-sonnet-5.5', 'high'], + ] as const) { + expect(createAiProviderRequest('openrouter_free', true, model)).toMatchObject({ + providerEffort: effort, + }); + expect(createAiVariationProviderRequest('openrouter_free', true, model)).toMatchObject({ + providerEffort: effort, + }); + } + expect( + createAiProviderRequest('openrouter_free', true, 'anthropic/claude-opus-5.5', 'high'), + ).toMatchObject({ providerEffort: 'high' }); + }); + it('shows extended effort levels only for models whose provider exposes them', () => { const markup = renderAi({ initialProviderMode: 'openrouter_free', diff --git a/convex/lib/nodeslideRoutedProposeEdit.test.ts b/convex/lib/nodeslideRoutedProposeEdit.test.ts index 8a20e23b..67ae88d4 100644 --- a/convex/lib/nodeslideRoutedProposeEdit.test.ts +++ b/convex/lib/nodeslideRoutedProposeEdit.test.ts @@ -176,7 +176,11 @@ describe('proposeEdit routed attribution (B2)', () => { spanModel: NODESLIDE_ROUTING_EXECUTOR_MODEL, role: 'tool', }); - expect(String(executorRow?.['message'])).toContain('Executor · Gemini 3.5 Flash'); + // Was 'Executor · Gemini 3.5 Flash': Google deprecated 3.5 Flash on 2026-10-08 (auto-routed to + // 3.6) and SPEC A.2.8 moved the executor to 3.8 Flash ('Executor · Gemini 3.8 Flash'); SPEC "Homen + // decisions" (2026-11-06) moves it to the paid deepseek/deepseek-v4.1-flash-1017. The ledger here is + // the real one (priced route, admitted), not a stand-in, so this is what production persists. + expect(String(executorRow?.['message'])).toContain('Executor · DeepSeek V4.1 Flash'); const proposal = mutations.find((args) => 'operations' in args && 'traceContext' in args); expect(proposal).toBeDefined(); diff --git a/convex/lib/nodeslideRoutingPolicy.test.ts b/convex/lib/nodeslideRoutingPolicy.test.ts index aa548dfb..993e43cc 100644 --- a/convex/lib/nodeslideRoutingPolicy.test.ts +++ b/convex/lib/nodeslideRoutingPolicy.test.ts @@ -80,11 +80,24 @@ describe('NodeSlide routing policy (B2 orchestrator/worker split)', () => { expect(decision.reason).toBe('no_split_planner_is_executor'); }); + it('routes the executor to the paid DeepSeek V4.1 Flash dated id (Homen, 2026-11-06)', () => { + // SPEC "Homen decisions", NodeSlide executor (2026-11-06): an exception to D2 for this role only, + // the exact dated id, not the deepseek-v4.1-flash alias. Was 'google/gemini-3.8-flash' (SPEC A.2.8). + expect(NODESLIDE_ROUTING_EXECUTOR_MODEL).toBe('deepseek/deepseek-v4.1-flash-1017'); + expect(isPremiumNodeSlidePlannerModel(NODESLIDE_ROUTING_EXECUTOR_MODEL)).toBe(false); + }); + it('classifies premium families by id segment, not by loose substring', () => { expect(isPremiumNodeSlidePlannerModel('moonshotai/kimi-k3')).toBe(true); expect(isPremiumNodeSlidePlannerModel('anthropic/claude-fable-5')).toBe(true); expect(isPremiumNodeSlidePlannerModel('openai/gpt-5.6-sol')).toBe(true); + // Gemini 3.5 Flash was the executor until Google deprecated it on 2026-10-08; 3.8 replaced it, and + // DeepSeek V4.1 Flash replaced 3.8 on 2026-11-06 (test above). Neither Flash row is premium. + expect(isPremiumNodeSlidePlannerModel('google/gemini-3.8-flash')).toBe(false); expect(isPremiumNodeSlidePlannerModel('google/gemini-3.5-flash')).toBe(false); + expect(isPremiumNodeSlidePlannerModel('anthropic/claude-sonnet-5.5')).toBe(true); + expect(isPremiumNodeSlidePlannerModel('anthropic/claude-opus-5.5')).toBe(true); + expect(isPremiumNodeSlidePlannerModel('openai/gpt-6.1-sol')).toBe(true); expect(isPremiumNodeSlidePlannerModel('z-ai/glm-5.2')).toBe(false); }); }); diff --git a/convex/lib/nodeslideRoutingPolicy.ts b/convex/lib/nodeslideRoutingPolicy.ts index fc427c36..644889a7 100644 --- a/convex/lib/nodeslideRoutingPolicy.ts +++ b/convex/lib/nodeslideRoutingPolicy.ts @@ -7,7 +7,7 @@ * contract unchanged. Keep this file dependency-free. * * Default policy: the planner is always the requested model. A cheap executor - * (Gemini 3.5 Flash) is granted ONLY when the planner is a premium model + * (DeepSeek V4.1 Flash) is granted ONLY when the planner is a premium model * (Kimi / Claude / GPT) AND the plan contains at least two replace_text * operations worth of copy work. Everything else runs single-model. * The executor is always advisory: on failure or timeout the planner's own @@ -16,7 +16,14 @@ export const NODESLIDE_ROUTING_POLICY_VERSION = 'nodeslide.model-routing/v1' as const; -export const NODESLIDE_ROUTING_EXECUTOR_MODEL = 'google/gemini-3.5-flash' as const; +// Gemini 3.5 Flash was deprecated by Google on 2026-10-08 (requests auto-route to 3.6); SPEC A.2.8 +// moved the executor to 'google/gemini-3.8-flash'. SPEC "Homen decisions", NodeSlide executor +// (2026-11-06): the executor is the paid OpenRouter route deepseek/deepseek-v4.1-flash-1017, an +// exception to D2 for this role only, the exact dated id, not the ~latest alias. The role needs a route +// the run-budget ledger admits: the ledger denies every zero-priced `:free` route (`dynamicRoute`, +// shared/nodeslideRunBudget.ts), so a `:free` executor is refused before dispatch on every edit and the +// split never runs. live-unverified until Homen adds OPENROUTER_API_KEY (no paid executor receipt yet). +export const NODESLIDE_ROUTING_EXECUTOR_MODEL = 'deepseek/deepseek-v4.1-flash-1017' as const; /** Minimum replace_text operations before splitting copy work to an executor. */ export const NODESLIDE_ROUTING_MIN_REPLACE_TEXT_OPS = 2 as const; diff --git a/convex/lib/nodeslideValidators.ts b/convex/lib/nodeslideValidators.ts index d88c260a..97f30087 100644 --- a/convex/lib/nodeslideValidators.ts +++ b/convex/lib/nodeslideValidators.ts @@ -1,6 +1,5 @@ import { ConvexError, v } from 'convex/values'; import { - NODESLIDE_DEFAULT_REASONING_EFFORT, type NodeSlideAgentModelId, type NodeSlideReasoningEffort, isNodeSlideAgentModelId, @@ -8,6 +7,7 @@ import { isNodeSlideReasoningEffort, nodeSlideAgentModel, nodeSlideDefaultModelForProviderMode, + nodeSlideDefaultReasoningEffort, nodeSlideModelSupportsReasoningEffort, } from '../../shared/nodeslide'; import { @@ -178,7 +178,7 @@ export function validateNodeSlideBriefProviderChoice( `The selected model is not available through ${providerName}.`, ); } - const selectedEffort = providerEffort ?? NODESLIDE_DEFAULT_REASONING_EFFORT; + const selectedEffort = providerEffort ?? nodeSlideDefaultReasoningEffort(selectedModel); if (!isNodeSlideReasoningEffort(selectedEffort)) { throw nodeslideCreatePublicError( 'invalid_request', @@ -718,10 +718,14 @@ export const nodeslideAgentModelValidator = v.union( v.literal('z-ai/glm-5.2'), v.literal('anthropic/claude-sonnet-5'), v.literal('anthropic/claude-fable-5'), + v.literal('anthropic/claude-sonnet-5.5'), + v.literal('anthropic/claude-opus-5.5'), v.literal('google/gemini-3.5-flash'), + v.literal('google/gemini-3.8-flash'), v.literal('google/gemini-3.1-pro-preview'), v.literal('openai/gpt-5.6-sol'), v.literal('openai/gpt-5.6-terra'), + v.literal('openai/gpt-6.1-sol'), v.literal('openrouter/free'), v.literal('google/gemma-4-26b-a4b-it:free'), v.literal('google/gemma-4-31b-it:free'), diff --git a/convex/nodeslideBudgetWiring.test.ts b/convex/nodeslideBudgetWiring.test.ts index dc419ca8..722c44e9 100644 --- a/convex/nodeslideBudgetWiring.test.ts +++ b/convex/nodeslideBudgetWiring.test.ts @@ -471,11 +471,14 @@ describe('the price table landed, so the withholding is over', () => { }); it('exports the complete ledger lifecycle and nothing beyond it', () => { + // `receiptForRun` is the one read-only addition (SPEC Part A section A.2.8): the public meter a + // campaign runner charges a run from. Every other export is an internal mutation or query. expect(Object.keys(budgets).sort()).toEqual([ 'captureTimeout', 'create', 'finalize', 'finalizeForJob', + 'receiptForRun', 'release', 'replay', 'reserve', @@ -567,3 +570,67 @@ describe('the price table landed, so the withholding is over', () => { expect(database.rows('nodeslide_billable_calls')).toEqual([]); }); }); + +describe('receiptForRun is the campaign meter for one run', () => { + const RUN_ID = 'nsrun-campaign-meter-1'; + + it('uses the same budget id the provider binds for that run id', async () => { + const { nodeSlideProviderBudgetId } = await import('./lib/nodeslideBudgetedProvider'); + const database = new MemoryDatabase(); + const { ctx } = recordingContext(database); + await rawHandler(budgets.create)(ctx, { + budgetId: nodeSlideProviderBudgetId(RUN_ID), + budget: { maxCostUsd: 2 }, + }); + + const receipt = await rawHandler(budgets.receiptForRun)(readContext(database), { + runId: RUN_ID, + }); + + expect(receipt).toMatchObject({ + version: 'nodeslide.run-budget-ledger-receipt/v1', + budgetId: nodeSlideProviderBudgetId(RUN_ID), + status: 'open', + cap: { maxCostMicroUsd: 2_000_000 }, + spend: { actualMicroUsd: 0, reservedMicroUsd: 0, unreconciledMicroUsd: 0 }, + }); + }); + + it('reports held reservations as spend exposure rather than hiding them', async () => { + const { nodeSlideProviderBudgetId } = await import('./lib/nodeslideBudgetedProvider'); + const database = new MemoryDatabase(); + const { ctx } = recordingContext(database); + const budgetId = nodeSlideProviderBudgetId(RUN_ID); + await rawHandler(budgets.create)(ctx, { budgetId, budget: { maxCostUsd: 2 } }); + const opened = database.rows('nodeslide_run_budgets')[0] as Record; + await rawHandler(budgets.reserve)(ctx, { + budgetId, + callId: 'call-meter-1', + model: 'moonshotai/kimi-k3', + estimatedInputTokens: 10_000, + requestedMaxOutputTokens: 2_000, + expectedRevision: opened.revision, + expectedStateDigest: opened.stateDigest, + }); + + const receipt = (await rawHandler(budgets.receiptForRun)(readContext(database), { + runId: RUN_ID, + })) as { spend: Record }; + + expect(receipt.spend).toEqual({ + actualMicroUsd: 0, + reservedMicroUsd: 60_000, + unreconciledMicroUsd: 0, + }); + }); + + it('answers null for a run that never opened a ledger row, and for a malformed id', async () => { + const database = new MemoryDatabase(); + await expect( + rawHandler(budgets.receiptForRun)(readContext(database), { runId: 'never-ran' }), + ).resolves.toBeNull(); + await expect( + rawHandler(budgets.receiptForRun)(readContext(database), { runId: '' }), + ).resolves.toBeNull(); + }); +}); diff --git a/convex/nodeslideBudgets.ts b/convex/nodeslideBudgets.ts index cf98eb6e..bd28b496 100644 --- a/convex/nodeslideBudgets.ts +++ b/convex/nodeslideBudgets.ts @@ -22,6 +22,7 @@ */ import { v } from 'convex/values'; import { + NODESLIDE_RUN_BUDGET_LEDGER_RECEIPT_VERSION, NODESLIDE_RUN_BUDGET_RECEIPT_VERSION, type NodeSlideRunBudget, type NodeSlideRunBudgetPreflightDenialReason, @@ -35,6 +36,7 @@ import { type QueryCtx, internalMutation, internalQuery, + query, } from './_generated/server'; import { NODESLIDE_BILLABLE_CALL_VERSION, @@ -64,6 +66,7 @@ import { reserveNodeSlideBudgetCost, settleNodeSlideBudgetCost, } from './lib/nodeslideBudgetLedger'; +import { nodeslideStableId } from './lib/nodeslideIds'; import { accountNodeSlideRunBudgetReceipt, nodeSlideRunBudgetReceiptDigest, @@ -509,6 +512,43 @@ export const replay = internalQuery({ }, }); +/** + * What one run cost, read from the hard-budget ledger: the only reservation path + * (`convex/lib/nodeslideBudgetedProvider.ts` is the only caller of `reserve`), so + * this is the meter a campaign runner can trust, unlike the Trace inspector text, + * which is attribution. Keyed by the same opaque id the provider binds, + * `nodeSlideProviderBudgetId(runId)` = `nodeslideStableId('nsbudget', runId)` (a + * test pins the equality; the provider module is not imported here because it + * drags the model SDK into a query bundle). + * + * Public on purpose: the campaign runner has no owner credential for a run it did + * not create. The budget id is a hash of an unguessable run id, and the result is + * counters only (no prompt, no deck, no key). `reserved` and `unreconciled` + * exposure are returned separately: a dispatch whose outcome never came back may + * still have been billed, and the caller must count it. + */ +export const receiptForRun = query({ + args: { runId: v.string() }, + handler: async (ctx, args) => { + if (args.runId.length < 1 || args.runId.length > 512) return null; + const budget = await findBudget(ctx, nodeslideStableId('nsbudget', args.runId)); + if (!budget) return null; + return { + version: NODESLIDE_RUN_BUDGET_LEDGER_RECEIPT_VERSION, + budgetId: budget.id, + status: budget.status, + cap: { maxCostMicroUsd: budget.budget.maxCostMicroUsd }, + spend: { + actualMicroUsd: budget.actualMicroUsd, + reservedMicroUsd: budget.reservedMicroUsd, + unreconciledMicroUsd: budget.unreconciledMicroUsd, + }, + revision: budget.revision, + stateDigest: budget.stateDigest, + }; + }, +}); + const zeroCostDeltas = { actualDeltaMicroUsd: 0, reservedDeltaMicroUsd: 0, diff --git a/convex/nodeslideExecutorSplitProbeBudget.test.ts b/convex/nodeslideExecutorSplitProbeBudget.test.ts new file mode 100644 index 00000000..52fa6fc8 --- /dev/null +++ b/convex/nodeslideExecutorSplitProbeBudget.test.ts @@ -0,0 +1,242 @@ +/** + * The executor probe's committed budget cap, checked against the REAL ledger. + * + * Situation: an operator runs `npx convex run nodeslideModelProbe:runExecutorSplit` with no + * configuration. The probe sends a premium-planner edit turn (kimi-k3, 3 / 15 USD per million tokens) + * through the reserve-before-dispatch provider, and the ledger reserves the WORST CASE of a call + * before the call is made. That worst case is far above what the call costs, so a cap sized for the + * cost refuses the planner before anything is dispatched, and the whole receipt is lost. + * + * This is what hid it: `scripts/tests/executor-split-probe.test.mjs` uses a fake ledger that quotes a + * flat 50,000 micro-USD per call (0.10 USD for the two calls), so a 0.25 USD cap looked generous. + * Here the reservation is computed by the real `nodeslideBudgets` mutations against an in-memory + * database, from the real price table and the real request the probe builds. Codex's replay of the + * same inputs (2026-10-16): kimi-k3 planner 114,252 input / 4,400 output tokens = 0.408756 USD, + * gemini-3.8-flash executor 107,010 / 4,000 = 0.095258 USD, 0.504014 USD together; 0.25 USD refused + * the planner, 0.55 USD admitted both (SPEC D3, Homen 2026-10-16: default 0.55 USD). + * + * Executor moved to deepseek/deepseek-v4.1-flash-1017 (SPEC "Homen decisions", 2026-11-06; ledger row + * 0.15 / 0.60 USD per million tokens, OpenRouter public list read 2026-11-06): the same 107,010 / 4,000 + * tokens reserve 18,451.5 -> 18,452 micro-USD (rounded up) = 0.018452 USD, so planner plus executor is + * 0.427208 USD (was 0.504014). The committed 0.55 USD cap is unchanged and still admits both; 0.25 USD + * still refuses the planner alone. + * + * Only the HTTP call is faked: no provider is contacted and nothing is spent. + */ +import { describe, expect, it, vi } from 'vitest'; +import { executorSplitReceiptFailures } from '../scripts/lib/model-fleet-receipt-core.mjs'; +import type { MutationCtx } from './_generated/server'; +import type { NodeSlideBudgetLedgerClient } from './lib/nodeslideBudgetedProvider'; +import { + NODESLIDE_EXECUTOR_SPLIT_DEFAULT_BUDGET_USD, + executorSplitProbeBudgetUsd, + runNodeSlideExecutorSplitProbe, +} from './lib/nodeslideExecutorSplitProbe'; +import { NODESLIDE_ROUTING_EXECUTOR_MODEL } from './lib/nodeslideRoutingPolicy'; +import { buildGoldenNodeSlide } from './lib/nodeslideSeed'; +import * as budgets from './nodeslideBudgets'; + +const state = vi.hoisted(() => ({ + calls: [] as string[], + planner: undefined as unknown, +})); + +vi.mock('./lib/nodeslideProvider', async (importOriginal) => { + const actual = await importOriginal(); + const attempt = { + attempt: 'initial', + attempted: true, + settled: true, + ambiguous: false, + unreconciled: false, + elapsedMs: 1, + }; + return { + ...actual, + callNodeSlideFreeJson: vi.fn( + async (request: { model: string; jsonSchema?: { name: string } }) => { + state.calls.push(request.model); + const isExecutor = request.jsonSchema?.name === 'nodeslide_copy_execution'; + const plan = state.planner as { operations: { elementId: string }[] }; + return { + ok: true, + value: isExecutor + ? { + copy: plan.operations.map((op) => ({ + elementId: op.elementId, + text: 'Executor copy', + })), + } + : plan, + telemetry: { + provider: 'openrouter', + requestedModel: request.model, + model: request.model, + actualProvider: 'openrouter', + actualModel: request.model, + echoedModel: request.model, + costMicroUsd: 1_000, + inputTokens: 120, + outputTokens: 40, + attempts: [attempt], + }, + }; + }, + ), + }; +}); + +type Row = Record & { _id: string; _creationTime: number }; + +/** The minimum of Convex's `ctx.db` that `nodeslideBudgets` uses, over plain arrays. */ +class MemoryDatabase { + private readonly tables = new Map(); + private sequence = 0; + query(tableName: string) { + const filters: { field: string; value: unknown }[] = []; + const rows = () => + (this.tables.get(tableName) ?? []).filter((row) => + filters.every((filter) => row[filter.field] === filter.value), + ); + const query = { + withIndex: (_name: string, configure: (index: unknown) => unknown) => { + const index = { + eq(field: string, value: unknown) { + filters.push({ field, value }); + return index; + }, + gt: () => index, + }; + configure(index); + return query; + }, + order: () => query, + take: async (count: number) => rows().slice(0, count), + collect: async () => rows(), + first: async () => rows()[0] ?? null, + unique: async () => { + if (rows().length > 1) throw new Error('Memory query was not unique.'); + return rows()[0] ?? null; + }, + }; + return query; + } + async insert(tableName: string, value: Record) { + this.sequence += 1; + const row = { + ...structuredClone(value), + _id: `${tableName}:${this.sequence}`, + _creationTime: this.sequence, + }; + this.tables.set(tableName, [...(this.tables.get(tableName) ?? []), row]); + return row._id; + } + async patch(rowId: string, value: Record) { + for (const rows of this.tables.values()) { + const row = rows.find((candidate) => candidate._id === rowId); + if (row) return void Object.assign(row, structuredClone(value)); + } + throw new Error(`Memory row ${rowId} was not found.`); + } + async get(rowId: string) { + for (const rows of this.tables.values()) { + const row = rows.find((candidate) => candidate._id === rowId); + if (row) return row; + } + return null; + } +} + +/** The binding `convex/nodeslideAgent.ts` builds, with every mutation body being production code. */ +function realLedgerClient(database: MemoryDatabase): NodeSlideBudgetLedgerClient { + const ctx = { db: database } as unknown as MutationCtx; + const call = (fn: unknown) => (args: Record) => { + const handler = (fn as { _handler?: (ctx: unknown, args: unknown) => Promise }) + ._handler; + if (typeof handler !== 'function') throw new Error('Expected a Convex function handler.'); + return handler(ctx, args); + }; + return { + create: call(budgets.create), + reserve: call(budgets.reserve), + settle: call(budgets.settle), + captureTimeout: call(budgets.captureTimeout), + release: call(budgets.release), + replay: call(budgets.replay), + } as unknown as NodeSlideBudgetLedgerClient; +} + +const COMMIT = 'a'.repeat(40); + +async function probe(budgetUsd: number) { + state.calls.length = 0; + // The planner's reply must name real element ids of the probe's own fixture deck. + const snapshot = buildGoldenNodeSlide('executor-split-probe', 1_700_000_000_000).snapshot; + const bySlide = new Map(); + for (const element of snapshot.elements) { + if (element.kind !== 'text' || element.locked) continue; + bySlide.set(element.slideId, [...(bySlide.get(element.slideId) ?? []), element]); + } + const [a, b] = [...bySlide.values()].find((elements) => elements.length >= 2) ?? []; + if (!a || !b) throw new Error('The probe fixture needs a slide with two text blocks.'); + state.planner = { + summary: 'Rewrite two blocks.', + operations: [ + { op: 'replace_text', slideId: a.slideId, elementId: a.id, text: 'Planner one' }, + { op: 'replace_text', slideId: b.slideId, elementId: b.id, text: 'Planner two' }, + ], + copyBriefs: [ + { slideId: a.slideId, elementId: a.id, brief: 'Opening statement.' }, + { slideId: b.slideId, elementId: b.id, brief: 'Proof point.' }, + ], + }; + return await runNodeSlideExecutorSplitProbe({ + ledger: realLedgerClient(new MemoryDatabase()), + buildIdentity: { schemaVersion: 'nodeslide.convex-build-identity/v1', commitSha: COMMIT }, + budgetUsd, + }); +} + +describe('the executor probe cap against the real ledger (SPEC D3)', () => { + it('commits 0.55 USD as the default on dev and on the nightly probe', () => { + expect(NODESLIDE_EXECUTOR_SPLIT_DEFAULT_BUDGET_USD).toBe(0.55); + // The nightly workflow and a bare `npx convex run` both read this: no env var is set for either. + expect(executorSplitProbeBudgetUsd({})).toBe(0.55); + }); + + it('refuses the planner at the old 0.25 USD cap before any request is dispatched', async () => { + const receipt = await probe(0.25); + expect(state.calls).toEqual([]); + expect(receipt.budget.requests).toBe(0); + expect(receipt.budget.stoppedBy).not.toBeNull(); + expect(receipt.routing.reason).toBe('planner_failed'); + }); + + it('admits planner plus the priced executor under the default cap (0.427208 USD; 0.504014 with the Gemini executor)', async () => { + const receipt = await probe(executorSplitProbeBudgetUsd({})); + // The planner goes first; the ledger then admits the executor too (a priced route, unlike a :free one). + expect(state.calls).toEqual(['moonshotai/kimi-k3', NODESLIDE_ROUTING_EXECUTOR_MODEL]); + expect(receipt.budget.refusals).toEqual([]); + expect(receipt.budget.stoppedBy).toBeNull(); + // 0.408756 planner (114,252 input / 4,400 output estimated tokens at 3 / 15 USD per million) plus + // 0.018452 executor (107,010 / 4,000 at deepseek-v4.1-flash-1017's 0.15 / 0.60). With the previous + // gemini-3.8-flash executor (0.75 / 3.75) the executor term was 0.095258 and the total 0.504014, the + // real-ledger figures Codex replayed on 2026-10-16. + expect(receipt.budget.estimateUsd).toBeCloseTo(0.408756 + 0.018452, 6); + expect(receipt.budget.estimateUsd).toBeGreaterThan(0.25); + expect(receipt.budget.estimateUsd).toBeLessThanOrEqual( + NODESLIDE_EXECUTOR_SPLIT_DEFAULT_BUDGET_USD, + ); + }); +}); + +describe('what the real ledger does with the committed executor', () => { + it('reserves, sends and records the executor, and the receipt passes the acceptance gate', async () => { + const receipt = await probe(executorSplitProbeBudgetUsd({})); + expect(receipt.routing).toMatchObject({ + executorModel: NODESLIDE_ROUTING_EXECUTOR_MODEL, + executorOutcome: 'applied', + }); + expect(executorSplitReceiptFailures(receipt, COMMIT)).toEqual([]); + }); +}); diff --git a/convex/nodeslideModelPricing.test.ts b/convex/nodeslideModelPricing.test.ts index 1b0d53a2..da1295a4 100644 --- a/convex/nodeslideModelPricing.test.ts +++ b/convex/nodeslideModelPricing.test.ts @@ -7,7 +7,7 @@ * table transcribed by hand between them can be wrong by three orders of * magnitude without looking wrong. So the catalog values are restated here, in * the provider's own units and exactly as the catalog printed them on - * 2026-07-28, and the test does the conversion itself. + * 2026-10-14, and the test does the conversion itself. * * That is deliberately a SECOND transcription, not an import. Importing the * table and asserting it equals itself would pass on any value at all. If these @@ -19,9 +19,26 @@ * pins the table to a recorded observation. Re-fetch the endpoint and update * both transcriptions together when the recorded date gets old. */ -import { describe, expect, it } from 'vitest'; -import { NODESLIDE_AGENT_MODELS, type NodeSlideAgentModelId } from '../shared/nodeslide'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// Loaded here, at collection, on purpose. The MCP BYOK client keeps pi-ai's provider catalog off its +// startup path with `await import('@earendil-works/pi-ai/compat')` inside `call()`, so the first BYOK +// case below used to pay that cold import inside its own 5 s test budget (5 s timeouts under a loaded +// `npm run check`; round 12 raised this file's testTimeout to 30 s, which hid the cause). Importing the +// module here puts the load in collection, which has no per-test timeout, and the client's dynamic +// import then resolves from the module cache. The client itself is unchanged. Measured unloaded on +// 2026-11-06: the BYOK case took 568 ms with the cold imports in its body, 52 ms with both lines below. +import '@earendil-works/pi-ai/compat'; +// The chat-completions transport behind OpenRouter, which the lazy API wrapper imports on first send. +import '@earendil-works/pi-ai/api/openai-completions'; +import { call as callMcpByok } from '../mcp/src/lib/llmClient'; import { + NODESLIDE_AGENT_MODELS, + type NodeSlideAgentModelId, + nodeSlideAgentModel, +} from '../shared/nodeslide'; +import { + NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT, + NODESLIDE_HELD_PRICE_VERIFIED_AT, NODESLIDE_MODEL_PRICING, NODESLIDE_MODEL_PRICING_SOURCE_URL, NODESLIDE_MODEL_PRICING_VERIFIED_AT, @@ -31,25 +48,22 @@ import { nodeSlidePricingRefusalReason, scoreNodeSlideWorstCaseCost, } from '../shared/nodeslideRunBudget'; +import { decideNodeSlideAutoRoute } from './lib/nodeslideAutoRoutingPolicy'; +import { + NODESLIDE_KIMI_K3, + NODESLIDE_OPENROUTER_MODEL_OVERRIDES, + callNodeSlideFreeJson, + openrouterProviderWithOverrides, +} from './lib/nodeslideProvider'; /** - * Read out of the `data[]` entry for each id on 2026-07-28: `pricing.prompt`, + * Read out of the `data[]` entry for each id on 2026-10-14: `pricing.prompt`, * `pricing.completion` (USD per token, as strings), `context_length`, and * `top_provider.max_completion_tokens`. `null` is recorded as null, not guessed. */ -const OPENROUTER_CATALOG_2026_07_28 = { - 'moonshotai/kimi-k3': { - prompt: '0.000003', - completion: '0.000015', - contextLength: 1_048_576, - maxCompletionTokens: null, - }, - 'z-ai/glm-5.2': { - prompt: '0.0000007686', - completion: '0.0000024156', - contextLength: 1_048_576, - maxCompletionTokens: 131_072, - }, +const OPENROUTER_CATALOG_2026_10_14 = { + // moonshotai/kimi-k3, z-ai/glm-5.2 and openai/gpt-5.6-sol are NOT in this table: their rows keep + // main's 2026-07-28 values, which this catalog read did not publish. See HELD_AT_MAINS_CEILING. 'anthropic/claude-sonnet-5': { prompt: '0.000002', completion: '0.00001', @@ -62,27 +76,46 @@ const OPENROUTER_CATALOG_2026_07_28 = { contextLength: 1_000_000, maxCompletionTokens: 128_000, }, + 'anthropic/claude-sonnet-5.5': { + prompt: '0.000002', + completion: '0.00001', + contextLength: 1_000_000, + maxCompletionTokens: 128_000, + }, + 'anthropic/claude-opus-5.5': { + prompt: '0.000004', + completion: '0.00002', + contextLength: 1_000_000, + maxCompletionTokens: 128_000, + }, 'google/gemini-3.5-flash': { prompt: '0.0000015', completion: '0.000009', contextLength: 1_048_576, maxCompletionTokens: 65_536, }, + 'google/gemini-3.8-flash': { + prompt: '0.00000075', + completion: '0.00000375', + contextLength: 1_048_576, + maxCompletionTokens: 65_536, + }, 'google/gemini-3.1-pro-preview': { prompt: '0.000002', completion: '0.000012', contextLength: 1_048_576, maxCompletionTokens: 65_536, }, - 'openai/gpt-5.6-sol': { - prompt: '0.000005', - completion: '0.00003', + // Was 0.00000125 / 0.0000075 on 2026-07-28. + 'openai/gpt-5.6-terra': { + prompt: '0.000002', + completion: '0.000012', contextLength: 1_050_000, maxCompletionTokens: 128_000, }, - 'openai/gpt-5.6-terra': { - prompt: '0.00000125', - completion: '0.0000075', + 'openai/gpt-6.1-sol': { + prompt: '0.000002', + completion: '0.00001', contextLength: 1_050_000, maxCompletionTokens: 128_000, }, @@ -98,6 +131,84 @@ const OPENROUTER_CATALOG_2026_07_28 = { > >; +/** + * Three rows keep main's 2026-07-28 values on purpose (SPEC D3, Homen 2026-10-16). The 2026-10-14 + * listing did not publish them, so they are not in the table above and their rows do not claim it: + * what verified them is GET /api/v1/models/{id}/endpoints on 2026-10-15 at 23:08 UTC, counting the + * endpoints at or below the value as a `max_price` ceiling (OPENROUTER_ADMISSION_2026_10_15). `listed` + * is what the /models listing read, kept as the evidence the value was not adopted. + */ +const HELD_AT_MAINS_CEILING = { + // The production default. Listing 0.0000007 / 0.000015 and 943_718 on 2026-10-14: as the ceiling + // that admitted 3 of 25 endpoints on 2026-10-15 (2 with structured_outputs) against 21 of 25 (18). + 'moonshotai/kimi-k3': { + prompt: '0.000003', + completion: '0.000015', + contextLength: 1_048_576, + maxCompletionTokens: null, + listed: { prompt: '0.0000007', completion: '0.000015' }, + }, + // Listing 0.00000005 / 0.000007 and 943_718 on 2026-10-14: as the ceiling that admitted 0 of 33 + // endpoints at about 18:30 and 18:49 UTC and 2 of 33 (1 structured) at 22:35 and 23:00 UTC on + // 2026-10-15, against 6 of 33 (4) for this row. + 'z-ai/glm-5.2': { + prompt: '0.0000007686', + completion: '0.0000024156', + contextLength: 1_048_576, + maxCompletionTokens: 131_072, + listed: { prompt: '0.00000005', completion: '0.000007' }, + }, + // Listing 0.000002 / 0.00001 on 2026-10-14 (0.000004 / 0.00002 on 2026-10-15): as the ceiling + // 2 / 10 admitted 1 of 7 endpoints against 6 of 7 for this row. + 'openai/gpt-5.6-sol': { + prompt: '0.000005', + completion: '0.00003', + contextLength: 1_050_000, + maxCompletionTokens: 128_000, + listed: { prompt: '0.000002', completion: '0.00001' }, + }, +} as const; + +/** + * The executor route (SPEC "Homen decisions", NodeSlide executor, 2026-11-06: the paid + * deepseek/deepseek-v4.1-flash-1017, an exception to D2). Read out of GET /api/v1/models at + * 2026-11-06T10:39:31Z: `pricing.prompt` / `pricing.completion`, `context_length`, + * `top_provider.max_completion_tokens`, created 2026-10-17, no `expiration_date`, `structured_outputs`, + * `response_format` and `reasoning` in `supported_parameters`. The listing also carries weekday + * time-of-day `overrides` up to 0.0000003 / 0.0000012 (01:00-04:00 and 06:00-10:00 UTC, Monday to + * Friday): those are the DeepSeek endpoint's own peak price. The row is the base price, which is also + * the `max_price` ceiling, so OpenRouter never bills above what the ledger reserved; at peak the + * DeepSeek endpoint is simply not admitted (see OPENROUTER_ADMISSION_2026_11_06). + */ +const OPENROUTER_EXECUTOR_CATALOG_2026_11_06 = { + 'deepseek/deepseek-v4.1-flash-1017': { + prompt: '0.00000015', + completion: '0.0000006', + contextLength: 1_048_576, + maxCompletionTokens: 393_216, + }, +} as const; + +/** + * The ledger-priced routes on which the frozen auto-router (pi-ai catalog price, micro-USD per + * million tokens) differs from the ledger, as read from the installed pi-ai 1.1.0 catalog on + * 2026-10-16. A row that appears or disappears here is a pricing change someone must look at. + */ +const AUTO_ROUTER_DIFFERS_FROM_LEDGER: Record = { + 'moonshotai/kimi-k3': { input: 500_000, output: 15_000_000 }, // ledger 3 / 15 + 'openai/gpt-5.6-sol': { input: 2_000_000, output: 10_000_000 }, // ledger 5 / 30 + 'z-ai/glm-5.2': { input: 171_000, output: 7_200_000 }, // ledger 0.7686 / 2.4156 +}; + +/** + * Ledger-priced routes the frozen auto-router cannot price at all: its only OpenRouter source is the + * bundled pi-ai 1.1.0 catalog, which has no row for these ids, so it refuses them (no estimate, no + * selection) instead of guessing. The executor is reached only through the routed edit planner and the + * reserve-before-dispatch ledger, never through the auto-router; a row appearing here is a route a + * job-create request cannot select. + */ +const AUTO_ROUTER_CANNOT_PRICE: readonly string[] = ['deepseek/deepseek-v4.1-flash-1017']; + /** The routes the catalog prices at "0" per token. Never a price; always a deny. */ const OPENROUTER_ZERO_PRICED_ROUTES: readonly NodeSlideAgentModelId[] = [ 'openrouter/free', @@ -122,19 +233,20 @@ function microUsdPerMillionTokens(usdPerToken: string): number { describe('the recorded catalog observation', () => { it('names the endpoint and the date it was read', () => { expect(NODESLIDE_MODEL_PRICING_SOURCE_URL).toBe('https://openrouter.ai/api/v1/models'); - expect(NODESLIDE_MODEL_PRICING_VERIFIED_AT).toBe('2026-07-28T00:00:00Z'); + expect(NODESLIDE_MODEL_PRICING_VERIFIED_AT).toBe('2026-10-14T16:03:00Z'); }); it('converts the provider unit to the ledger unit without floating-point drift', () => { // The route that would have silently lost a micro-USD to `* 1e12`. expect(microUsdPerMillionTokens('0.0000007686')).toBe(768_600); + expect(microUsdPerMillionTokens('0.0000007')).toBe(700_000); expect(microUsdPerMillionTokens('0.000003')).toBe(3_000_000); expect(microUsdPerMillionTokens('0.00005')).toBe(50_000_000); }); }); describe('every priced row matches the catalog it claims to come from', () => { - for (const [modelId, catalog] of Object.entries(OPENROUTER_CATALOG_2026_07_28)) { + for (const [modelId, catalog] of Object.entries(OPENROUTER_CATALOG_2026_10_14)) { it(`prices ${modelId} exactly as the catalog published it`, () => { const pricing = nodeSlideModelPricing(modelId); expect(pricing.kind).toBe('priced'); @@ -161,6 +273,50 @@ describe('every priced row matches the catalog it claims to come from', () => { } }); +describe('the held rows carry the evidence that verified them, not the listing they differ from', () => { + for (const [modelId, row] of Object.entries(OPENROUTER_EXECUTOR_CATALOG_2026_11_06)) { + it(`prices ${modelId} as the 2026-11-06 listing published it, labelled with that read`, () => { + const pricing = nodeSlideModelPricing(modelId); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') return; + expect(pricing.inputMicroUsdPerMillionTokens).toBe(microUsdPerMillionTokens(row.prompt)); + expect(pricing.outputMicroUsdPerMillionTokens).toBe(microUsdPerMillionTokens(row.completion)); + expect(pricing.inputMicroUsdPerMillionTokens).toBe(150_000); + expect(pricing.outputMicroUsdPerMillionTokens).toBe(600_000); + expect(pricing.providerContextWindowTokens).toBe(row.contextLength); + expect(pricing.providerMaxOutputTokens).toBe(row.maxCompletionTokens); + expect(pricing.source).toBe('openrouter_model_catalog_api'); + expect(pricing.sourceUrl).toBe(NODESLIDE_MODEL_PRICING_SOURCE_URL); + expect(pricing.verifiedAt).toBe(NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT); + expect(NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT).toBe('2026-11-06T10:39:31Z'); + }); + } + + for (const [modelId, held] of Object.entries(HELD_AT_MAINS_CEILING)) { + it(`labels ${modelId} with its endpoint check of 2026-10-15, not the 2026-10-14 listing`, () => { + const pricing = nodeSlideModelPricing(modelId); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') return; + expect(pricing.inputMicroUsdPerMillionTokens).toBe(microUsdPerMillionTokens(held.prompt)); + expect(pricing.outputMicroUsdPerMillionTokens).toBe( + microUsdPerMillionTokens(held.completion), + ); + expect(pricing.providerContextWindowTokens).toBe(held.contextLength); + expect(pricing.providerMaxOutputTokens).toBe(held.maxCompletionTokens ?? held.contextLength); + expect(pricing.source).toBe('openrouter_model_catalog_api'); + // The label names what verified the value: the per-route endpoints read, at its own time. + expect(pricing.sourceUrl).toBe(`${NODESLIDE_MODEL_PRICING_SOURCE_URL}/${modelId}/endpoints`); + expect(pricing.verifiedAt).toBe(NODESLIDE_HELD_PRICE_VERIFIED_AT); + expect(NODESLIDE_HELD_PRICE_VERIFIED_AT).toBe('2026-10-15T23:08:00Z'); + expect(pricing.verifiedAt).not.toBe(NODESLIDE_MODEL_PRICING_VERIFIED_AT); + // The listing the old label claimed is genuinely cheaper, so that label was false. + expect(microUsdPerMillionTokens(held.listed.prompt)).toBeLessThan( + microUsdPerMillionTokens(held.prompt), + ); + }); + } +}); + describe('zero-priced and unpriceable routes deny rather than reserve', () => { for (const modelId of OPENROUTER_ZERO_PRICED_ROUTES) { it(`refuses ${modelId} with a stated reason instead of treating "0" as a price`, () => { @@ -260,3 +416,406 @@ describe('worst-case scoring rounds against the run, never in its favour', () => expect(scored.totalCostMicroUsd).toBe(60_000_000); }); }); + +/** + * The ledger price is also the OpenRouter `max_price` ceiling (`nodeslideBudgetedProvider.ts`), and a + * request whose ceiling is below every live endpoint is not run ("will prevent your request from + * running if the price is not available"). The /models listing price is the CHEAPEST endpoint's, so + * a ledger row copied from it leaves a route with one to three providers, or none: glm-5.2 at its + * listing (0.05 / 7) admitted 0 of 33 endpoints at about 18:30 UTC on 2026-10-15 and 2 of 33 at 22:35 + * UTC, and kimi-k3, the production default, at 0.7 / 15 admitted 3 of 25 where its 3 / 15 admits 21. + * + * For each metered OpenRouter route this records what GET /api/v1/models/{id}/endpoints returned on + * 2026-10-15 at 23:08 UTC for the committed ceiling: how many endpoints exist (`of`), how many are at + * or below the ceiling on both rates (`admitted`), and how many of those support `structured_outputs` + * (`structured`; `require_parameters` demands it on a json_schema request). The test cannot see the + * live catalog. It fails the day a ledger row moves without this observation being re-fetched and + * re-recorded, or is recorded as a route that one provider outage would make unroutable; the fix is to + * re-fetch the endpoints, not to edit these numbers. + */ +const OPENROUTER_ADMISSION_2026_10_15 = { + 'moonshotai/kimi-k3': { of: 25, admitted: 21, structured: 18 }, + 'z-ai/glm-5.2': { of: 33, admitted: 6, structured: 4 }, + 'anthropic/claude-sonnet-5': { of: 10, admitted: 5, structured: 4 }, + 'anthropic/claude-fable-5': { of: 6, admitted: 5, structured: 4 }, + 'anthropic/claude-sonnet-5.5': { of: 8, admitted: 5, structured: 3 }, + 'anthropic/claude-opus-5.5': { of: 11, admitted: 5, structured: 4 }, + 'google/gemini-3.5-flash': { of: 7, admitted: 4, structured: 4 }, + 'google/gemini-3.8-flash': { of: 7, admitted: 4, structured: 4 }, + 'google/gemini-3.1-pro-preview': { of: 6, admitted: 4, structured: 4 }, + 'openai/gpt-5.6-sol': { of: 7, admitted: 6, structured: 6 }, + 'openai/gpt-5.6-terra': { of: 7, admitted: 3, structured: 3 }, + 'openai/gpt-6.1-sol': { of: 8, admitted: 3, structured: 3 }, +} as const; + +/** + * The executor row, read the same way from GET /api/v1/models/deepseek/deepseek-v4.1-flash-1017/endpoints + * at 2026-11-06T10:39:31Z: 50 endpoints, 18 at or below 0.15 / 0.60 on both base rates (16 with + * structured_outputs). One of the 18 is DeepSeek's own endpoint, whose weekday peak override + * (0.30 / 1.20) is above the ceiling, so 17 (16 structured) are admitted at every hour. + */ +const OPENROUTER_ADMISSION_2026_11_06 = { + 'deepseek/deepseek-v4.1-flash-1017': { of: 50, admitted: 17, structured: 16 }, +} as const; + +const OPENROUTER_ADMISSION = { + ...OPENROUTER_ADMISSION_2026_10_15, + ...OPENROUTER_ADMISSION_2026_11_06, +} as const; + +/** The committed ceiling per route, restated in the listing's own unit (USD per million tokens). */ +const OPENROUTER_CEILING_AT_OBSERVATION = { + 'moonshotai/kimi-k3': { prompt: 3, completion: 15 }, + 'z-ai/glm-5.2': { prompt: 0.7686, completion: 2.4156 }, + 'anthropic/claude-sonnet-5': { prompt: 2, completion: 10 }, + 'anthropic/claude-fable-5': { prompt: 10, completion: 50 }, + 'anthropic/claude-sonnet-5.5': { prompt: 2, completion: 10 }, + 'anthropic/claude-opus-5.5': { prompt: 4, completion: 20 }, + 'google/gemini-3.5-flash': { prompt: 1.5, completion: 9 }, + 'google/gemini-3.8-flash': { prompt: 0.75, completion: 3.75 }, + 'google/gemini-3.1-pro-preview': { prompt: 2, completion: 12 }, + 'openai/gpt-5.6-sol': { prompt: 5, completion: 30 }, + 'openai/gpt-5.6-terra': { prompt: 2, completion: 12 }, + 'openai/gpt-6.1-sol': { prompt: 2, completion: 10 }, + 'deepseek/deepseek-v4.1-flash-1017': { prompt: 0.15, completion: 0.6 }, +} as const; + +describe('every metered OpenRouter ledger price is a ceiling that still routes', () => { + const meteredRoutes = NODESLIDE_AGENT_MODELS.filter( + (model) => model.provider === 'openrouter' && nodeSlideModelPricing(model.id).kind === 'priced', + ); + + it('has an observation for every metered route, and no stray rows', () => { + const metered = meteredRoutes.map((model) => model.id).sort(); + expect(Object.keys(OPENROUTER_ADMISSION).sort()).toEqual(metered); + expect(Object.keys(OPENROUTER_CEILING_AT_OBSERVATION).sort()).toEqual(metered); + }); + + for (const [modelId, observed] of Object.entries(OPENROUTER_ADMISSION)) { + it(`${modelId} was observed at its committed ceiling with a choice of providers`, () => { + const pricing = nodeSlideModelPricing(modelId); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') return; + const ceiling = + OPENROUTER_CEILING_AT_OBSERVATION[ + modelId as keyof typeof OPENROUTER_CEILING_AT_OBSERVATION + ]; + // The ceiling the observation was taken at is the ceiling that ships. + expect(pricing.inputMicroUsdPerMillionTokens).toBe(Math.round(ceiling.prompt * 1e6)); + expect(pricing.outputMicroUsdPerMillionTokens).toBe(Math.round(ceiling.completion * 1e6)); + // At least three endpoints, two of them structured-output capable: one provider outage or + // repricing must still leave a provider to route to. + expect(observed.admitted).toBeGreaterThanOrEqual(3); + expect(observed.structured).toBeGreaterThanOrEqual(2); + expect(observed.structured).toBeLessThanOrEqual(observed.admitted); + expect(observed.admitted).toBeLessThanOrEqual(observed.of); + }); + } +}); + +/** + * Part A rule 6: every pricing source in this repo, each with its date, one test, equal + * `{inPerM, outPerM}` per (id, OpenRouter transport). The sources: + * + * 1. the ledger table `NODESLIDE_MODEL_PRICING` (also the reservation quote and the OpenRouter + * `max_price` ceiling), pricingAsOf `NODESLIDE_MODEL_PRICING_VERIFIED_AT` (2026-10-14T16:03Z), and + * `NODESLIDE_HELD_PRICE_VERIFIED_AT` (2026-10-15T23:08Z) on the three held rows; + * 2. the hand-typed `Model<>` overrides in `nodeslideProvider.ts`, same pricingAsOf; + * 3. the provider the dispatcher actually builds (`openrouterProviderWithOverrides`): its rows + * price every response (`usage.cost.total` -> `costMicroUsd`). Its base rows are the bundled + * pi-ai 1.1.0 OpenRouter catalog, which is NOT dated by us and disagreed with the ledger on + * two rows when read on 2026-10-14: moonshotai/kimi-k3 0.5 / 15 (ledger 3 / 15) and + * z-ai/glm-5.2 0.171 / 7.2 (ledger 0.7686 / 2.4156). The provider therefore prices every ledger-priced + * row at the ledger's rate, and this test is what notices the day that stops being true; + * 4. the auto-router estimate (`nodeslideAutoRoutingPolicy.ts`), which reads the same pi-ai + * catalog and is a FROZEN site (SPEC A.2.8): it is not edited here, so it keeps pi-ai's price + * and differs from the ledger on three rows. The divergence is pinned below + * (`AUTO_ROUTER_DIFFERS_FROM_LEDGER`), not asserted equal; the receipt it caps is not only + * advisory (`cost_cap_exceeded` is in ENFORCEABLE_REFUSALS and nodeslideJobs.ts rewrites a + * refused create request to providerMode 'deterministic'), and the ledger still reserves the + * worst case before any dispatch; + * 5. the MCP BYOK client (`mcp/src/lib/llmClient.ts`), which called `getModel` on the raw pi-ai + * catalog and reported `usage.cost.total` as `costUsd` (kimi-k3 $0.015500 against the ledger's + * $0.018000 for 1k in / 1k out, glm-5.2 $0.007371 against $0.0031842). It prices OpenRouter + * routes through `nodeSlideLedgerPricedCost`, the function the provider in 3 uses. It carries + * no date of its own: it takes the ledger's, `NODESLIDE_MODEL_PRICING_VERIFIED_AT`. + * + * Cache rates are part of the agreement, not only input and output: the reservation quote prices + * every input token at the ledger's input rate, so a cached-read token must not cost more than that + * (on 2026-10-14 pi-ai's glm-5.2 row said 0.162 against a ledger 0.05, which settled 100k cached + * tokens at 3.24x their quote and left a valid response unreconciled; the ledger input is 0.7686 now, + * so the cap binds on no row today and these tests guard the invariant, not a live case), and a + * cache-write premium must stay inside the quote's 2x input-estimate headroom (Claude and GPT rows + * bill writes at 1.25x). + * + * Above-threshold tiers (pi-ai lists a higher rate above 200K-272K prompt tokens for gemini-3.1-pro + * and the gpt-5.6 / gpt-6.1 rows) are pi-ai-only data the flat ledger does not model; a NodeSlide + * prompt is bounded far below the threshold by the read-context limit. + */ +describe('every pricing source in this repo agrees (Part A rule 6)', () => { + const ledgerPricedOpenRouterRoutes = NODESLIDE_AGENT_MODELS.filter( + (model) => model.provider === 'openrouter' && nodeSlideModelPricing(model.id).kind === 'priced', + ); + const perMillion = (usdPerMillion: number) => Math.round(usdPerMillion * 1_000_000); + const textOnly = { web: false, longContext: false, image: false, reasoning: false }; + + function autoRoute(modelId: NodeSlideAgentModelId, maxUsd: number) { + return decideNodeSlideAutoRoute({ + task: 'compose-deck', + capabilities: textOnly, + privacy: 'external_if_consented', + requestedReasoningEffort: null, + deterministicAvailable: true, + consent: { providers: ['openrouter'], models: [modelId] }, + availability: [{ provider: 'openrouter', catalogModelId: modelId, available: true }], + expectedInputTokens: 100_000, + expectedOutputTokens: 1_000, + maxUsd, + fallbackPolicy: { mode: 'none' }, + }); + } + + it('covers every metered OpenRouter route in the catalog', () => { + // A route added to the catalog without a ledger price fails the exhaustiveness test above; this + // one fails if the filter above ever silently matches nothing. + expect(ledgerPricedOpenRouterRoutes.length).toBeGreaterThanOrEqual(10); + expect(ledgerPricedOpenRouterRoutes.map((model) => model.id)).toEqual( + expect.arrayContaining(['moonshotai/kimi-k3', 'z-ai/glm-5.2', 'anthropic/claude-sonnet-5.5']), + ); + }); + + it('the hand-typed Kimi K3 Model<> override costs what the price table charges', () => { + const pricing = nodeSlideModelPricing('moonshotai/kimi-k3'); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') return; + expect(NODESLIDE_KIMI_K3.provider).toBe('openrouter'); + expect(perMillion(NODESLIDE_KIMI_K3.cost.input)).toBe(pricing.inputMicroUsdPerMillionTokens); + expect(perMillion(NODESLIDE_KIMI_K3.cost.output)).toBe(pricing.outputMicroUsdPerMillionTokens); + expect(NODESLIDE_KIMI_K3.contextWindow).toBe(pricing.providerContextWindowTokens); + }); + + it('every OpenRouter model override is a priced row that agrees with the table', () => { + for (const override of NODESLIDE_OPENROUTER_MODEL_OVERRIDES) { + const pricing = nodeSlideModelPricing(override.id); + expect(pricing.kind).toBe('priced'); + if (pricing.kind !== 'priced') continue; + expect(perMillion(override.cost.input)).toBe(pricing.inputMicroUsdPerMillionTokens); + expect(perMillion(override.cost.output)).toBe(pricing.outputMicroUsdPerMillionTokens); + } + }); + + it('the provider the dispatcher builds prices every metered route at the ledger rate', () => { + const models = new Map( + openrouterProviderWithOverrides() + .getModels() + .map((model) => [model.id, model] as const), + ); + for (const route of ledgerPricedOpenRouterRoutes) { + const pricing = nodeSlideModelPricing(route.id); + const model = models.get(route.upstreamId); + expect(model, `${route.upstreamId} is in the provider`).toBeDefined(); + if (pricing.kind !== 'priced' || !model) continue; + expect(perMillion(model.cost.input), `${route.id} input`).toBe( + pricing.inputMicroUsdPerMillionTokens, + ); + expect(perMillion(model.cost.output), `${route.id} output`).toBe( + pricing.outputMicroUsdPerMillionTokens, + ); + } + }); + + it('no cache rate prices a token above what the reservation quote assumed', () => { + // The quote's input estimate is bytes x MAX_PROVIDER_ATTEMPTS (2) + overhead, i.e. at least twice + // the tokens ever sent, so a write premium up to 2x the input rate still settles inside it. + const WRITE_PREMIUM_HEADROOM = 2; + const models = new Map( + openrouterProviderWithOverrides() + .getModels() + .map((model) => [model.id, model] as const), + ); + for (const route of ledgerPricedOpenRouterRoutes) { + const model = models.get(route.upstreamId); + if (!model) throw new Error(`${route.upstreamId} is missing from the provider`); + expect(model.cost.cacheRead, `${route.id} cacheRead <= ledger input`).toBeLessThanOrEqual( + model.cost.input, + ); + expect( + model.cost.cacheWrite, + `${route.id} cacheWrite within the quote's headroom`, + ).toBeLessThanOrEqual(model.cost.input * WRITE_PREMIUM_HEADROOM); + } + }); + + describe('a response is costed at the ledger rate through both response paths', () => { + const originalKey = process.env['OPENROUTER_API_KEY']; + let usage: Record = {}; + const sse = () => + [ + 'data: {"id":"gen-fake","model":"fake/echo","choices":[{"index":0,"delta":{"role":"assistant","content":"{\\"ok\\":true}"},"finish_reason":null}]}\n\n', + `data: ${JSON.stringify({ + id: 'gen-fake', + model: 'fake/echo', + choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], + usage, + })}\n\n`, + 'data: [DONE]\n\n', + ].join(''); + beforeEach(() => { + process.env['OPENROUTER_API_KEY'] = 'sk-or-test-fake-not-a-credential'; + vi.stubGlobal( + 'fetch', + async () => + new Response(sse(), { status: 200, headers: { 'content-type': 'text/event-stream' } }), + ); + }); + afterEach(() => { + vi.unstubAllGlobals(); + if (originalKey === undefined) Reflect.deleteProperty(process.env, 'OPENROUTER_API_KEY'); + else process.env['OPENROUTER_API_KEY'] = originalKey; + }); + + const ledgerMicroUsd = (id: string, inputTokens: number, outputTokens: number) => { + const pricing = nodeSlideModelPricing(id); + if (pricing.kind !== 'priced') throw new Error(`${id} is not ledger-priced`); + return ( + (inputTokens * pricing.inputMicroUsdPerMillionTokens + + outputTokens * pricing.outputMicroUsdPerMillionTokens) / + 1_000_000 + ); + }; + // MCP routes by vendor prefix; these are the routes it sends to OpenRouter by id. + const mcpRoutes = ['moonshotai/kimi-k3', 'z-ai/glm-5.2'] as const; + const mcpCall = (modelId: string) => + callMcpByok({ + provider: 'openrouter', + modelId, + systemPrompt: 'Return JSON.', + userText: '{}', + }); + + it('the MCP BYOK client costs 1k in / 1k out at the ledger rate (kimi-k3 $0.018000, glm-5.2 $0.0031842)', async () => { + usage = { prompt_tokens: 1000, completion_tokens: 1000, total_tokens: 2000 }; + for (const id of mcpRoutes) { + const result = await mcpCall(id); + expect(result.costUsd * 1_000_000, id).toBeCloseTo(ledgerMicroUsd(id, 1000, 1000), 6); + } + }); + + // Codex 2026-11-06 (P2): the client costs at the ledger rate, so without a matching price ceiling + // OpenRouter can bill a pricier endpoint than the cost it persists (GLM billed $0.006806, persisted + // 3,184 micro-USD). The ceiling makes the persisted figure an upper bound on what is billed. + it('the MCP BYOK client caps OpenRouter at the ledger rate it costs at (provider.max_price)', async () => { + usage = { prompt_tokens: 10, completion_tokens: 10, total_tokens: 20 }; + for (const id of mcpRoutes) { + let body: Record = {}; + vi.stubGlobal('fetch', async (_url: unknown, init?: RequestInit) => { + body = JSON.parse(String(init?.body)); + return new Response(sse(), { + status: 200, + headers: { 'content-type': 'text/event-stream' }, + }); + }); + await mcpCall(id); + const pricing = nodeSlideModelPricing(id); + if (pricing.kind !== 'priced') throw new Error(`${id} is not ledger-priced`); + expect(body['provider'], id).toMatchObject({ + max_price: { + prompt: pricing.inputMicroUsdPerMillionTokens / 1_000_000, + completion: pricing.outputMicroUsdPerMillionTokens / 1_000_000, + }, + }); + } + }); + + it('no response path costs a fully cached prompt above the input rate the quote assumed', async () => { + // 100k prompt tokens, all served from cache, 10 output tokens (Codex's replay: glm-5.2 settled + // 16,270 micro-USD against a 15,352 quote before the cache cap). + usage = { + prompt_tokens: 100_000, + completion_tokens: 10, + total_tokens: 100_010, + prompt_tokens_details: { cached_tokens: 100_000 }, + }; + for (const route of ledgerPricedOpenRouterRoutes) { + const ceiling = Math.ceil(ledgerMicroUsd(route.id, 100_000, 10)); + const result = await callNodeSlideFreeJson({ + systemPrompt: 'Return JSON.', + userText: '{}', + maxTokens: 500, + model: route.id, + reasoningEffort: (route.supportedEfforts as readonly string[]).includes('low') + ? 'low' + : 'high', + }); + expect(result.ok, route.id).toBe(true); + if (!result.ok) continue; + expect(result.telemetry.costMicroUsd, `convex ${route.id}`).toBeLessThanOrEqual(ceiling); + } + for (const id of mcpRoutes) { + const result = await mcpCall(id); + expect(result.costUsd * 1_000_000, `mcp ${id}`).toBeLessThanOrEqual( + Math.ceil(ledgerMicroUsd(id, 100_000, 10)), + ); + } + }); + }); + + // SPEC A.2.8 freezes `nodeslideAutoRoutingPolicy.ts` ("derived from the installed pi-ai catalog"), so + // the auto-router is a pricing source this PR enumerates but does not edit: it estimates at the + // bundled pi-ai catalog's price, not the ledger's. Round 1 had moved it to the ledger; that edit was + // reverted (a frozen site is not edited) and the divergence is pinned here instead, so it can neither + // widen nor close unnoticed. Without a pinned row a router estimate below the ledger's worst case + // would admit a job-create route the ledger prices higher (kimi-k3: 100k in + 1k out is $0.065 here + // against the ledger's $0.315). The router's receipt is not only advisory: `cost_cap_exceeded` is in + // ENFORCEABLE_REFUSALS (nodeslideRoutingReceipt.ts) and nodeslideJobs.ts applies + // resolveNodeSlideEnforcedCreateRequest, which turns the create request into providerMode + // 'deterministic'. So the pinned divergence can change which create requests run deterministically + // (glm-5.2 output is overestimated at 7.2 against the ledger's 2.4156, which can refuse a request the + // ledger would admit). No spend is under-reserved: the ledger still reserves the worst case before + // any dispatch. + // + // This is NOT the A.0.6 equality: it pins a known disagreement. Closing it needs either an edit to the + // frozen auto-router or a change to the ledger prices D3 held, and neither is this PR's to make. It is + // listed under "Open for Homen" in the PR body; do not delete this test to make the gap disappear. + it('pins where the frozen auto-router estimate differs from the ledger rate', () => { + const differing: Record = {}; + const unpriced: string[] = []; + for (const route of ledgerPricedOpenRouterRoutes) { + const pricing = nodeSlideModelPricing(route.id); + if (pricing.kind !== 'priced') continue; + const decision = autoRoute(route.id, 100); + if (decision.kind !== 'selected') { + // Refused for want of a price, not for any other reason. + expect(decision.kind === 'refused' && decision.refusal.code, route.id).toBe( + 'pricing_unavailable', + ); + unpriced.push(route.id); + continue; + } + expect(decision.kind, `${route.id} is routable`).toBe('selected'); + const estimate = decision.costEstimate; + expect(estimate.status).toBe('estimated'); + if (estimate.status !== 'estimated') continue; + expect(estimate.pricing.source, `${route.id} source`).toBe('pi-ai-openrouter-catalog'); + const input = perMillion(estimate.pricing.inputUsdPerMillionTokens); + const output = perMillion(estimate.pricing.outputUsdPerMillionTokens); + if ( + input !== pricing.inputMicroUsdPerMillionTokens || + output !== pricing.outputMicroUsdPerMillionTokens + ) { + differing[route.id] = { input, output }; + } + } + expect(differing).toEqual(AUTO_ROUTER_DIFFERS_FROM_LEDGER); + expect(unpriced).toEqual(AUTO_ROUTER_CANNOT_PRICE); + }); + + it('keeps the Nebius GLM-5.2 hand-typed cost out of every reservation path', () => { + // NODESLIDE_NEBIUS_GLM carries a hand-typed 1.4 / 4.4 (not in frontier.json, not on OpenRouter). + // The route is productionEnabled:false and its ledger row is 'unknown' (denied), so the + // figure cannot reach a reservation. It is verified against the Nebius price list when the + // route is enabled (SPEC Part A section A.2.8, R row convex/lib/nodeslideProvider.ts:27). + expect(nodeSlideAgentModel('nebius/zai-org/GLM-5.2').productionEnabled).toBe(false); + expect(nodeSlideModelPricing('nebius/zai-org/GLM-5.2').kind).toBe('unknown'); + }); +}); diff --git a/convex/nodeslideModelProbe.ts b/convex/nodeslideModelProbe.ts index 07a835cf..e307882f 100644 --- a/convex/nodeslideModelProbe.ts +++ b/convex/nodeslideModelProbe.ts @@ -1,6 +1,13 @@ 'use node'; +import { api, internal } from './_generated/api'; import { internalAction } from './_generated/server'; +import { bindNodeSlideBudgetLedgerClient } from './lib/nodeslideBudgetedProvider'; +import { + type NodeSlideExecutorSplitProbeReceipt, + executorSplitProbeBudgetUsd, + runNodeSlideExecutorSplitProbe, +} from './lib/nodeslideExecutorSplitProbe'; import { runNodeSlideFreeRouterProbe, runNodeSlideFreeRouterStructuredProbe, @@ -24,3 +31,28 @@ export const runFreeRouterStructured = internalAction({ args: {}, handler: async () => runNodeSlideFreeRouterStructuredProbe(), }); + +// Convex's generated API makes this action's own file part of the reference types it calls through, +// which TypeScript reads as a self-reference. Same confined escape hatch as convex/nodeslideAgent.ts. +// biome-ignore lint/suspicious/noExplicitAny: generated Convex self-reference described above +const generatedApi: any = api; +// biome-ignore lint/suspicious/noExplicitAny: generated Convex self-reference described above +const generatedInternal: any = internal; + +/** + * Candidate-bound executor receipt (SPEC Part A, section A.2.8): one premium-planner edit turn split + * to the routed copy executor through the reserve-before-dispatch provider. Spends real provider + * money, capped by NODESLIDE_PROBE_BUDGET_USD (default 0.55 USD, planner and executor together). + * Invoke with `npx convex run nodeslideModelProbe:runExecutorSplit`. + */ +export const runExecutorSplit = internalAction({ + args: {}, + handler: async (ctx): Promise => { + const buildIdentity = await ctx.runQuery(generatedApi.nodeslideBuildIdentity.get, {}); + return runNodeSlideExecutorSplitProbe({ + ledger: bindNodeSlideBudgetLedgerClient(ctx, generatedInternal.nodeslideBudgets), + buildIdentity, + budgetUsd: executorSplitProbeBudgetUsd(process.env), + }); + }, +}); diff --git a/docs/codebase/INTEGRATIONS.md b/docs/codebase/INTEGRATIONS.md index f2f10d69..9cf1fb38 100644 --- a/docs/codebase/INTEGRATIONS.md +++ b/docs/codebase/INTEGRATIONS.md @@ -79,7 +79,7 @@ receipt. Note these live in the **Convex** environment, not in `.env.local`; ## MCP — NodeSlide for coding agents (optional) -- **Where:** `mcp/`, tools registered in `mcp/src/lib/nodeslideTools.ts:414` (`registerNodeSlideTools`). +- **Where:** `mcp/`, tools registered in `mcp/src/lib/nodeslideTools.ts:417` (`registerNodeSlideTools`). - **How it connects:** stdio MCP server that calls the same Convex functions the browser calls. Provider keys stay in the MCP process — `nodeslide.byok_status` reports presence and never returns a value. diff --git a/mcp/src/lib/llmClient.test.ts b/mcp/src/lib/llmClient.test.ts new file mode 100644 index 00000000..2d51f753 --- /dev/null +++ b/mcp/src/lib/llmClient.test.ts @@ -0,0 +1,63 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +/** + * Scenario: a designer runs the local MCP planner on Claude Opus 5.5 through OpenRouter and names no + * effort. pi-ai 1.1.0 sends 'high' for every managed-effort Claude row when the caller says nothing, + * but the NodeSlide row (and the vendor) default Opus 5.5 to medium (SPEC A.2.8). The client must + * name the row default itself. pi-ai is faked so no request leaves the process. + */ +const complete = vi.hoisted(() => vi.fn()); +vi.mock('@earendil-works/pi-ai/compat', () => ({ + getModel: () => ({ input: ['text'], cost: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0 } }), + complete, +})); + +import { call } from './llmClient.js'; + +const base = { systemPrompt: 's', userText: 'u' } as const; + +describe('local MCP client names the NodeSlide row default effort', () => { + beforeEach(() => { + complete.mockReset(); + complete.mockResolvedValue({ + content: [], + usage: { cost: { total: 0 }, input: 0, output: 0 }, + model: 'm', + stopReason: 'stop', + }); + }); + + it('sends medium for Opus 5.5 and high for the Sonnet 5.5 row', async () => { + for (const [modelId, effort] of [ + ['anthropic/claude-opus-5.5', 'medium'], + ['anthropic/claude-sonnet-5.5', 'high'], + ] as const) { + await call({ provider: 'openrouter', modelId, ...base }); + expect(complete.mock.calls.at(-1)?.[2]).toMatchObject({ effort }); + } + }); + + // Was: 'moonshotai/kimi-k3' -> { effort: 'high' } (round 3), which applied the row default to every + // catalog row. SPEC A.0.4 keeps the rows this refresh does not add (kimi-k3, GPT-5.6, Gemini 3.1 Pro) + // on the request main sent, which carries no effort; the byte-level comparison is in + // llmClient.wire.test.ts. + it('adds no effort for a catalog row this refresh does not add', async () => { + for (const modelId of [ + 'moonshotai/kimi-k3', + 'openai/gpt-5.6-sol', + 'openai/gpt-5.6-terra', + 'google/gemini-3.1-pro-preview', + ]) { + await call({ provider: 'openrouter', modelId, ...base }); + expect(complete.mock.calls.at(-1)?.[2]).not.toHaveProperty('effort'); + } + }); + + it('adds no effort for a model id that is not a NodeSlide row', async () => { + // Was 'claude-opus-5-5' (round 3). That is the direct wire id of the Opus 5.5 row since the + // wire-id table (round 4): it is now the same row and gets its default, asserted in + // llmClient.wire.test.ts. The id here is a model the catalog does not list. + await call({ provider: 'anthropic', modelId: 'claude-haiku-5-5', ...base }); + expect(complete.mock.calls.at(-1)?.[2]).not.toHaveProperty('effort'); + }); +}); diff --git a/mcp/src/lib/llmClient.ts b/mcp/src/lib/llmClient.ts index bc11a5a0..9159017a 100644 --- a/mcp/src/lib/llmClient.ts +++ b/mcp/src/lib/llmClient.ts @@ -37,6 +37,16 @@ import type { ImageContent, TextContent, } from '@earendil-works/pi-ai/compat'; +import { + type NodeSlideReasoningEffort, + isNodeSlideAgentModelId, + isNodeSlideVerifiedFreeModelId, + nodeSlideDefaultReasoningEffort, +} from '../../../shared/nodeslide.js'; +import { + nodeSlideLedgerPricedCost, + nodeSlideModelPricing, +} from '../../../shared/nodeslideRunBudget.js'; /** * pi-ai's Provider type is `KnownProvider | string` (open by design — users @@ -91,6 +101,9 @@ export interface CallResult { * `model` string and we route correctly. */ export function inferProvider(modelId: string): SupportedProvider { + // `:free` / `-free` ids and the free router exist only on OpenRouter, so the key the caller needs + // (byok.ts) and the route `call` takes are decided here, once, not by the id's vendor prefix. + if (isFreeLookingModelId(modelId)) return 'openrouter'; if (modelId.startsWith('anthropic/') || modelId.startsWith('claude-')) return 'anthropic'; if (modelId.startsWith('openai/') || modelId.startsWith('gpt-')) return 'openai'; if (modelId.startsWith('google/') || modelId.startsWith('gemini-')) return 'google'; @@ -103,16 +116,94 @@ export function inferProvider(modelId: string): SupportedProvider { return 'openai'; } +/** + * Direct-Anthropic wire ids for the NodeSlide catalog's Claude rows (SPEC section 1.2, `anthropic` + * column). The catalog id is the OpenRouter slug (`anthropic/claude-sonnet-5.5`, dotted), which is not + * the direct id (`claude-sonnet-5-5`, dashed): stripping the prefix produced `claude-sonnet-5.5`, + * which pi-ai's registry does not have, so the call threw before any request. An explicit table, not + * string replacement (SPEC A.0.5). Which provider serves the id is still `inferProvider`'s choice. + */ +const DIRECT_ANTHROPIC_WIRE_ID: Readonly> = { + 'anthropic/claude-sonnet-5': 'claude-sonnet-5', + 'anthropic/claude-fable-5': 'claude-fable-5', + 'anthropic/claude-sonnet-5.5': 'claude-sonnet-5-5', + 'anthropic/claude-opus-5.5': 'claude-opus-5-5', +}; + +/** + * The catalog rows this refresh adds, the only ones `call` sets an effort for (see the use in `call`). + * Opus / Sonnet 5.5 need the top-level `output_config.effort`; GPT-6.1 Sol needs an explicit effort + * (SPEC 1.3 rejects 'none'); Gemini 3.8 Flash takes `thinkingLevel`. + */ +const EFFORT_MANAGED_ROWS = [ + 'anthropic/claude-opus-5.5', + 'anthropic/claude-sonnet-5.5', + 'openai/gpt-6.1-sol', + 'google/gemini-3.8-flash', +] as const; + /** * Strip provider prefix if present so getModel(provider, id) gets the canonical * id. e.g. "anthropic/claude-sonnet-4-6" + provider="anthropic" -> "claude-sonnet-4-6". */ function canonicalizeModelId(provider: SupportedProvider, modelId: string): string { + if (provider === 'anthropic' && Object.hasOwn(DIRECT_ANTHROPIC_WIRE_ID, modelId)) { + return DIRECT_ANTHROPIC_WIRE_ID[modelId] as string; + } + // An OpenRouter id is the whole slug (`openrouter/free` is a catalog route, not a provider prefix). + if (provider === 'openrouter') return modelId; const prefix = `${provider}/`; if (modelId.startsWith(prefix)) return modelId.slice(prefix.length); return modelId; } +/** The verified free constant a free-looking unknown id resolves to (SPEC A.0.10). */ +const FREE_ROUTER_MODEL_ID = 'openrouter/free'; + +function isFreeLookingModelId(modelId: string): boolean { + return modelId.endsWith(':free') || modelId.endsWith('-free') || modelId === FREE_ROUTER_MODEL_ID; +} + +/** + * The row default effort in the option the model's own API reads. pi-ai's `complete` forwards options + * untouched, and each API reads a different one: Anthropic `effort` (the mid-conversation effort + * message), the OpenAI Responses and Chat-completions (OpenRouter) APIs `reasoningEffort`, Gemini + * `thinking.level`. A name the API does not read is dropped, which ran GPT and Gemini rows at the vendor default (medium) instead of the + * row's (high). `effort` is always passed, as before; the other two are added for their API. + */ +function rowEffortOption(api: string, effort: NodeSlideReasoningEffort | undefined) { + if (effort === undefined) return {}; + switch (api) { + case 'openai-responses': + case 'openai-completions': // OpenRouter's route for the same rows reads reasoningEffort too + return { effort, reasoningEffort: effort }; + case 'google-generative-ai': + // Gemini 3.x Flash takes low / medium / high only (the catalog rows never offer more). + return effort === 'low' || effort === 'medium' || effort === 'high' + ? { + effort, + thinking: { enabled: true, level: effort.toUpperCase() as 'LOW' | 'MEDIUM' | 'HIGH' }, + } + : { effort }; + default: + return { effort }; + } +} + +/** + * Anthropic managed-effort rows (Opus 5.5, Sonnet 5.5) are governed by the top-level + * `output_config.effort`. pi-ai 1.1.0 writes a fixed 'high' there and only appends the requested + * effort as a trailing effort-only message, which the API applies "from the next user turn" + * (migration guide, mid-conversation effort). This call is one user turn with no turn after it, so the + * trailing message cannot govern the reply. Writing the row effort into the top-level field makes the + * reply run at the row default. A body with no `output_config.effort` (Sonnet 5) is left untouched. + */ +function withTopLevelEffort(payload: unknown, effort: NodeSlideReasoningEffort): unknown { + const body = payload as { output_config?: { effort?: string } }; + if (body.output_config?.effort === undefined) return payload; + return { ...body, output_config: { ...body.output_config, effort } }; +} + /** * Single completion call. Supports text-only and vision. * @@ -127,19 +218,58 @@ export async function call(opts: CallOptions): Promise { // Keep the sizeable provider catalog off the MCP startup/help path. Offline // file tools never pay this import cost; BYOK loads it only at first use. const pi = await import('@earendil-works/pi-ai/compat'); - const canonicalId = canonicalizeModelId(opts.provider, opts.modelId); + let provider = opts.provider; + let canonicalId = canonicalizeModelId(provider, opts.modelId); // pi-ai's getModel is typed against its compile-time MODEL registry, but // we accept arbitrary strings at this boundary (env-driven model overrides, // per-call user input). Runtime validation inside getModel throws for // unknown ids — we surface that as a clear error message to the agent. // biome-ignore lint/suspicious/noExplicitAny: see comment above - const registryModel = (pi.getModel as any)(opts.provider, canonicalId); - const model = opts.baseUrl ? { ...registryModel, baseUrl: opts.baseUrl } : registryModel; + const lookup = pi.getModel as any; + let registryModel = lookup(provider, canonicalId); + if (!registryModel) { + // SPEC D1: a known id (a NodeSlide catalog row, or a SPEC 1.2 verified free id) is never rerouted + // to another model, so one pi-ai cannot serve throws here, before any request. SPEC A.0.10: an unknown id never becomes + // a paid default; a free-looking one resolves to the verified free router and every other unknown + // throws. + if (isNodeSlideAgentModelId(opts.modelId) || isNodeSlideVerifiedFreeModelId(opts.modelId)) { + throw new Error( + `Model "${opts.modelId}" is a known NodeSlide id but pi-ai has no ${provider} route for it; it is not rerouted.`, + ); + } + if (!isFreeLookingModelId(opts.modelId)) { + throw new Error(`Unknown model "${opts.modelId}": pi-ai has no ${provider} route for it.`); + } + provider = 'openrouter'; + canonicalId = FREE_ROUTER_MODEL_ID; + registryModel = lookup(provider, canonicalId); + if (!registryModel) + throw new Error(`The free router "${FREE_ROUTER_MODEL_ID}" is not in pi-ai.`); + } + // The bundled pi-ai catalog is an older price snapshot than the NodeSlide run-budget ledger + // (kimi-k3 0.5 against 3, glm-5.2 0.171 against 0.7686), so a response on an OpenRouter route the + // ledger prices is costed at the ledger's rate, the same one the Convex dispatcher uses. + const pricedModel = + provider === 'openrouter' && registryModel.cost + ? { ...registryModel, cost: nodeSlideLedgerPricedCost(canonicalId, registryModel.cost) } + : registryModel; + const model = opts.baseUrl ? { ...pricedModel, baseUrl: opts.baseUrl } : pricedModel; + // Costing at the ledger rate is only honest if OpenRouter cannot bill above it, so the same rate is + // sent as the routing ceiling (as the Convex dispatcher does). Without it a pricier endpoint is + // billed while the cheaper ledger figure is persisted (Codex 2026-11-06: $0.006806 billed, 3,184 µUSD kept). + const ledger = pricedModel !== registryModel ? nodeSlideModelPricing(canonicalId) : undefined; + const maxPrice = + ledger?.kind === 'priced' + ? { + prompt: ledger.inputMicroUsdPerMillionTokens / 1_000_000, + completion: ledger.outputMicroUsdPerMillionTokens / 1_000_000, + } + : undefined; const userContent: (TextContent | ImageContent)[] = [{ type: 'text', text: opts.userText }]; if (opts.userImage !== undefined) { if (!model.input.includes('image')) { - throw new Error(`pi-ai model ${opts.provider}/${canonicalId} does not support image input`); + throw new Error(`pi-ai model ${provider}/${canonicalId} does not support image input`); } userContent.push({ type: 'image', @@ -159,7 +289,31 @@ export async function call(opts: CallOptions): Promise { ], }; + // The four rows this refresh adds state their own default effort (Opus 5.5 = medium; GPT-6.1 Sol + // rejects 'none'). Left unset, pi-ai sends 'high' for every managed-effort Claude row and 'none' + // for GPT-6.1 Sol. Only those rows get an effort: every other row keeps the request it sent before + // (SPEC A.0.4). Every spelling of a row (the slug, the dashed wire id, bare or with the provider + // prefix) reaches the same wire id, so the row is found from that wire id, not the spelling. + const row = EFFORT_MANAGED_ROWS.find( + (id) => id === opts.modelId || canonicalizeModelId(provider, id) === canonicalId, + ); + const rowEffort = row !== undefined ? nodeSlideDefaultReasoningEffort(row) : undefined; const result = await pi.complete(model, context, { + ...rowEffortOption(model.api, rowEffort), + ...((model.api === 'anthropic-messages' && rowEffort !== undefined) || maxPrice + ? { + onPayload: (payload: unknown) => { + const body = ( + model.api === 'anthropic-messages' && rowEffort !== undefined + ? withTopLevelEffort(payload, rowEffort) + : payload + ) as { provider?: Record }; + return maxPrice + ? { ...body, provider: { ...body.provider, max_price: maxPrice } } + : body; + }, + } + : {}), ...(opts.signal !== undefined ? { signal: opts.signal } : {}), ...(opts.maxTokens !== undefined ? { maxOutputTokens: opts.maxTokens } : {}), }); @@ -172,7 +326,7 @@ export async function call(opts: CallOptions): Promise { costUsd: Number.isFinite(result.usage.cost.total) ? result.usage.cost.total : 0, inputTokens: result.usage.input, outputTokens: result.usage.output, - provider: opts.provider, + provider, modelUsed: result.model, stopReason: result.stopReason, }; diff --git a/mcp/src/lib/llmClient.wire.test.ts b/mcp/src/lib/llmClient.wire.test.ts new file mode 100644 index 00000000..b5c7a936 --- /dev/null +++ b/mcp/src/lib/llmClient.wire.test.ts @@ -0,0 +1,585 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { localByokStatus, requireLocalKeys } from './byok.js'; +import { call, callByModel } from './llmClient.js'; + +/** + * Scenario: a designer runs the local MCP bring-your-own-key edit planner (`planLocalByokEdit` -> + * `callByModel`) with an Anthropic key and picks a Claude row from the NodeSlide catalog. The catalog + * id is the OpenRouter slug (`anthropic/claude-sonnet-5.5`); the direct Anthropic API wants + * `claude-sonnet-5-5` (SPEC section 1.2). Before, the slug had its prefix stripped to + * `claude-sonnet-5.5`, which pi-ai's registry lacks: the call threw and sent no request. This drives + * the real pi-ai client with a fake `fetch`, so the assertion is on the request that would leave. + */ +type Body = { + model?: string; + thinking?: { type?: string }; + messages?: { role?: string }[]; +} & Record; +type Sent = { url: string; headers: Record; body: Body }; + +/** SPEC A.0.6 / 1.3: keys a Claude 5.5 request must not carry anywhere in its body. */ +const FORBIDDEN_KEYS = ['temperature', 'top_p', 'top_k', 'tool_choice', 'budget_tokens']; + +function wireShapeProblems(body: Body): string[] { + const problems: string[] = []; + const walk = (node: unknown, path: string) => { + if (Array.isArray(node)) node.forEach((v, i) => walk(v, `${path}[${i}]`)); + else if (node !== null && typeof node === 'object') + for (const [k, v] of Object.entries(node)) { + if (FORBIDDEN_KEYS.includes(k)) problems.push(`${path}.${k} is forbidden`); + walk(v, `${path}.${k}`); + } + }; + walk(body, 'body'); + if (body.thinking?.type !== 'adaptive') problems.push('thinking is not adaptive'); + const last = body.messages?.[body.messages.length - 1]; + if (!last || last.role === 'assistant') problems.push('last turn is an assistant prefill'); + return problems; +} + +/** Scenario as above, plus: the reply is governed by the top-level effort, set to the row default. */ +describe('callByModel sends the direct Anthropic wire id and the row default effort', () => { + const sent: Sent[] = []; + + beforeEach(() => { + sent.length = 0; + vi.stubEnv('ANTHROPIC_API_KEY', 'test-key-not-real'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + sent.push({ + url: String(input instanceof Request ? input.url : input), + headers: Object.fromEntries(new Headers(init?.headers)), + body: JSON.parse(String(init?.body ?? '{}')) as Body, + }); + // A 400 ends the call without retries; only the request matters here. + return new Response( + JSON.stringify({ + type: 'error', + error: { type: 'invalid_request_error', message: 'stop' }, + }), + { status: 400, headers: { 'content-type': 'application/json' } }, + ); + }), + ); + }); + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + const run = (model: string) => + callByModel({ model, systemPrompt: 's', userText: 'u', maxTokens: 64 }); + + // Every spelling of one row must reach the same wire id and the same default effort. + it.each([ + ['anthropic/claude-sonnet-5.5', 'claude-sonnet-5-5', 'high'], + ['claude-sonnet-5-5', 'claude-sonnet-5-5', 'high'], + ['anthropic/claude-opus-5.5', 'claude-opus-5-5', 'medium'], + ['anthropic/claude-opus-5-5', 'claude-opus-5-5', 'medium'], + ['claude-opus-5-5', 'claude-opus-5-5', 'medium'], + ] as const)('%s goes out as %s at the row default effort %s', async (model, wireId, effort) => { + const result = await run(model); + expect(result.provider).toBe('anthropic'); + expect(sent).toHaveLength(1); + const { url, headers, body } = sent[0] as Sent; + expect(url).toContain('api.anthropic.com'); + expect(body.model).toBe(wireId); + expect(wireShapeProblems(body)).toEqual([]); + // A trailing effort-only message applies only from the NEXT user turn (migration guide, mid- + // conversation effort), and this request has none. The reply is governed by the top-level + // output_config.effort, which pi-ai hard-codes to 'high' for managed-effort rows; the client + // rewrites it to the row default (Opus 5.5 = medium). pi-ai's own trailing message is unchanged. + expect(body['output_config']).toEqual({ effort }); + expect(body.messages).toHaveLength(2); + expect(body.messages[0]?.role).toBe('user'); + expect(body.messages[1]).toEqual({ + role: 'system', + content: [], + output_config: { effort }, + }); + expect(headers['anthropic-beta']).toContain('mid-conversation-output-config-2026-07-01'); + }); + + it('keeps the existing Sonnet 5 row on its own id (pi-ai sends no effort for it)', async () => { + await run('anthropic/claude-sonnet-5'); + expect(sent).toHaveLength(1); + const body = (sent[0] as Sent).body; + expect(body.model).toBe('claude-sonnet-5'); + expect(JSON.stringify(body)).not.toContain('effort'); + expect(FORBIDDEN_KEYS.filter((k) => JSON.stringify(body).includes(`"${k}"`))).toEqual([]); + expect(body.messages.at(-1)?.role).toBe('user'); + }); +}, 30_000); // first call cold-imports the pi-ai catalog; the default 5 s timed out on a cold run + +/** + * SPEC 1.3 shapes for the two direct providers, checked on the whole body so an extra key cannot hide + * behind a `toMatchObject`. GPT-6.1: reasoning carries only effort (plus the summary pi-ai asks for), + * low..max, never `enabled` or a token budget; no sampling/logprob keys; the input does not end on an + * assistant turn. Gemini 3.8: thinkingConfig carries only includeThoughts and thinkingLevel + * (LOW/MEDIUM/HIGH), never thinkingBudget; no candidateCount or sampling keys; the last content is + * not a model turn (prefill is a 400). + */ +const DIRECT_FORBIDDEN_KEYS = [ + ...FORBIDDEN_KEYS, + 'thinking_budget', + 'thinkingBudget', + 'candidate_count', + 'candidateCount', + // Gemini's own sampling keys are camelCase (generationConfig.topP/topK); the walk is recursive, so + // they are caught at any depth, as is generationConfig.temperature via FORBIDDEN_KEYS. SPEC 1.3: + // sampling on Gemini 3.6+ is deprecated and must be removed. Codex round 6: injecting topP/topK left + // all 49 tests green because only the snake_case spellings were listed. + 'topP', + 'topK', + 'logprobs', + 'top_logprobs', + 'prefill', +]; + +function directWireProblems( + provider: 'openai' | 'gemini' | 'openrouter', + body: Record, +): string[] { + const problems: string[] = []; + const walk = (node: unknown, path: string) => { + if (Array.isArray(node)) node.forEach((v, i) => walk(v, `${path}[${i}]`)); + else if (node !== null && typeof node === 'object') + for (const [k, v] of Object.entries(node)) { + if (DIRECT_FORBIDDEN_KEYS.includes(k)) problems.push(`${path}.${k} is forbidden`); + walk(v, `${path}.${k}`); + } + }; + walk(body, 'body'); + const keysOutside = (obj: unknown, allowed: string[], path: string) => { + for (const k of Object.keys((obj ?? {}) as object)) + if (!allowed.includes(k)) problems.push(`${path}.${k} is not an allowed key`); + }; + if (provider === 'openrouter') { + // Chat Completions through OpenRouter (GPT-6.1 / Gemini 3.8 rows): reasoning carries only the + // row effort, and the messages do not end on an assistant prefill (SPEC 1.3). + const reasoning = body['reasoning'] as { effort?: string } | undefined; + keysOutside(reasoning, ['effort'], 'body.reasoning'); + if (!['low', 'medium', 'high', 'xhigh', 'max'].includes(reasoning?.effort ?? '')) + problems.push('reasoning.effort is not low..max'); + const messages = body['messages'] as { role?: string }[] | undefined; + const last = messages?.[messages.length - 1]; + if (!last || last.role === 'assistant') problems.push('last message is an assistant prefill'); + } else if (provider === 'openai') { + const reasoning = body['reasoning'] as { effort?: string } | undefined; + keysOutside(reasoning, ['effort', 'summary'], 'body.reasoning'); + if (!['low', 'medium', 'high', 'xhigh', 'max'].includes(reasoning?.effort ?? '')) + problems.push('reasoning.effort is not low..max'); + const input = body['input'] as { role?: string }[] | undefined; + const last = input?.[input.length - 1]; + if (!last || last.role === 'assistant') + problems.push('last input turn is an assistant prefill'); + } else { + const cfg = body['generationConfig'] as + | { thinkingConfig?: { thinkingLevel?: string } } + | undefined; + keysOutside( + cfg?.thinkingConfig, + ['includeThoughts', 'thinkingLevel'], + 'body.generationConfig.thinkingConfig', + ); + if (!['LOW', 'MEDIUM', 'HIGH'].includes(cfg?.thinkingConfig?.thinkingLevel ?? '')) + problems.push('thinkingLevel is not LOW/MEDIUM/HIGH'); + const contents = body['contents'] as { role?: string }[] | undefined; + const last = contents?.[contents.length - 1]; + if (!last || last.role === 'model') problems.push('last content is a model-turn prefill'); + } + return problems; +} + +describe('the direct-provider shape guard itself', () => { + // Codex round 5: injecting reasoning.max_tokens, reasoning.enabled:false and a trailing assistant + // input into the GPT-6.1 request left every test passing. The guard must object to each shape. + const gpt = { + model: 'm', + reasoning: { effort: 'high', summary: 'auto' }, + input: [{ role: 'user' }], + }; + const gem = { + contents: [{ role: 'user' }], + generationConfig: { + thinkingConfig: { includeThoughts: true, thinkingLevel: 'HIGH' }, + }, + }; + const orr = { + model: 'm', + messages: [{ role: 'user' }], + reasoning: { effort: 'high' }, + }; + it('accepts the clean bodies', () => { + expect(directWireProblems('openai', gpt)).toEqual([]); + expect(directWireProblems('gemini', gem)).toEqual([]); + expect(directWireProblems('openrouter', orr)).toEqual([]); + }); + it.each([ + [ + 'a reasoning token budget', + 'openai', + { ...gpt, reasoning: { ...gpt.reasoning, max_tokens: 1 } }, + ], + [ + 'a disabled reasoning block', + 'openai', + { ...gpt, reasoning: { ...gpt.reasoning, enabled: false } }, + ], + ['effort none', 'openai', { ...gpt, reasoning: { effort: 'none' } }], + [ + 'a trailing assistant input', + 'openai', + { ...gpt, input: [...gpt.input, { role: 'assistant' }] }, + ], + ['a sampling key', 'openai', { ...gpt, temperature: 0 }], + ['OpenRouter temperature', 'openrouter', { ...orr, temperature: 0 }], + ['OpenRouter top_p', 'openrouter', { ...orr, top_p: 0.9 }], + ['OpenRouter top_k', 'openrouter', { ...orr, top_k: 5 }], + [ + 'an OpenRouter trailing assistant message', + 'openrouter', + { ...orr, messages: [...orr.messages, { role: 'assistant' }] }, + ], + [ + 'OpenRouter reasoning.max_tokens', + 'openrouter', + { ...orr, reasoning: { effort: 'high', max_tokens: 1 } }, + ], + ['OpenRouter reasoning.enabled:false', 'openrouter', { ...orr, reasoning: { enabled: false } }], + ['logprobs', 'openai', { ...gpt, logprobs: true }], + [ + 'thinkingBudget', + 'gemini', + { + ...gem, + generationConfig: { + thinkingConfig: { thinkingLevel: 'HIGH', thinkingBudget: 0 }, + }, + }, + ], + [ + 'candidateCount', + 'gemini', + { + ...gem, + generationConfig: { ...gem.generationConfig, candidateCount: 2 }, + }, + ], + [ + 'generationConfig.topP', + 'gemini', + { ...gem, generationConfig: { ...gem.generationConfig, topP: 0.9 } }, + ], + [ + 'generationConfig.topK', + 'gemini', + { ...gem, generationConfig: { ...gem.generationConfig, topK: 5 } }, + ], + [ + 'generationConfig.temperature', + 'gemini', + { ...gem, generationConfig: { ...gem.generationConfig, temperature: 0 } }, + ], + ['a model-turn prefill', 'gemini', { ...gem, contents: [...gem.contents, { role: 'model' }] }], + [ + 'thinkingLevel MINIMAL', + 'gemini', + { + ...gem, + generationConfig: { thinkingConfig: { thinkingLevel: 'MINIMAL' } }, + }, + ], + ] as const)('rejects %s', (_label, provider, body) => { + expect(directWireProblems(provider, body as Record)).not.toEqual([]); + }); +}); + +/** + * Scenario: the same designer picks a GPT-6.1 Sol or Gemini 3.8 Flash row. The row default is `high`. + * pi-ai's `complete` reads a different option per API (`reasoningEffort` on the OpenAI Responses API, + * `thinking.level` on Gemini) and silently drops the `effort` that only its Anthropic path reads, so + * both calls used to go out at the vendor default (medium). The assertion is on the request body. + */ +describe('callByModel sends the row default effort on the OpenAI and Gemini APIs too', () => { + const sent: Sent[] = []; + + beforeEach(() => { + sent.length = 0; + vi.stubEnv('OPENAI_API_KEY', 'test-key-not-real'); + vi.stubEnv('GEMINI_API_KEY', 'test-key-not-real'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + sent.push({ + url: String(input instanceof Request ? input.url : input), + headers: Object.fromEntries(new Headers(init?.headers)), + body: JSON.parse(String(init?.body ?? '{}')) as Body, + }); + return new Response(JSON.stringify({ error: { message: 'stop', code: 400 } }), { + status: 400, + headers: { 'content-type': 'application/json' }, + }); + }), + ); + }); + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + const run = (model: string) => + callByModel({ model, systemPrompt: 's', userText: 'u', maxTokens: 64 }); + + it('openai/gpt-6.1-sol goes to the Responses API at reasoning.effort high, with no sampling keys', async () => { + await run('openai/gpt-6.1-sol'); + expect(sent).toHaveLength(1); + const { url, body } = sent[0] as Sent; + expect(url).toContain('api.openai.com/v1/responses'); + expect(body.model).toBe('gpt-6.1-sol'); + expect(body['reasoning']).toMatchObject({ effort: 'high' }); + expect(directWireProblems('openai', body)).toEqual([]); + }); + + it('google/gemini-3.8-flash goes out with thinkingLevel HIGH and no sampling keys', async () => { + await run('google/gemini-3.8-flash'); + expect(sent).toHaveLength(1); + const { url, body } = sent[0] as Sent; + expect(url).toContain('generativelanguage.googleapis.com'); + expect(url).toContain('gemini-3.8-flash'); + expect(body['generationConfig']).toMatchObject({ + thinkingConfig: { thinkingLevel: 'HIGH' }, + }); + expect(directWireProblems('gemini', body)).toEqual([]); + }); + + // Codex round 6: an explicit OpenRouter call to a GPT-6.1 or Gemini 3.8 row went out with no + // `reasoning` block, because pi-ai's chat-completions adapter reads `reasoningEffort`, not `effort`. + it.each([['openai/gpt-6.1-sol'], ['google/gemini-3.8-flash']])( + 'explicit OpenRouter call to %s carries the row default reasoning effort high', + async (modelId) => { + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + const result = await call({ + provider: 'openrouter', + modelId, + systemPrompt: 's', + userText: 'u', + maxTokens: 64, + }); + expect(result.provider).toBe('openrouter'); + expect(sent).toHaveLength(1); + const { url, body } = sent[0] as Sent; + expect(url).toContain('openrouter.ai'); + expect(body.model).toBe(modelId); + expect(body['reasoning']).toEqual({ effort: 'high' }); + // Codex round 8: injecting temperature/top_p/top_k or a trailing assistant turn into this + // builder left every test green, because only model and reasoning were read. + expect(directWireProblems('openrouter', body)).toEqual([]); + }, + ); + + // SPEC A.0.10: free-looking unknown ids reach the verified free router; every other unknown throws + // before any request. `openrouter/free` is a catalog route and used to lose its prefix. + it.each([['openrouter/free'], ['bogus/model:free'], ['vendor-free']])( + '%s resolves to the free router on OpenRouter', + async (model) => { + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + const result = await run(model); + expect(result.provider).toBe('openrouter'); + expect(sent).toHaveLength(1); + const { url, body } = sent[0] as Sent; + expect(url).toContain('openrouter.ai'); + expect(body.model).toBe('openrouter/free'); + }, + ); + + // SPEC D1: a NodeSlide catalog row is a known id and is never silently rerouted. These three used + // to reach OpenRouter as `openrouter/free` (pi-ai's `google` route had no such id, so the free + // fallback ran); each is now sent as itself, to OpenRouter. + it.each([ + ['google/gemma-4-26b-a4b-it:free'], + ['google/gemma-4-31b-it:free'], + ['nvidia/nemotron-3-super-120b-a12b:free'], + ])('catalog id %s is sent to OpenRouter as itself, not as the free router', async (model) => { + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + const result = await run(model); + expect(result.provider).toBe('openrouter'); + expect(sent).toHaveLength(1); + const { url, body } = sent[0] as Sent; + expect(url).toContain('openrouter.ai'); + expect(body.model).toBe(model); + }); + + // SPEC D1 / A.0.10: a SPEC 1.2 verified free id that pi-ai cannot serve is a known id, so it throws + // before any request instead of being rerouted to `openrouter/free`. + it('verified free id pi-ai has no row for is refused, not rerouted to the free router', async () => { + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + await expect(run('nvidia/nemotron-3.5-content-safety:free')).rejects.toThrow(/not rerouted/); + expect(sent).toEqual([]); + }); + + // The key the tool demands before it calls must be the key the call then uses. `vendor-free` once + // demanded OPENAI_API_KEY and was sent to OpenRouter; the gemma ids demanded GEMINI_API_KEY. + it.each([ + ['vendor-free'], + ['bogus/model:free'], + ['openrouter/free'], + ['google/gemma-4-26b-a4b-it:free'], + ['google/gemma-4-31b-it:free'], + ['nvidia/nemotron-3-super-120b-a12b:free'], + ])('%s needs the OpenRouter key alone, and only the OpenRouter key', async (model) => { + expect(localByokStatus([model]).models[0]).toMatchObject({ + provider: 'openrouter', + envVar: 'OPENROUTER_API_KEY', + }); + // Only an OpenRouter key is set: the check passes and the call goes where the check said. + vi.stubEnv('OPENAI_API_KEY', ''); + vi.stubEnv('GEMINI_API_KEY', ''); + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + expect(() => requireLocalKeys([model])).not.toThrow(); + const result = await run(model); + expect(result.provider).toBe('openrouter'); + expect(sent[0]?.url).toContain('openrouter.ai'); + }); + + it('refuses a free-looking id when only the inferred vendor key is set', () => { + vi.stubEnv('OPENAI_API_KEY', 'test-key-not-real'); + vi.stubEnv('GEMINI_API_KEY', 'test-key-not-real'); + vi.stubEnv('OPENROUTER_API_KEY', ''); + expect(() => requireLocalKeys(['vendor-free'])).toThrow(/OPENROUTER_API_KEY/); + expect(() => requireLocalKeys(['google/gemma-4-26b-a4b-it:free'])).toThrow( + /OPENROUTER_API_KEY/, + ); + }); + + it.each([['bogus/model'], ['gpt-nonexistent'], ['claude-unknown-9']])( + '%s is refused before any request', + async (model) => { + await expect(run(model)).rejects.toThrow(/Unknown model/); + expect(sent).toEqual([]); + }, + ); +}, 30_000); + +/** + * Scenario: a designer keeps working with the rows this refresh did not touch (the previous-generation + * GPT-5.6 rows and the frozen Gemini 3.1 Pro preview). SPEC A.0.4 says their behaviour is as today, so + * their request must be exactly the one main's client sent: `pi.complete` with only `maxOutputTokens`, + * which is how main's `call()` invoked it. Applying the new rows' effort to them changed the OpenAI + * rows from reasoning effort 'none' to 'high' and gave Gemini 3.1 Pro an explicit thinking level. + */ +describe('callByModel leaves the requests of rows this refresh does not add byte-identical to main', () => { + const sent: Sent[] = []; + + beforeEach(() => { + sent.length = 0; + vi.stubEnv('OPENAI_API_KEY', 'test-key-not-real'); + vi.stubEnv('GEMINI_API_KEY', 'test-key-not-real'); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + sent.push({ + url: String(input instanceof Request ? input.url : input), + headers: Object.fromEntries(new Headers(init?.headers)), + body: JSON.parse(String(init?.body ?? '{}')) as Body, + }); + return new Response(JSON.stringify({ error: { message: 'stop', code: 400 } }), { + status: 400, + headers: { 'content-type': 'application/json' }, + }); + }), + ); + }); + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + /** What main's `call()` sent: the registry model and `{ maxOutputTokens }`, nothing else. */ + async function mainRequest(provider: 'openai' | 'google', canonicalId: string): Promise { + const pi = await import('@earendil-works/pi-ai/compat'); + // biome-ignore lint/suspicious/noExplicitAny: pi-ai's getModel is typed against its compile-time registry + const model = (pi.getModel as any)(provider, canonicalId); + sent.length = 0; + await pi.complete( + model, + { + systemPrompt: 's', + messages: [ + { + role: 'user', + content: [{ type: 'text', text: 'u' }], + timestamp: 0, + }, + ], + }, + { maxOutputTokens: 64 }, + ); + return sent[0] as Sent; + } + + it.each([ + ['openai/gpt-5.6-sol', 'openai', 'gpt-5.6-sol'], + ['openai/gpt-5.6-terra', 'openai', 'gpt-5.6-terra'], + ['google/gemini-3.1-pro-preview', 'google', 'gemini-3.1-pro-preview'], + ['google/gemini-3.5-flash', 'google', 'gemini-3.5-flash'], + ] as const)('%s sends the body main sent', async (id, provider, canonicalId) => { + const baseline = await mainRequest(provider, canonicalId); + sent.length = 0; + await callByModel({ + model: id, + systemPrompt: 's', + userText: 'u', + maxTokens: 64, + }); + expect(sent).toHaveLength(1); + const now = sent[0] as Sent; + expect(now.url).toBe(baseline.url); + expect(now.body).toEqual(baseline.body); + expect(JSON.stringify(now.body)).toBe(JSON.stringify(baseline.body)); + }); + + // SPEC 1.2 supersession (2026-10-31 recheck): Flint is a verified free id with no pi-ai row, so it is + // a known id and is refused, never sent as `openrouter/free`. + it('recursive/flint-v1.0:free is refused before any request, not rerouted', async () => { + vi.stubEnv('OPENROUTER_API_KEY', 'test-key-not-real'); + await expect( + callByModel({ + model: 'recursive/flint-v1.0:free', + systemPrompt: 's', + userText: 'u', + maxTokens: 64, + }), + ).rejects.toThrow(/not rerouted/); + expect(sent).toEqual([]); + }); +}, 30_000); + +/** The checker above is only worth having if it rejects each shape A.0.6 forbids. */ +describe('wireShapeProblems rejects the shapes SPEC A.0.6 forbids', () => { + const ok = { + thinking: { type: 'adaptive' }, + messages: [{ role: 'user', content: [] }], + }; + it.each([ + ['temperature', { ...ok, temperature: 0 }], + ['top_p', { ...ok, top_p: 0.9 }], + ['top_k', { ...ok, top_k: 5 }], + ['a forced tool_choice', { ...ok, tool_choice: { type: 'tool', name: 'x' } }], + ['budget_tokens', { ...ok, thinking: { type: 'adaptive', budget_tokens: 1024 } }], + ['disabled thinking', { ...ok, thinking: { type: 'disabled' } }], + [ + 'an assistant prefill', + { + ...ok, + messages: [...ok.messages, { role: 'assistant', content: '{' }], + }, + ], + ])('%s', (_name, body) => { + expect(wireShapeProblems(body)).not.toEqual([]); + }); + it('accepts the clean shape', () => { + expect(wireShapeProblems(ok)).toEqual([]); + }); +}); diff --git a/mcp/src/lib/nodeslideTools.ts b/mcp/src/lib/nodeslideTools.ts index 93bc951b..8b43cd4c 100644 --- a/mcp/src/lib/nodeslideTools.ts +++ b/mcp/src/lib/nodeslideTools.ts @@ -3,7 +3,10 @@ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { z } from 'zod'; import { buildNodeSlideStoryContext } from '../../../convex/lib/nodeslideStoryContext.js'; import { writeDeckArtifacts } from '../../../packages/cli/src/generate.js'; -import type { NodeSlideWorkspace as CanonicalNodeSlideWorkspace } from '../../../shared/nodeslide.js'; +import { + type NodeSlideWorkspace as CanonicalNodeSlideWorkspace, + NODESLIDE_DEFAULT_AGENT_MODEL, +} from '../../../shared/nodeslide.js'; import { localByokStatus, requireLocalKeys } from './byok.js'; import { type CallResult, callByModel } from './llmClient.js'; @@ -12,7 +15,7 @@ const REVIEW_CONSENT = 'openrouter_nodeslide_review_context_v1'; const BRIEF_CONSENT = 'openrouter_full_brief_v1'; const WEB_CONSENT = 'nodeslide_web_research_v1'; const LOCAL_BYOK_CONSENT = 'nodeslide_local_byok_edit_v1'; -const DEFAULT_BYOK_MODEL = process.env.NODESLIDE_BYOK_MODEL ?? 'moonshotai/kimi-k3'; +const DEFAULT_BYOK_MODEL = process.env.NODESLIDE_BYOK_MODEL ?? NODESLIDE_DEFAULT_AGENT_MODEL; const NODE_SLIDE_EXTERNAL_OPERATION_MAX = 8; const NODE_SLIDE_PAGE_DEFAULT = 25; const NODE_SLIDE_PAGE_MAX = 100; @@ -604,7 +607,10 @@ export function registerNodeSlideTools(server: McpServer, convexCall: ConvexCall scope, providerMode: args.execution === 'hosted' ? 'openrouter_free' : 'deterministic', ...(args.execution === 'hosted' - ? { providerModel: args.model ?? 'moonshotai/kimi-k3', providerConsent: REVIEW_CONSENT } + ? { + providerModel: args.model ?? NODESLIDE_DEFAULT_AGENT_MODEL, + providerConsent: REVIEW_CONSENT, + } : {}), ...(args.idempotencyKey ? { idempotencyKey: args.idempotencyKey } : {}), }); @@ -739,7 +745,7 @@ export function registerNodeSlideTools(server: McpServer, convexCall: ConvexCall clientSessionId: z.string().min(8).max(256), accessCode: z.string().optional(), execution: z.enum(['hosted', 'deterministic']).default('hosted'), - model: z.string().default('moonshotai/kimi-k3'), + model: z.string().default(NODESLIDE_DEFAULT_AGENT_MODEL), effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).default('low'), consent: z.boolean().default(false), outputDirectory: z.string().min(1).default('nodeslide-output'), diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 2661881a..ed7ece77 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -6,6 +6,7 @@ import type { NodeSlideInstallProfile, NodeSlideUiMode, } from '@nodeslide/registry'; +import { NODESLIDE_DEFAULT_AGENT_MODEL } from '../../../shared/nodeslide'; import { generateDeck, resolveGenerateEffort } from './generate'; import { type NodeSlideInitOptions, runNodeSlideInit, runNodeSlideUpgrade } from './index'; @@ -53,8 +54,8 @@ try { outputDirectory: pathValue(flags, 'output') ?? process.cwd(), clientSessionId: pathValue(flags, 'session') ?? `cli-${Date.now()}-${crypto.randomUUID().slice(0, 12)}`, - model: pathValue(flags, 'model') ?? 'moonshotai/kimi-k3', - effort: effortValue(flags, pathValue(flags, 'model') ?? 'moonshotai/kimi-k3'), + model: pathValue(flags, 'model') ?? NODESLIDE_DEFAULT_AGENT_MODEL, + effort: effortValue(flags, pathValue(flags, 'model') ?? NODESLIDE_DEFAULT_AGENT_MODEL), ...((pathValue(flags, 'access-code') ?? process.env['NODESLIDE_PREVIEW_ACCESS_CODE']) ? { accessCode: diff --git a/scripts/build-model-capability-ledger.mjs b/scripts/build-model-capability-ledger.mjs index 3df8dbbb..ec05fc8c 100644 --- a/scripts/build-model-capability-ledger.mjs +++ b/scripts/build-model-capability-ledger.mjs @@ -51,6 +51,33 @@ const MODEL_POLICIES = { }, }; +// Rows added by the 2026-10 model refresh. None has a Deck Gym run yet (the frozen v1 matrix +// carries only kimi-k3, claude-sonnet-5 and gemini-3.5-flash), so each policy states that no role +// is claimed until a live-route ablation passes; the card reports 0 attempted runs, not a guess. +function unmeasuredPolicy(slug, label) { + return { + slug, + label, + bestRoles: ['no full-deck role until a live-route ablation passes'], + avoidRoles: ['full-deck generator', 'fallback authority', 'final taste judge'], + scaffolding: ['no-generic-fallback', 'independent route verification'], + }; +} + +MODEL_POLICIES['anthropic/claude-sonnet-5.5'] = unmeasuredPolicy( + 'claude-sonnet-5-5', + 'Claude Sonnet 5.5', +); +MODEL_POLICIES['anthropic/claude-opus-5.5'] = unmeasuredPolicy( + 'claude-opus-5-5', + 'Claude Opus 5.5', +); +MODEL_POLICIES['google/gemini-3.8-flash'] = unmeasuredPolicy( + 'gemini-3-8-flash', + 'Gemini 3.8 Flash', +); +MODEL_POLICIES['openai/gpt-6.1-sol'] = unmeasuredPolicy('gpt-6-1-sol', 'GPT-6.1 Sol'); + export async function buildModelCapabilityLedger({ artifactDir, outputDir }) { const matrix = await readJson(path.join(artifactDir, 'matrix.json')); const runDirs = await discoverRunDirs(path.join(artifactDir, 'runs')); @@ -171,7 +198,13 @@ export function summarizeModel({ confidence: { cognitiveBehavior: 'low — no plan or reasoning traces captured', toolExecution: 'low — only browser creation and export were observed', - artifactQuality: evaluations.length >= 20 ? 'high' : 'medium', + // No evaluated runs is no evidence about artifact quality: report that, not a middling grade. + artifactQuality: + evaluations.length === 0 + ? 'none — no evaluated runs' + : evaluations.length >= 20 + ? 'high' + : 'medium', routingRecommendation: live.length >= 6 ? 'medium' : 'low', }, status: 'provisional — requires skill-on versus skill-off ablation', diff --git a/scripts/capture-model-fleet-probe.mjs b/scripts/capture-model-fleet-probe.mjs index 2bacf12c..9f1d019b 100644 --- a/scripts/capture-model-fleet-probe.mjs +++ b/scripts/capture-model-fleet-probe.mjs @@ -5,7 +5,11 @@ import path from 'node:path'; import process from 'node:process'; import { ConvexHttpClient } from 'convex/browser'; import { api } from '../convex/_generated/api.js'; -import { validateModelFleetReceipt } from './lib/model-fleet-receipt-core.mjs'; +import { + EXECUTOR_SPLIT_RECEIPT_SCHEMA, + executorSplitReceiptFailures, + validateModelFleetReceipt, +} from './lib/model-fleet-receipt-core.mjs'; import { assertNodeSlideProductionDeployKey, captureNodeSlideConvexBuildIdentity, @@ -29,6 +33,7 @@ const allowedProbeFunctions = new Map([ ['runFleet', 'nodeslide.model-fleet-probe/v1'], ['runFreeRouterFleet', 'nodeslide.free-router-fleet-probe/v1'], ['runFreeRouterStructured', 'nodeslide.free-router-structured-probe/v1'], + ['runExecutorSplit', 'nodeslide.executor-split-probe/v1'], ]); if (allowedProbeFunctions.get(probeFunction) !== expectedSchema) { fail('Probe function and expected schema are not an allowed pair'); @@ -95,10 +100,20 @@ const exitCode = await new Promise((resolve, reject) => { if (exitCode !== 0) fail(`Convex fleet action failed (${safeDiagnostic(stderr)})`); const receipt = parseReceipt(stdout); -try { - validateModelFleetReceipt(receipt, expectedSchema); -} catch (error) { - fail(error instanceof Error ? error.message : 'Convex fleet action returned an invalid receipt'); +const isExecutorSplit = expectedSchema === EXECUTOR_SPLIT_RECEIPT_SCHEMA; +if (isExecutorSplit) { + // The deployed backend must be the merge commit this workflow run stamped (sourceCommit). + const failures = executorSplitReceiptFailures(receipt, sourceCommit); + receipt.passed = failures.length === 0; + receipt.failures = failures; +} else { + try { + validateModelFleetReceipt(receipt, expectedSchema); + } catch (error) { + fail( + error instanceof Error ? error.message : 'Convex fleet action returned an invalid receipt', + ); + } } const exactMainSourceAfter = await verifyNodeSlideExactMainSource( sourceCommit, @@ -121,7 +136,9 @@ const artifact = { await mkdir(path.dirname(outputPath), { recursive: true }); await writeFile(outputPath, `${JSON.stringify(artifact, null, 2)}\n`, { mode: 0o600 }); console.log( - `[model-fleet] ${receipt.passed ? 'PASS' : 'FAIL'} ${receipt.probedModelCount - receipt.failedModelCount}/${receipt.probedModelCount} offered routes returned assistant text`, + isExecutorSplit + ? `[model-fleet] ${receipt.passed ? 'PASS' : 'FAIL'} executor split${receipt.passed ? '' : `: ${receipt.failures.join('; ')}`}` + : `[model-fleet] ${receipt.passed ? 'PASS' : 'FAIL'} ${receipt.probedModelCount - receipt.failedModelCount}/${receipt.probedModelCount} offered routes returned assistant text`, ); console.log(`[model-fleet] artifact: ${path.relative(process.cwd(), outputPath)}`); if (!receipt.passed) process.exit(1); diff --git a/scripts/lib/deck-gym-campaign.mjs b/scripts/lib/deck-gym-campaign.mjs new file mode 100644 index 00000000..c526317f --- /dev/null +++ b/scripts/lib/deck-gym-campaign.mjs @@ -0,0 +1,355 @@ +/** + * Campaign cost control for `scripts/run-deck-gym.mjs`. + * + * Situation: a person starts a keyed Deck Gym campaign of dozens of production runs and walks away. + * Nothing in the runner used to count dollars, so the only brake was how long it took. This module + * is that brake. Before a worker dequeues a run it asks `shouldStopCampaign` whether the money + * already spent, plus a worst-case reservation for this run and for every run still in flight, + * would cross the campaign cap. After a run it charges the backend budget ledger's figure (never the + * Trace inspector text, which is attribution), or the full reservation when that figure cannot be + * read. It is a separate module so the production worker and its test are the same function. + */ +import { randomUUID } from 'node:crypto'; +import { closeSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs'; +import { mkdir, readFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { + NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD, + combineNodeGymLedgerReceipts, + nodeGymRunCharge, + shouldStopCampaign, + writeNodeGymFileAtomic, +} from './node-gym-runner-core.mjs'; + +export const DECK_GYM_DEFAULT_LIMIT_FOR_UNCAPPED = 12; + +/** + * The campaign cap. An explicit value always wins. Without one the run count itself must bound the + * spend: a campaign of at most 12 runs is capped at its own worst case (limit x per-run cap), the + * same shape as node-gym's default cap for a bounded subset; a larger campaign must say how much it + * may spend. + */ +export function resolveDeckGymMaxTotalCostMicroUsd({ explicit, limit }) { + if (explicit !== undefined) { + const parsed = Number(explicit); + if (!Number.isSafeInteger(parsed) || parsed < 0) + throw new Error('--max-total-cost-micro-usd must be a non-negative integer.'); + return parsed; + } + if (Number.isSafeInteger(limit) && limit >= 1 && limit <= DECK_GYM_DEFAULT_LIMIT_FOR_UNCAPPED) + return limit * NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD; + throw new Error( + `--max-total-cost-micro-usd is required unless --limit is at most ${DECK_GYM_DEFAULT_LIMIT_FOR_UNCAPPED}.`, + ); +} + +/** + * `spentCostMicroUsd` starts from what earlier invocations of this campaign already cost + * (`restoreDeckGymSpend`): the cap binds the whole campaign, not one process. Every run reserves the + * backend ledger cap that binds it; that cap is not an option, because a reservation below it lets a + * campaign dispatch paid work it has not budgeted for. + */ +export function createDeckGymCampaignBudget({ maxTotalCostMicroUsd, spentCostMicroUsd = 0 }) { + if (!Number.isSafeInteger(maxTotalCostMicroUsd) || maxTotalCostMicroUsd < 0) + throw new Error('Deck Gym campaign cap must be a non-negative integer.'); + if (!Number.isSafeInteger(spentCostMicroUsd) || spentCostMicroUsd < 0) + throw new Error('Deck Gym restored spend must be a non-negative integer.'); + return { + maxTotalCostMicroUsd, + perRunMaxCostMicroUsd: NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD, + spentCostMicroUsd, + inFlight: 0, + stoppedBy: null, + }; +} + +export const DECK_GYM_LOCK_FILE = 'campaign.lock'; + +/** + * One invocation at a time per runs directory. Spend is restored from disk once at start and then + * tracked in memory, and each charge rewrites a run's whole history, so two invocations on the same + * directory each see an empty balance, can dispatch the same run, and overwrite each other's + * charges: replayed, two runs finalized 1,600,000 micro-USD against a 1,000,000 cap and only 800,000 + * was persisted. The cap cannot hold unless a second invocation never starts. `O_EXCL` creation is + * the test-and-set; the file names its holder. Synchronous so an exit or signal handler can release. + * A crashed holder leaves the file behind and the next start refuses, naming it: remove it once the + * recorded pid is confirmed dead (no liveness probe on purpose: a wrong guess would admit a second + * invocation, which is the failure this exists to stop). Release unlinks only a file that still + * carries this holder's token: if the lock was deleted by hand and another invocation took it, the + * first holder exiting must not delete the second holder's lock. That narrows the race rather than closing it: a pathname lock has no atomic compare-and-unlink, so a hand deletion plus a new acquire inside the read-to-unlink window (well under a millisecond) can still lose a lock. `label` names the campaign kind in + * the refusal; node-gym takes the same lock on its campaign directory. + */ +export function acquireDeckGymCampaignLock(runsDir, label = 'Deck Gym') { + const file = path.join(runsDir, DECK_GYM_LOCK_FILE); + let fd; + try { + fd = openSync(file, 'wx'); + } catch (error) { + if (error?.code !== 'EEXIST') throw error; + let holder = 'unknown holder'; + try { + holder = readFileSync(file, 'utf8').trim() || holder; + } catch {} + throw new Error( + `${label} campaign in ${runsDir} is already running (${holder}); a second invocation would restore the same balance and overspend the cap. If that process is dead, delete ${file} and start again.`, + { cause: error }, + ); + } + const token = randomUUID(); + writeSync(fd, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), token })); + let released = false; + return function release() { + if (released) return; + released = true; + closeSync(fd); + let ownsFile = false; + try { + ownsFile = JSON.parse(readFileSync(file, 'utf8'))?.token === token; + } catch {} + if (ownsFile) unlinkSync(file); + }; +} + +export const DECK_GYM_CHARGES_FILE = 'budget-charges.json'; +const DECK_GYM_CHARGES_SCHEMA = 'nodeslide.deck-gym-run-charges/v1'; + +/** + * Every charge one run directory has incurred, oldest first. Append-only in spirit: an attempt writes + * its reservation before it dispatches and replaces that entry with the ledger figure when it ends, + * so an attempt whose process died stays charged at its reservation and a re-run adds to it. + * A file that cannot be read back throws: the history it held is unknown, any figure made up for it + * (zero, or one reservation) can be lower than what it held, and every caller either restores spend + * or appends to the history, so a made-up figure would admit paid runs past the cap or overwrite the + * lost history for good. Only a missing file (`null`) is a run with no charges yet. + */ +export async function readDeckGymRunCharges(runDir) { + const file = path.join(runDir, DECK_GYM_CHARGES_FILE); + let text; + try { + text = await readFile(file, 'utf8'); + } catch (error) { + if (error?.code === 'ENOENT') return null; + throw new Error( + `Deck Gym charge history ${file} cannot be read (${error?.code ?? error?.message}); spend is unknown, so the campaign stops. Restore the file or remove the run directory deliberately.`, + { cause: error }, + ); + } + const unreadable = (why) => + new Error( + `Deck Gym charge history ${file} is ${why}; spend is unknown, so the campaign stops. Restore the file or remove the run directory deliberately.`, + ); + let parsed; + try { + parsed = JSON.parse(text); + } catch { + throw unreadable('not valid JSON'); + } + const charges = parsed?.charges; + if ( + parsed?.schemaVersion !== DECK_GYM_CHARGES_SCHEMA || + !Array.isArray(charges) || + !charges.every( + (charge) => + Number.isSafeInteger(charge?.chargedMicroUsd) && + charge.chargedMicroUsd >= 0 && + ['ledger', 'reservation'].includes(charge.source), + ) + ) + throw unreadable('not a valid charge history'); + return charges.map(({ chargedMicroUsd, source }) => ({ chargedMicroUsd, source })); +} + +/** + * The whole history is rewritten on every change, so the rewrite must be atomic: a plain truncating + * write interrupted partway leaves a file that cannot be read back, and an unreadable history stops + * the campaign (it used to come back as ONE reservation, so 2,000,000 micro-USD of history became + * 1,000,000 and the next run was admitted under the cap). Temp file plus rename leaves either the old + * history or the new one, never a torn file. + */ +export async function writeDeckGymRunCharges(runDir, charges) { + await mkdir(runDir, { recursive: true }); + await writeNodeGymFileAtomic( + runDir, + path.join(runDir, DECK_GYM_CHARGES_FILE), + `${JSON.stringify({ schemaVersion: DECK_GYM_CHARGES_SCHEMA, charges }, null, 2)} +`, + { label: 'Deck Gym charge history' }, + ); +} + +/** + * Each run's charge history is one file in `/`, read-modify-written by whichever worker + * holds that run. Two runs that share a directory (the same runId, or ids that differ only in case on + * a case-insensitive filesystem) would lose one worker's reservation or charge to the other's write and + * restore less than was spent, so a matrix that repeats an id is refused before anything is dispatched. + */ +export function assertUniqueDeckGymRunIds(runs) { + const seen = new Map(); + for (const run of runs) { + if (typeof run?.runId !== 'string' || run.runId === '') { + throw new Error('Deck Gym matrix has a run without a runId.'); + } + // runId is joined onto runsDir as a directory name (run-deck-gym.mjs), so it must be exactly one + // path component: 'group/../same' resolves onto 'same' and '../../x' leaves runsDir, and either + // would put two runs' charge histories in one file or write one outside the campaign directory. + // A leading dot rules out '.' and '..'; a trailing dot is dropped by Windows ('same.' is 'same'). + if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/u.test(run.runId) || run.runId.endsWith('.')) { + throw new Error( + `Deck Gym matrix runId "${run.runId}" is not a single safe path component (letters, digits, '_', '-', and '.' inside).`, + ); + } + const key = run.runId.toLowerCase(); + if (seen.has(key)) { + throw new Error( + `Deck Gym matrix repeats a run directory: "${seen.get(key)}" and "${run.runId}" share one charge history.`, + ); + } + seen.set(key, run.runId); + } +} + +/** Persist the reservation of an attempt about to be dispatched. */ +export async function recordDeckGymReservation(runDir, reservationMicroUsd) { + const charges = (await readDeckGymRunCharges(runDir)) ?? []; + await writeDeckGymRunCharges(runDir, [ + ...charges, + { chargedMicroUsd: reservationMicroUsd, source: 'reservation' }, + ]); +} + +/** Replace the attempt's reservation entry (the last one) with what the attempt was charged. */ +export async function recordDeckGymCharge(runDir, charge) { + const charges = (await readDeckGymRunCharges(runDir)) ?? []; + charges.splice(Math.max(charges.length - 1, 0), 1, { + chargedMicroUsd: charge.chargedMicroUsd, + source: charge.source, + }); + await writeDeckGymRunCharges(runDir, charges); +} + +/** + * What every earlier invocation already spent in this runs directory, whatever this invocation + * selected: `--limit` or a narrower matrix must not make earlier spend disappear, because the cap + * binds the whole campaign. A run directory with a charges file contributes its charges. A directory + * without one but with anything in it is from an invocation that predates charge records, or from a + * process that died before writing one: its spend is unknown, so it is charged one reservation, + * written down now so that re-running the run cannot erase it. Only a missing runs directory means + * nothing was spent; any other read failure is unknown spend and stops the campaign. + */ +export async function restoreDeckGymSpend({ runsDir }) { + let entries; + try { + entries = await readdir(runsDir, { withFileTypes: true }); + } catch (error) { + if (error?.code === 'ENOENT') return 0; + throw error; + } + let total = 0; + for (const entry of entries.filter((candidate) => candidate.isDirectory())) { + const runDir = path.join(runsDir, entry.name); + let charges = await readDeckGymRunCharges(runDir); + if (charges === null) { + // Only a vanished directory is empty. Any other listing failure (EACCES, EBUSY, EIO) leaves the + // run's spend unknown, so it stops the campaign instead of counting as nothing spent. + const present = await readdir(runDir).catch((error) => { + if (error?.code === 'ENOENT') return []; + throw error; + }); + if (present.length === 0) continue; + charges = [ + { chargedMicroUsd: NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD, source: 'reservation' }, + ]; + await writeDeckGymRunCharges(runDir, charges); + } + for (const charge of charges) total += charge.chargedMicroUsd; + if (!Number.isSafeInteger(total)) + throw new Error('Deck Gym campaign cumulative cost exceeds the safe integer range.'); + } + return total; +} + +export function deckGymBudgetSummary(budget) { + return { + maxTotalCostMicroUsd: budget.maxTotalCostMicroUsd, + spentCostMicroUsd: budget.spentCostMicroUsd, + reservedInFlightMicroUsd: budget.inFlight * budget.perRunMaxCostMicroUsd, + stoppedBy: budget.stoppedBy, + }; +} + +/** + * One worker. `executeRun(run)` drives the browser and resolves to a receipt that may carry + * `backendRunIds`; `readLedger(ids)` resolves to a Map of run id -> backend ledger receipt (null when + * unreadable). Both are injected so a test drives this exact loop with a fake page and ledger. + */ +export async function deckGymWorker({ + queue, + budget, + receipts, + isResumable, + executeRun, + readLedger, + recordReservation = async () => undefined, + recordCharge = async () => undefined, + onSkip = () => undefined, + onStop = () => undefined, +}) { + while (queue.length && budget.stoppedBy === null) { + const run = queue.shift(); + if (!run) return; + if (await isResumable(run)) { + receipts.push({ runId: run.runId, status: 'skipped', reason: 'resume_artifact_exists' }); + onSkip(run); + continue; + } + // Check and reserve with no await in between: two workers must not both see the same headroom. + const decision = shouldStopCampaign({ + spentCostMicroUsd: budget.spentCostMicroUsd, + maxTotalCostMicroUsd: budget.maxTotalCostMicroUsd, + failures: 0, + maxFailures: Number.POSITIVE_INFINITY, + nextRunMaxCostMicroUsd: (budget.inFlight + 1) * budget.perRunMaxCostMicroUsd, + }); + if (decision.stop) { + queue.unshift(run); + budget.stoppedBy = decision.issueCode; + onStop(decision.issueCode, run); + return; + } + budget.inFlight += 1; + // Written before dispatch: if this process dies mid-run, the next invocation finds the reservation. + // A write that fails is not swallowed: a run that cannot be recorded must not be started. + await recordReservation(run, budget.perRunMaxCostMicroUsd); + let receipt; + try { + receipt = await executeRun(run); + } catch (error) { + receipt = { + runId: run.runId, + status: 'failed', + failure: String(error instanceof Error ? error.message : error).slice(0, 300), + }; + } + let ledgerReceipt = null; + try { + const ids = Array.isArray(receipt?.backendRunIds) ? receipt.backendRunIds : []; + ledgerReceipt = combineNodeGymLedgerReceipts(ids, await readLedger(ids)); + } catch { + ledgerReceipt = null; + } + const charge = nodeGymRunCharge({ + reservationMicroUsd: budget.perRunMaxCostMicroUsd, + ledgerReceipt, + }); + budget.spentCostMicroUsd += charge.chargedMicroUsd; + budget.inFlight -= 1; + await recordCharge(run, charge); + // Backend run ids are working data for the ledger lookup, not part of the published summary. + const { backendRunIds, ...publicReceipt } = receipt ?? {}; + receipts.push({ + ...publicReceipt, + backendRunCount: Array.isArray(backendRunIds) ? backendRunIds.length : 0, + budget: charge, + }); + } +} diff --git a/scripts/lib/model-fleet-receipt-core.mjs b/scripts/lib/model-fleet-receipt-core.mjs index 9cdee5c4..5c9afc85 100644 --- a/scripts/lib/model-fleet-receipt-core.mjs +++ b/scripts/lib/model-fleet-receipt-core.mjs @@ -1,26 +1,36 @@ +import { createHash } from 'node:crypto'; + export const NODE_SLIDE_OFFERED_ROUTE_CATALOG = [ ['moonshotai/kimi-k3', 'openrouter', 'moonshotai/kimi-k3'], ['z-ai/glm-5.2', 'openrouter', 'z-ai/glm-5.2'], ['anthropic/claude-sonnet-5', 'openrouter', 'anthropic/claude-sonnet-5'], ['anthropic/claude-fable-5', 'openrouter', 'anthropic/claude-fable-5'], - ['google/gemini-3.5-flash', 'openrouter', 'google/gemini-3.5-flash'], + ['anthropic/claude-sonnet-5.5', 'openrouter', 'anthropic/claude-sonnet-5.5'], + ['anthropic/claude-opus-5.5', 'openrouter', 'anthropic/claude-opus-5.5'], + // google/gemini-3.5-flash left the offered set: Google deprecated it on 2026-10-08. + ['google/gemini-3.8-flash', 'openrouter', 'google/gemini-3.8-flash'], ['google/gemini-3.1-pro-preview', 'openrouter', 'google/gemini-3.1-pro-preview'], ['openai/gpt-5.6-sol', 'openrouter', 'openai/gpt-5.6-sol'], ['openai/gpt-5.6-terra', 'openrouter', 'openai/gpt-5.6-terra'], + ['openai/gpt-6.1-sol', 'openrouter', 'openai/gpt-6.1-sol'], ].map(([id, provider, upstreamId]) => ({ id, provider, upstreamId })); export const NODE_SLIDE_FREE_ROUTE_CATALOG = [ ['openrouter/free', 'openrouter', 'openrouter/free'], ['google/gemma-4-26b-a4b-it:free', 'openrouter', 'google/gemma-4-26b-a4b-it:free'], ['google/gemma-4-31b-it:free', 'openrouter', 'google/gemma-4-31b-it:free'], - [ - 'nvidia/nemotron-3-super-120b-a12b:free', - 'openrouter', - 'nvidia/nemotron-3-super-120b-a12b:free', - ], - ['openai/gpt-oss-20b:free', 'openrouter', 'openai/gpt-oss-20b:free'], + // nvidia/nemotron-3-super-120b-a12b:free dropped: absent from the OpenRouter catalog (GET /api/v1/models, 2026-10-31). + // openai/gpt-oss-20b:free dropped: absent from the OpenRouter catalog (GET /api/v1/models, 2026-10-10). ].map(([id, provider, upstreamId]) => ({ id, provider, upstreamId })); +export const EXECUTOR_SPLIT_RECEIPT_SCHEMA = 'nodeslide.executor-split-probe/v1'; +// Mirrors NODESLIDE_ROUTING_EXECUTOR_MODEL (SPEC "Homen decisions", 2026-11-06; was google/gemini-3.8-flash). +const EXECUTOR_SPLIT_EXECUTOR_MODEL = 'deepseek/deepseek-v4.1-flash-1017'; +const EXECUTOR_SPLIT_PLANNER_MODEL = 'moonshotai/kimi-k3'; +const EXECUTOR_SPLIT_COMMAND = 'npx convex run nodeslideModelProbe:runExecutorSplit'; +/** Pre-flight ceiling: one planner call and one executor call. A third is a retry or repair call. */ +const EXECUTOR_SPLIT_MAX_REQUESTS = 2; + const CATALOG_BY_SCHEMA = new Map([ ['nodeslide.model-fleet-probe/v1', NODE_SLIDE_OFFERED_ROUTE_CATALOG], ['nodeslide.free-router-fleet-probe/v1', NODE_SLIDE_FREE_ROUTE_CATALOG], @@ -127,3 +137,177 @@ function isNormalizedModelIdentity(value) { /^[A-Za-z0-9._-]+\/[A-Za-z0-9._:-]+$/u.test(value) ); } + +/** + * Acceptance rule for the routed-executor receipt (SPEC Part A, sections A.0.3 and A.2.8). Accepted + * only when the turn really split to the new executor, the provider echoed that exact model with + * non-zero usage, the executor's copy was applied, the ledger shows spend and no refusal, no call was + * retried or fell back to another model, and the deployment names the tested commit. Returns the + * failures; an empty list means accepted. Never throws on a bad receipt. A rejected receipt is re-run, + * never edited. + */ +export function executorSplitReceiptFailures(receipt, testedCommit) { + if (!receipt || receipt.schemaVersion !== EXECUTOR_SPLIT_RECEIPT_SCHEMA) + return ['receipt schema is not nodeslide.executor-split-probe/v1']; + const failures = []; + const fail = (message) => failures.push(message); + + if (receipt.command !== EXECUTOR_SPLIT_COMMAND) fail(`command is ${receipt.command}`); + if ( + !Array.isArray(receipt.candidateIds) || + !receipt.candidateIds.includes(EXECUTOR_SPLIT_EXECUTOR_MODEL) + ) + fail('candidateIds does not name the executor under test'); + if (receipt.constantSha256 !== sha256(EXECUTOR_SPLIT_EXECUTOR_MODEL)) + fail('constantSha256 does not match the executor constant'); + if (!testedCommit || receipt.testedCommit !== testedCommit) + fail(`testedCommit is ${receipt.testedCommit ?? null}`); + if (!testedCommit || receipt.buildIdentity?.commitSha !== testedCommit) + fail(`buildIdentity.commitSha is ${receipt.buildIdentity?.commitSha ?? null}`); + if (typeof receipt.startedAt !== 'string' || Number.isNaN(Date.parse(receipt.startedAt))) + fail('startedAt is not a timestamp'); + if (!receipt.environment || typeof receipt.environment !== 'object') + fail('environment is missing'); + + const routing = receipt.routing ?? {}; + if (routing.reason !== 'split_premium_planner_bulk_copy') + fail(`routing.reason is ${routing.reason}`); + if (routing.plannerModel !== EXECUTOR_SPLIT_PLANNER_MODEL) + fail(`routing.plannerModel is ${routing.plannerModel}`); + if (routing.executorModel !== EXECUTOR_SPLIT_EXECUTOR_MODEL) + fail(`routing.executorModel is ${routing.executorModel}`); + if (routing.executorOutcome !== 'applied') + fail(`routing.executorOutcome is ${routing.executorOutcome}`); + + const spans = Array.isArray(receipt.spans) ? receipt.spans : []; + const rows = Array.isArray(receipt.rows) ? receipt.rows : []; + const expected = [ + ['planner', EXECUTOR_SPLIT_PLANNER_MODEL], + ['executor', EXECUTOR_SPLIT_EXECUTOR_MODEL], + ]; + const microUsd = (usd) => Math.round(usd * 1_000_000); + const isCount = (value) => Number.isFinite(value) && value >= 0; + for (const [toolName, model] of expected) { + const span = spans.find((entry) => entry?.toolName === toolName); + const row = rows.find((entry) => entry?.toolName === toolName); + if (!span) fail(`no ${toolName} span`); + else { + if (span.spanModel !== model) fail(`${toolName} spanModel is ${span.spanModel}`); + if (span.responseModel !== model) fail(`${toolName} responseModel is ${span.responseModel}`); + const { inputTokens, outputTokens } = span.usage ?? {}; + if (!(inputTokens > 0 || outputTokens > 0)) fail(`${toolName} usage is zero`); + } + if (!row) fail(`no ${toolName} row`); + else { + if (row.requestedModel !== model) + fail(`${toolName} row requestedModel is ${row.requestedModel}`); + if (row.resolvedModel !== row.requestedModel) + fail(`${toolName} row resolvedModel ${row.resolvedModel} differs from requestedModel`); + if (row.echoedModel !== model) fail(`${toolName} row echoedModel is ${row.echoedModel}`); + if (row.fallbackUsed !== false) fail(`${toolName} row used a fallback`); + if (span && row.echoedModel !== span.responseModel) fail(`${toolName} row and span disagree`); + // The row is the accounting line for the span: its usage, cost and call count must be present + // and must reconcile with the span, otherwise a row stripped of them would pass unseen. + const rowUsage = row.usage ?? {}; + if (!(isCount(rowUsage.inputTokens) && isCount(rowUsage.outputTokens))) + fail(`${toolName} row usage is missing`); + else if (!(rowUsage.inputTokens > 0 || rowUsage.outputTokens > 0)) + fail(`${toolName} row usage is zero`); + if (!isCount(row.costUsd)) fail(`${toolName} row costUsd is missing`); + if (row.dispatches !== 1) + fail(`${toolName} row dispatched ${row.dispatches ?? null} times, not exactly once`); + if (span) { + if (row.requestedModel !== span.spanModel) + fail(`${toolName} row requestedModel and span spanModel disagree`); + if ( + rowUsage.inputTokens !== span.usage?.inputTokens || + rowUsage.outputTokens !== span.usage?.outputTokens + ) + fail(`${toolName} row usage and span usage disagree`); + if (!isCount(span.costMicroUsd) || microUsd(row.costUsd) !== span.costMicroUsd) + fail(`${toolName} row costUsd and span costMicroUsd disagree`); + } + } + } + const toolNames = (entries) => + entries + .map((entry) => entry?.toolName) + .sort() + .join(','); + if (toolNames(spans) !== 'executor,planner' || toolNames(rows) !== 'executor,planner') + fail('spans and rows are not exactly one planner and one executor'); + if (spans.length !== expected.length || rows.length !== expected.length) + fail(`receipt has ${spans.length} spans and ${rows.length} rows, not ${expected.length}`); + const echoed = [...new Set(rows.map((row) => row?.echoedModel).filter(Boolean))].sort(); + const reported = Array.isArray(receipt.echoedModels) ? [...receipt.echoedModels].sort() : []; + if (JSON.stringify(echoed) !== JSON.stringify(reported)) + fail('echoedModels does not list the models the rows echoed'); + if (!reported.includes(EXECUTOR_SPLIT_EXECUTOR_MODEL)) + fail('echoedModels does not include the executor'); + + // A.0.3: `dispatchPolicy` absent or not {maxRetries: 0, crossModelFallback: false} is rejected, and + // so is a request count above the pre-flight ceiling. The policy is the one the probe enforced + // (retries are switched off in the provider call); each row separately must show one dispatch. + const policy = receipt.dispatchPolicy; + if (!policy || policy.maxRetries !== 0 || policy.crossModelFallback !== false) + fail( + `dispatchPolicy is ${JSON.stringify(policy ?? null)}, not maxRetries 0 and no cross-model fallback`, + ); + const dispatches = rows.reduce( + (total, row) => total + (Number.isInteger(row?.dispatches) ? row.dispatches : 0), + 0, + ); + + // `budget` is the ledger's accounting for the probe: what it authorized, what it settled, and + // whether it refused anything. + const budget = receipt.budget; + if (!budget) fail('budget is missing'); + else { + if (!(Number.isFinite(budget.maxUsd) && budget.maxUsd > 0)) + fail('budget.maxUsd is not a positive number'); + if (!(Number.isFinite(budget.estimateUsd) && budget.estimateUsd > 0)) + fail('budget.estimateUsd shows no reservation'); + else if ( + Number.isFinite(budget.maxUsd) && + microUsd(budget.estimateUsd) > microUsd(budget.maxUsd) + ) + fail('budget.estimateUsd exceeds budget.maxUsd'); + if (!(Number.isFinite(budget.spentUsd) && budget.spentUsd > 0)) + fail('budget.spentUsd shows no spend'); + else { + if (budget.spentUsd > budget.maxUsd) fail('budget.spentUsd exceeds budget.maxUsd'); + // The ledger settles the larger of the provider's cost and a token-based recomputation, so it + // can exceed the rows, never undercut them. + const spansMicroUsd = spans.reduce((total, span) => total + (span?.costMicroUsd ?? 0), 0); + const rowsMicroUsd = rows.reduce( + (total, row) => total + (isCount(row?.costUsd) ? microUsd(row.costUsd) : 0), + 0, + ); + const spentMicroUsd = microUsd(budget.spentUsd); + if (spentMicroUsd < Math.max(spansMicroUsd, rowsMicroUsd)) + fail('budget.spentUsd is below the cost the rows report'); + // A reservation quote is the worst case the ledger authorized for a call, so settled spend + // above the summed quotes means the books and the reservations do not reconcile. + if (Number.isFinite(budget.estimateUsd) && spentMicroUsd > microUsd(budget.estimateUsd)) + fail('budget.spentUsd exceeds budget.estimateUsd'); + } + if (budget.requests !== dispatches) + fail(`budget.requests is ${budget.requests}, rows dispatched ${dispatches}`); + if (budget.requests !== EXECUTOR_SPLIT_MAX_REQUESTS) + fail( + `budget.requests is ${budget.requests}, not the ${EXECUTOR_SPLIT_MAX_REQUESTS} one planner and one executor request make`, + ); + if (!(budget.requests <= EXECUTOR_SPLIT_MAX_REQUESTS)) + fail( + `budget.requests is ${budget.requests}, above the pre-flight ceiling of ${EXECUTOR_SPLIT_MAX_REQUESTS}`, + ); + if (budget.stoppedBy !== null) fail(`budget.stoppedBy is ${budget.stoppedBy}`); + if (!Array.isArray(budget.refusals) || budget.refusals.length > 0) + fail('the budget refused a dispatch or the refusal list is missing'); + } + return failures; +} + +function sha256(text) { + return `sha256:${createHash('sha256').update(text).digest('hex')}`; +} diff --git a/scripts/lib/node-gym-config-core.mjs b/scripts/lib/node-gym-config-core.mjs index 370ac60e..e2132874 100644 --- a/scripts/lib/node-gym-config-core.mjs +++ b/scripts/lib/node-gym-config-core.mjs @@ -69,6 +69,10 @@ export function validateNodeGymConfig(value) { failures.push(`${model.id} must record the returned model.`); if (model.cohort === 'pinned-free' && !model.route.endsWith(':free')) failures.push(`${model.id} is not a pinned free route.`); + if (model.execution !== undefined) { + const reason = nodeGymExecutionShapeFailure(model.execution); + if (reason) failures.push(`${model?.id ?? ''} execution is invalid: ${reason}.`); + } } const harnesses = Array.isArray(value?.harnesses) ? value.harnesses : []; @@ -92,6 +96,63 @@ export function validateNodeGymConfig(value) { return { failures: [...new Set(failures)], matrixSize }; } +const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/u; + +/** + * `model.execution` is the one switch that stops a model from being run without removing its row + * (its `runId`, `comparisonKey` and `harnessPairingKey` key on `model.id`, so deleting the row would + * renumber the benchmark's identity). It accepts exactly `{ disabled: true, since, reason }`. + */ +function nodeGymExecutionShapeFailure(execution) { + if (!execution || typeof execution !== 'object' || Array.isArray(execution)) + return 'expected an object'; + const keys = Object.keys(execution).sort().join(','); + if (keys !== 'disabled,reason,since') return 'only disabled, since and reason are allowed'; + if (execution.disabled !== true) return 'disabled must be true'; + if (typeof execution.since !== 'string' || !ISO_DATE.test(execution.since)) + return 'since must be an ISO date (YYYY-MM-DD)'; + // Date.parse normalizes 2026-02-30 to 2026-03-02, so require the exact UTC round-trip. + const parsed = new Date(`${execution.since}T00:00:00Z`); + if (Number.isNaN(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== execution.since) + return 'since is not a real date'; + if (typeof execution.reason !== 'string' || !execution.reason.trim()) + return 'reason must be a non-empty string'; + return null; +} + +/** + * Splits matrix runs into those the runner may execute and those whose model row is disabled. + * Runs before runtime filtering and subset selection (`selectNodeGymSubset` derives its model list + * from the runs it receives, so a disabled model then yields no pair). A model named explicitly + * while disabled is an error, never a silent empty match. + */ +export function partitionDisabledNodeGymRuns({ runs, includeDisabled, requestedModels = [] }) { + const isDisabled = (run) => run.model?.execution?.disabled === true; + if (includeDisabled) return { runnable: [...runs], skippedDisabled: [] }; + for (const modelId of requestedModels) { + const run = runs.find((candidate) => candidate.model.id === modelId && isDisabled(candidate)); + if (run) { + const { since, reason } = run.model.execution; + throw new Error( + `Model ${modelId} is disabled since ${since}: ${reason}; pass --include-disabled to run it.`, + ); + } + } + const runnable = []; + const skippedDisabled = []; + for (const run of runs) { + if (isDisabled(run)) { + skippedDisabled.push({ + runId: run.runId, + modelId: run.model.id, + since: run.model.execution.since, + reason: run.model.execution.reason, + }); + } else runnable.push(run); + } + return { runnable, skippedDisabled }; +} + export function buildNodeGymMatrixInput(config) { return { tasks: config.tasks.map((task) => ({ diff --git a/scripts/lib/node-gym-runner-core.mjs b/scripts/lib/node-gym-runner-core.mjs index 4b50b4ad..c53a517b 100644 --- a/scripts/lib/node-gym-runner-core.mjs +++ b/scripts/lib/node-gym-runner-core.mjs @@ -1,5 +1,15 @@ import { createHash, randomUUID } from 'node:crypto'; -import { link, lstat, mkdir, realpath, rename, rm, writeFile } from 'node:fs/promises'; +import { + link, + lstat, + mkdir, + readFile, + readdir, + realpath, + rename, + rm, + writeFile, +} from 'node:fs/promises'; import path from 'node:path'; import { validateNodeGymConfig } from './node-gym-config-core.mjs'; @@ -85,7 +95,13 @@ export function assertNodeGymMatrixBoundToConfig({ configBytes, config, matrix, * Validates and accounts every immutable attempt receipt for one bound run. * Costs and failures are returned once for campaign-wide pre-scheduling sums. */ -export function summarizeNodeGymAttemptHistory({ plan, receipts, executor }) { +export function summarizeNodeGymAttemptHistory({ + plan, + receipts, + executor, + reservationMicroUsd = nodeGymRunReservationMicroUsd(plan), + orphanCharges = [], +}) { if (!plan?.runId) throw new Error('NodeGym history requires a bound run plan.'); if (!Array.isArray(receipts)) throw new Error(`NodeGym attempt history is invalid for ${plan.runId}.`); @@ -94,6 +110,7 @@ export function summarizeNodeGymAttemptHistory({ plan, receipts, executor }) { ); const planDigest = digestJson(plan); let spentCostMicroUsd = 0; + let reservedUnknownMicroUsd = 0; let failures = 0; let passedReceipt = null; @@ -125,9 +142,14 @@ export function summarizeNodeGymAttemptHistory({ plan, receipts, executor }) { if (nonNegativeNumber(receipt.usage?.[field]) === null) throw new Error(`${prefix} has invalid ${field} usage.`); } - const cost = Number(receipt.usage?.costMicroUsd); - if (!Number.isSafeInteger(cost) || cost < 0) + const usageCost = Number(receipt.usage?.costMicroUsd); + if (!Number.isSafeInteger(usageCost) || usageCost < 0) throw new Error(`${prefix} has invalid costMicroUsd usage.`); + // The campaign meter is the recorded charge, never the executor's own usage figure. A receipt + // written before charges were recorded has no `budget` and is charged the run's full reservation. + const charge = nodeGymReceiptCharge(receipt, reservationMicroUsd, prefix); + const cost = charge.chargedMicroUsd; + if (charge.source === 'reservation') reservedUnknownMicroUsd += cost; if (receipt.status === 'passed') { if ( receipt.automatedHardGatesPassed !== true || @@ -147,9 +169,19 @@ export function summarizeNodeGymAttemptHistory({ plan, receipts, executor }) { if (receipt.status !== 'passed') failures += 1; } + // An attempt directory found without its receipt (the runner itself died mid-attempt) was charged + // its reservation when it was set aside; those durable charges belong to the run's spend. + for (const orphan of orphanCharges) { + spentCostMicroUsd += orphan.budget.chargedMicroUsd; + reservedUnknownMicroUsd += orphan.budget.chargedMicroUsd; + } + if (!Number.isSafeInteger(spentCostMicroUsd)) + throw new Error(`NodeGym cumulative cost is unsafe for ${plan.runId}.`); + return { receipts: ordered, spentCostMicroUsd, + reservedUnknownMicroUsd, failures, latestAttempt: ordered.length, latestReceipt: ordered.at(-1) ?? null, @@ -507,6 +539,208 @@ export function validateNodeGymExecutorResult(plan, result, options = {}) { }; } +/** + * The most a single gym run can cost the backend ledger, in micro-USD. This is the per-run hard cap + * the production backend binds to every run it meters (`normalizeNodeSlideRunBudget({})` -> + * `maxCostMicroUsd`, `shared/nodeslideRunBudget.ts`), mirrored here because this module runs under + * plain `node`, which cannot load that TypeScript. `scripts/tests/node-gym-campaign-budget.test.mjs` + * fails when the two differ. + */ +export const NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD = 1_000_000; +export const NODE_GYM_LEDGER_RECEIPT_VERSION = 'nodeslide.run-budget-ledger-receipt/v1'; +export const NODE_GYM_ORPHAN_CHARGE_SCHEMA = 'nodekit.gym-orphan-attempt-charge/v1'; + +/** + * What one run reserves against the campaign before it is dispatched: the backend ledger cap that + * binds it, not the gym plan's own `budget.maxCostMicroUsd` (which the UI executor never hands to the + * backend). It takes no override: a reservation below the enforced cap would let a campaign dispatch + * paid work it has not budgeted for. Local, `:free` and `openrouter/free` routes issue no metered + * request and reserve 0. + */ +export function nodeGymRunReservationMicroUsd(plan) { + const model = plan?.model; + if ( + model?.provider === 'local' || + model?.route === 'openrouter/free' || + String(model?.route ?? '').endsWith(':free') + ) + return 0; + return NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD; +} + +/** + * Micro-USD one backend ledger receipt (`nodeslideBudgets.receiptForRun`) says a run cost. Only a + * finalized ledger row is a final figure: a row still `open` belongs to a job that may be running + * (a UI timeout does not stop it), so its counters are a floor, not the cost. Exposure that is + * reserved or unreconciled (a dispatch whose outcome never came back) counts: it may still have been + * billed. Returns null when the receipt is not a readable, finalized ledger receipt; the caller then + * keeps the run's full reservation. + */ +export function nodeGymLedgerReceiptMicroUsd(receipt) { + if (receipt?.version !== NODE_GYM_LEDGER_RECEIPT_VERSION) return null; + if (receipt.status !== 'finalized') return null; + const spend = receipt.spend; + const parts = [spend?.actualMicroUsd, spend?.reservedMicroUsd, spend?.unreconciledMicroUsd]; + if (!parts.every((part) => Number.isSafeInteger(part) && part >= 0)) return null; + const total = parts[0] + parts[1] + parts[2]; + return Number.isSafeInteger(total) ? total : null; +} + +/** + * Combines the ledger receipts of every backend run one gym attempt caused. Any run that is named but + * unreadable (or no run named at all) makes the whole attempt's usage unknown: returns null. + */ +export function combineNodeGymLedgerReceipts(backendRunIds, receiptsByRunId) { + if (!Array.isArray(backendRunIds) || backendRunIds.length === 0) return null; + let total = 0; + for (const runId of new Set(backendRunIds)) { + const charged = nodeGymLedgerReceiptMicroUsd(receiptsByRunId?.get?.(runId) ?? null); + if (charged === null) return null; + total += charged; + } + return Number.isSafeInteger(total) ? { chargedMicroUsd: total } : null; +} + +/** + * The one charge rule for a finished run. A readable backend ledger receipt is the charge. Anything + * else — a crash, a timeout, a failure result, a missing or invalid result, no backend run ids, an + * unreadable receipt — keeps the run's full reservation: an unknown spend is never a zero. + */ +export function nodeGymRunCharge({ reservationMicroUsd, ledgerReceipt }) { + if (!Number.isSafeInteger(reservationMicroUsd) || reservationMicroUsd < 0) + throw new Error('NodeGym run charge requires a non-negative integer reservation.'); + const ledger = ledgerReceipt?.chargedMicroUsd; + if (Number.isSafeInteger(ledger) && ledger >= 0) + return { chargedMicroUsd: ledger, source: 'ledger' }; + return { chargedMicroUsd: reservationMicroUsd, source: 'reservation' }; +} + +/** + * Charges one finished attempt. The backend ledger is the meter: a completed executor result names + * the backend runs it caused (`backendRunIds`) and `readLedger(ids)` resolves their ledger receipts + * (Map of run id -> receipt). A crash, timeout, missing or invalid result, no run ids or any + * unreadable receipt keeps the full reservation; a failure result is charged the ledger only when it + * names the backend runs the executor had already started. The executor's own `usage.costMicroUsd` and + * the Trace inspector text are attribution and never reach this function. + */ +export async function chargeNodeGymAttempt({ reservationMicroUsd, result, readLedger }) { + const ids = result?.backendRunIds; + const named = + Array.isArray(ids) && + ids.length > 0 && + ids.length <= 64 && + ids.every((id) => typeof id === 'string' && id.length > 0 && id.length <= 512); + let ledgerReceipt = null; + if (reservationMicroUsd > 0 && named) { + try { + ledgerReceipt = combineNodeGymLedgerReceipts(ids, await readLedger(ids)); + } catch { + ledgerReceipt = null; + } + } + return nodeGymRunCharge({ reservationMicroUsd, ledgerReceipt }); +} + +/** The charge a stored attempt receipt carries; a receipt from before charges were recorded owes the reservation. */ +export function nodeGymReceiptCharge(receipt, reservationMicroUsd, label = 'NodeGym receipt') { + const budget = receipt?.budget; + if (budget === undefined) return { chargedMicroUsd: reservationMicroUsd, source: 'reservation' }; + if ( + !budget || + !Number.isSafeInteger(budget.chargedMicroUsd) || + budget.chargedMicroUsd < 0 || + !['ledger', 'reservation'].includes(budget.source) + ) + throw new Error(`${label} has an invalid budget charge.`); + return { chargedMicroUsd: budget.chargedMicroUsd, source: budget.source }; +} + +/** Durable record for an attempt directory that never produced a receipt: it is charged its reservation. */ +export function nodeGymOrphanAttemptCharge({ runId, attempt, reservationMicroUsd }) { + return { + schemaVersion: NODE_GYM_ORPHAN_CHARGE_SCHEMA, + runId, + attempt, + budget: { chargedMicroUsd: reservationMicroUsd, source: 'reservation' }, + }; +} + +export function assertNodeGymOrphanCharge(value, runId, label = 'NodeGym orphan charge') { + if ( + value?.schemaVersion !== NODE_GYM_ORPHAN_CHARGE_SCHEMA || + value.runId !== runId || + !Number.isSafeInteger(value.attempt) || + value.attempt < 1 || + value.budget?.source !== 'reservation' || + !Number.isSafeInteger(value.budget?.chargedMicroUsd) || + value.budget.chargedMicroUsd < 0 + ) + throw new Error(`${label} is invalid for ${runId}.`); + return value; +} + +const ORPHAN_ATTEMPT_DIR = /^orphaned-attempt-(\d{3,})-(\d+)$/u; +const ORPHAN_CHARGE_FILE = /^orphaned-attempt-(\d{3,})-(\d+)\.charge\.json$/u; + +/** + * The runner itself died mid-attempt: `attempts/attempt-NNN/` exists but no `attempt-NNN.json` + * receipt was ever written, so what that attempt spent is unknown. Each such directory is charged the + * run's full reservation, durably, and set aside so the attempt number can be re-issued. The charge + * file is written first (a crash between the two steps over-charges once, never under-charges) and + * a pending charge whose directory has not been renamed yet is reused, so a repeated resume does not + * charge the same directory twice. + */ +export async function setAsideNodeGymOrphanAttempts({ + campaignRoot, + attemptsDir, + runId, + orphanAttempts, + reservationMicroUsd, +}) { + for (const attempt of [...orphanAttempts].sort((left, right) => left - right)) { + const stem = String(attempt).padStart(3, '0'); + const names = await readdir(attemptsDir); + const pending = names + .map((name) => ORPHAN_CHARGE_FILE.exec(name)) + .filter((match) => match && match[1] === stem) + .map((match) => Number(match[2])) + .find((k) => !names.includes(`orphaned-attempt-${stem}-${k}`)); + const used = names + .flatMap((name) => [ORPHAN_CHARGE_FILE.exec(name), ORPHAN_ATTEMPT_DIR.exec(name)]) + .filter((match) => match && match[1] === stem) + .map((match) => Number(match[2])); + const k = pending ?? Math.max(0, ...used) + 1; + const chargePath = path.join(attemptsDir, `orphaned-attempt-${stem}-${k}.charge.json`); + if (pending === undefined) { + const charge = nodeGymOrphanAttemptCharge({ runId, attempt, reservationMicroUsd }); + await writeNodeGymFileAtomic( + campaignRoot, + chargePath, + `${JSON.stringify(charge, null, 2)}\n`, + { + exclusive: true, + label: 'orphaned attempt charge', + }, + ); + } + await rename( + path.join(attemptsDir, `attempt-${stem}`), + path.join(attemptsDir, `orphaned-attempt-${stem}-${k}`), + ); + } +} + +/** Every durable orphan charge recorded for one run, validated. */ +export async function loadNodeGymOrphanCharges({ attemptsDir, runId }) { + const charges = []; + for (const name of await readdir(attemptsDir)) { + if (!ORPHAN_CHARGE_FILE.test(name)) continue; + const raw = JSON.parse(await readFile(path.join(attemptsDir, name), 'utf8')); + charges.push(assertNodeGymOrphanCharge(raw, runId, `NodeGym orphan charge ${name}`)); + } + return charges; +} + export function shouldStopCampaign(input) { // Equality is allowed so zero-cost controls/free routes can run under a zero // aggregate cap. Any positive metered cost then trips the next boundary. @@ -682,3 +916,37 @@ function comparisonKeyFromPlan(plan) { ].join(':'), ].join('::'); } + +/** + * Tracks the one executor child a campaign has running so the campaign lock is never released while + * it lives. On POSIX a child outlives a parent that exits, so a signal that only reached the parent + * used to free `campaign.lock` while the executor kept writing its attempt workspace; the next launch + * then took the lock, treated that live workspace as an orphan, set it aside and re-issued the same + * attempt path. `stop()` signals the child and resolves only once it has closed, escalating to + * SIGKILL after `graceMs`; `killNow()` is the synchronous last resort for an exit path. + */ +export function createNodeGymChildGuard({ graceMs = 10_000 } = {}) { + let active = null; + return { + track(child) { + active = child; + const clear = () => { + if (active === child) active = null; + }; + child.once('close', clear); + child.once('error', clear); + }, + async stop() { + const child = active; + if (!child) return; + const closed = new Promise((resolve) => child.once('close', resolve)); + child.kill(); + const escalate = setTimeout(() => child.kill('SIGKILL'), graceMs); + await closed; + clearTimeout(escalate); + }, + killNow() { + active?.kill('SIGKILL'); + }, + }; +} diff --git a/scripts/lib/node-gym-selection-core.mjs b/scripts/lib/node-gym-selection-core.mjs new file mode 100644 index 00000000..a7a0090b --- /dev/null +++ b/scripts/lib/node-gym-selection-core.mjs @@ -0,0 +1,46 @@ +import { partitionDisabledNodeGymRuns } from './node-gym-config-core.mjs'; +import { applyPairSafeLimit, selectNodeGymSubset } from './node-gym-runner-core.mjs'; +import { filterNodeGymRunsForRuntime } from './node-gym-task-core.mjs'; + +/** + * Which matrix runs a campaign executes. The order is load-bearing: explicit filters first, then the + * disabled-model partition, and only THEN runtime filtering and subset selection, because + * `selectNodeGymSubset` derives its model list from the runs it receives, so a disabled model that + * is partitioned out first yields no pair and `--subset all` drops exactly its runs. + */ +export function selectNodeGymCampaignRuns({ + matrix, + config, + filters, + subset, + limit = Number.POSITIVE_INFINITY, + includeDisabled = false, + runtime = process.env, +}) { + const explicitlyFilteredRuns = matrix.runs.filter( + (run) => + (!filters.tasks.length || filters.tasks.includes(run.task.id)) && + (!filters.models.length || filters.models.includes(run.model.id)) && + (!filters.harnesses.length || filters.harnesses.includes(run.harness.id)) && + (!filters.repetitions.length || filters.repetitions.includes(run.repetition)), + ); + const { runnable, skippedDisabled } = partitionDisabledNodeGymRuns({ + runs: explicitlyFilteredRuns, + includeDisabled, + requestedModels: filters.models, + }); + const filteredRuns = filterNodeGymRunsForRuntime({ + runs: runnable, + tasks: config.tasks, + runtime, + explicitTaskIds: filters.tasks, + }); + if (!filteredRuns.length) throw new Error('Explicit NodeGym selection matched no matrix runs.'); + return { + selectedRuns: applyPairSafeLimit( + selectNodeGymSubset({ ...matrix, runs: filteredRuns }, subset), + limit, + ), + skippedDisabled, + }; +} diff --git a/scripts/lib/nodeslide-backend-runs.mjs b/scripts/lib/nodeslide-backend-runs.mjs new file mode 100644 index 00000000..66a7046c --- /dev/null +++ b/scripts/lib/nodeslide-backend-runs.mjs @@ -0,0 +1,80 @@ +/** + * Which backend runs did one browser session cause, and what did the budget ledger charge for them? + * + * The campaign runners (`run-deck-gym.mjs`, `run-node-gym.mjs` via the UI executor) drive the + * production site in a fresh browser context per run, so every backend job in that context's client + * session belongs to that run. The ledger (`nodeslideBudgets.receiptForRun`) is the meter; this + * module only finds the run ids and reads the receipts. It never reads cost from the Trace inspector. + */ + +export const NODESLIDE_SESSION_ID_STORAGE_KEY = 'parity.studio.sessionId'; +const MAX_BACKEND_RUN_IDS = 64; + +export function productionConvexUrl(value) { + const url = new URL(value); + if ( + url.protocol !== 'https:' || + url.username || + url.password || + url.hash || + !url.hostname.endsWith('.convex.cloud') + ) + throw new Error('Convex URL must be a clean production Convex HTTPS URL.'); + return url; +} + +/** The two Convex reads the runners need, bound to a production deployment. */ +export async function createNodeSlideBackendClient(convexUrl) { + const [{ ConvexHttpClient }, { api }] = await Promise.all([ + import('convex/browser'), + import('../../convex/_generated/api.js'), + ]); + const client = new ConvexHttpClient(productionConvexUrl(convexUrl).origin); + return { + listSessionJobs: (clientSessionId) => + client.query(api.nodeslideJobs.listSessionJobs, { clientSessionId }), + receiptForRun: (runId) => client.query(api.nodeslideBudgets.receiptForRun, { runId }), + }; +} + +/** + * Backend run ids (job ids) the page's client session caused. Returns [] when the session id cannot + * be read or the list cannot be fetched: the caller then treats usage as unknown and keeps the + * run's full reservation. + */ +export async function readBackendRunIds({ page, backend }) { + try { + const clientSessionId = await page.evaluate((key) => { + try { + return window.localStorage.getItem(key) ?? window.sessionStorage.getItem(key) ?? ''; + } catch { + return ''; + } + }, NODESLIDE_SESSION_ID_STORAGE_KEY); + if (typeof clientSessionId !== 'string' || !clientSessionId) return []; + const jobs = await backend.listSessionJobs(clientSessionId); + if (!Array.isArray(jobs)) return []; + return [ + ...new Set( + jobs + .map((job) => job?.jobId) + .filter((jobId) => typeof jobId === 'string' && jobId.length > 0 && jobId.length <= 512), + ), + ].slice(0, MAX_BACKEND_RUN_IDS); + } catch { + return []; + } +} + +/** Ledger receipts keyed by run id; a read that fails or finds no row is stored as null (unknown). */ +export async function readLedgerReceipts({ backend, runIds }) { + const receipts = new Map(); + for (const runId of runIds ?? []) { + try { + receipts.set(runId, (await backend.receiptForRun(runId)) ?? null); + } catch { + receipts.set(runId, null); + } + } + return receipts; +} diff --git a/scripts/node-gym-runner-core.test.mjs b/scripts/node-gym-runner-core.test.mjs index bc1b3e73..552b8136 100644 --- a/scripts/node-gym-runner-core.test.mjs +++ b/scripts/node-gym-runner-core.test.mjs @@ -125,6 +125,10 @@ function immutableReceipt(plan, attempt, status, costMicroUsd) { automatedHardGatesPassed: status === 'passed', issueCodes: status === 'passed' ? [] : ['provider_error'], usage: { ...passed.usage, costMicroUsd }, + // Receipts now record what the campaign was charged (backend ledger figure); the figures these + // tests assert are unchanged. A receipt without `budget` is covered in + // scripts/tests/node-gym-campaign-budget.test.mjs. + budget: { chargedMicroUsd: costMicroUsd, source: 'ledger' }, attempt, recordedAt: `2026-07-22T00:00:0${attempt}.000Z`, }; diff --git a/scripts/node-gym-ui-executor.mjs b/scripts/node-gym-ui-executor.mjs index 2aac170c..8be3f4be 100644 --- a/scripts/node-gym-ui-executor.mjs +++ b/scripts/node-gym-ui-executor.mjs @@ -24,6 +24,7 @@ import { } from './lib/node-gym-task-core.mjs'; import { buildNodeGymUiEvidenceEnvelope } from './lib/node-gym-ui-evidence-core.mjs'; import { sanitizeNodeGymArtifactShadowReceipt } from './lib/node-gym-ui-shadow-core.mjs'; +import { createNodeSlideBackendClient, readBackendRunIds } from './lib/nodeslide-backend-runs.mjs'; import { cleanupNodeSlideProductionFixture, productionFixtureCleanupDisposition, @@ -55,6 +56,7 @@ let capturedTrace = null; let createdDeckId = ''; let ownerAccessKey = ''; let creationSubmitted = false; +let backendRunIds = []; let uiEvidenceInput = null; try { if (plan.model.provider === 'local') throw new Error('UI executor does not accept local models.'); @@ -140,6 +142,12 @@ try { await page.screenshot({ path: browserPath, fullPage: true }); const trace = await captureTrace(page, plan.model.route); capturedTrace = trace; + // The backend runs this browser session caused. The runner (not this executor) reads their + // budget-ledger receipts to charge the campaign; a failure result deliberately omits them. + backendRunIds = await readBackendRunIds({ + page, + backend: await createNodeSlideBackendClient(convexUrl.href), + }).catch(() => []); await writeFile(path.join(runDir, 'trace.json'), `${JSON.stringify(trace, null, 2)}\n`, { mode: 0o600, }); @@ -283,6 +291,7 @@ try { runId: plan.runId, pairingKey: plan.pairingKey, status: 'completed', + backendRunIds, route: { mode: routeMode, requestedRoute: plan.model.route, @@ -336,6 +345,14 @@ try { }; } } catch (error) { + if (creationSubmitted && page && backendRunIds.length === 0) { + // Creation was submitted before the failure: name the backend runs it started so the runner + // charges the ledger's figure instead of the whole reservation. + backendRunIds = await readBackendRunIds({ + page, + backend: await createNodeSlideBackendClient(convexUrl.href), + }).catch(() => []); + } result = failureResult( exportTimedOut ? 'artifact-failure' : 'failed', [exportTimedOut ? 'pptx_export_timeout' : 'ui_executor_failed'], @@ -411,6 +428,7 @@ function failureResult(status, issueCodes, failure = null) { costMicroUsd: 0, repairCount: 0, }, + ...(backendRunIds.length ? { backendRunIds } : {}), artifacts: {}, diagnostics: { estimatedTextOverflowCount: 0, diff --git a/scripts/run-deck-gym.mjs b/scripts/run-deck-gym.mjs index 04facfe2..b34fc93b 100644 --- a/scripts/run-deck-gym.mjs +++ b/scripts/run-deck-gym.mjs @@ -3,23 +3,60 @@ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'; import path from 'node:path'; import process from 'node:process'; import { chromium } from 'playwright'; +import { + acquireDeckGymCampaignLock, + assertUniqueDeckGymRunIds, + createDeckGymCampaignBudget, + deckGymBudgetSummary, + deckGymWorker, + recordDeckGymCharge, + recordDeckGymReservation, + resolveDeckGymMaxTotalCostMicroUsd, + restoreDeckGymSpend, +} from './lib/deck-gym-campaign.mjs'; +import { + createNodeSlideBackendClient, + readBackendRunIds, + readLedgerReceipts, +} from './lib/nodeslide-backend-runs.mjs'; const matrixPath = path.resolve(option('matrix') ?? 'artifacts/deck-gym/deck-gym-v1/matrix.json'); const runsDir = path.resolve(option('runs-dir') ?? path.join(path.dirname(matrixPath), 'runs')); const baseUrl = productionUrl(option('url') ?? 'https://nodeslide.vercel.app/'); const requestedConcurrency = positiveInteger(option('concurrency'), 2); const limit = positiveInteger(option('limit'), Number.MAX_SAFE_INTEGER); +const backend = await createNodeSlideBackendClient( + option('convex-url') ?? + process.env.NODE_GYM_PROD_CONVEX_URL ?? + 'https://agile-stoat-411.convex.cloud', +); const resume = !process.argv.includes('--no-resume'); const matrix = JSON.parse(await readFile(matrixPath, 'utf8')); if (matrix?.schemaVersion !== 'nodeslide.deck-gym-matrix/v1' || !Array.isArray(matrix.runs)) { throw new Error('Deck Gym matrix is invalid.'); } +assertUniqueDeckGymRunIds(matrix.runs); const maxConcurrency = Math.max( 1, Math.min(requestedConcurrency, Number(matrix.runs[0]?.budgets?.maxConcurrency ?? 1)), ); const runs = matrix.runs.slice(0, limit); await mkdir(runsDir, { recursive: true }); +// Held until exit, before spend is restored: see acquireDeckGymCampaignLock. A signal exits through +// process.exit so the 'exit' handler still releases it. +const releaseCampaignLock = acquireDeckGymCampaignLock(runsDir); +process.once('exit', releaseCampaignLock); +for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => process.exit(1)); +// The cap binds the whole campaign, so what earlier invocations already spent counts before any +// run is scheduled, whether those runs resume as skipped or are about to be re-run, and whether or +// not `--limit` selected them this time: restore reads every run directory in `runsDir`. +const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: resolveDeckGymMaxTotalCostMicroUsd({ + explicit: option('max-total-cost-micro-usd'), + limit: option('limit') === undefined ? undefined : limit, + }), + spentCostMicroUsd: await restoreDeckGymSpend({ runsDir }), +}); const browser = await chromium.launch({ headless: true }); const queue = [...runs]; @@ -41,6 +78,7 @@ const summary = { completed: receipts.filter((entry) => entry.status === 'completed').length, failed: receipts.filter((entry) => entry.status === 'failed').length, skipped: receipts.filter((entry) => entry.status === 'skipped').length, + budget: deckGymBudgetSummary(budget), concurrency: maxConcurrency, productionOrigin: baseUrl.origin, receipts, @@ -49,23 +87,36 @@ await writeJson(path.join(path.dirname(runsDir), 'generation-summary.json'), sum console.log( `[deck-gym] generation complete: ${summary.completed} completed, ${summary.failed} failed, ${summary.skipped} skipped`, ); -if (summary.failed) process.exitCode = 1; +if (budget.stoppedBy) { + console.error( + `[deck-gym] campaign stopped by ${budget.stoppedBy}: ${queue.length} run(s) not started (spent ${budget.spentCostMicroUsd} of ${budget.maxTotalCostMicroUsd} micro-USD).`, + ); +} +if (summary.failed || budget.stoppedBy) process.exitCode = 1; -async function worker(workerId) { - while (queue.length) { - const run = queue.shift(); - if (!run) return; - const runDir = path.join(runsDir, run.runId); - const pptxPath = path.join(runDir, 'deck.pptx'); - const existing = await readJson(path.join(runDir, 'run.json')).catch(() => null); - if (resume && (await exists(pptxPath)) && existing?.execution?.status === 'completed') { - receipts.push({ runId: run.runId, status: 'skipped', reason: 'resume_artifact_exists' }); - console.log(`[deck-gym:${workerId}] SKIP ${run.runId}`); - continue; - } - const receipt = await executeRun(workerId, run, runDir); - receipts.push(receipt); - } +function worker(workerId) { + return deckGymWorker({ + queue, + budget, + receipts, + isResumable: async (run) => { + const runDir = path.join(runsDir, run.runId); + const existing = await readJson(path.join(runDir, 'run.json')).catch(() => null); + return ( + resume && + (await exists(path.join(runDir, 'deck.pptx'))) && + existing?.execution?.status === 'completed' + ); + }, + executeRun: (run) => executeRun(workerId, run, path.join(runsDir, run.runId)), + readLedger: (runIds) => readLedgerReceipts({ backend, runIds }), + recordReservation: (run, reservationMicroUsd) => + recordDeckGymReservation(path.join(runsDir, run.runId), reservationMicroUsd), + recordCharge: (run, charge) => recordDeckGymCharge(path.join(runsDir, run.runId), charge), + onSkip: (run) => console.log(`[deck-gym:${workerId}] SKIP ${run.runId}`), + onStop: (issueCode, run) => + console.error(`[deck-gym:${workerId}] STOP before ${run.runId}: ${issueCode}`), + }); } async function executeRun(workerId, run, runDir) { @@ -87,6 +138,7 @@ async function executeRun(workerId, run, runDir) { serviceWorkers: 'block', }); const page = await context.newPage(); + let backendRunIds = []; page.on('pageerror', (error) => runtimeErrors.push(`pageerror: ${safeError(error.message)}`)); page.on('console', (message) => { if (message.type() === 'error') @@ -120,6 +172,7 @@ async function executeRun(workerId, run, runDir) { await page.getByTestId('slide-canvas').waitFor({ timeout: 45_000 }); await page.screenshot({ path: path.join(runDir, 'editor.png'), fullPage: true }); const trace = await captureTrace(page); + backendRunIds = await readBackendRunIds({ page, backend }); await page.getByLabel('Export deck').click(); await page.getByTestId('export-pptx').waitFor({ timeout: 30_000 }); @@ -148,7 +201,12 @@ async function executeRun(workerId, run, runDir) { console.log( `[deck-gym:${workerId}] PASS ${run.runId} (${Math.round(execution.durationMs / 1000)}s; ${trace.classification})`, ); - return { runId: run.runId, status: 'completed', durationMs: execution.durationMs }; + return { + runId: run.runId, + status: 'completed', + durationMs: execution.durationMs, + backendRunIds, + }; } catch (error) { const failure = safeError(error); await page @@ -166,7 +224,9 @@ async function executeRun(workerId, run, runDir) { }, }); console.error(`[deck-gym:${workerId}] FAIL ${run.runId}: ${failure}`); - return { runId: run.runId, status: 'failed', failure }; + // The page may already have started a metered job before it failed; ask the ledger anyway. + if (!backendRunIds.length) backendRunIds = await readBackendRunIds({ page, backend }); + return { runId: run.runId, status: 'failed', failure, backendRunIds }; } finally { await context.close(); } diff --git a/scripts/run-node-gym.mjs b/scripts/run-node-gym.mjs index 303d5f4e..1e30a0db 100644 --- a/scripts/run-node-gym.mjs +++ b/scripts/run-node-gym.mjs @@ -4,6 +4,7 @@ import { createHash } from 'node:crypto'; import { lstat, mkdir, readFile, readdir, stat } from 'node:fs/promises'; import path from 'node:path'; import process from 'node:process'; +import { acquireDeckGymCampaignLock } from './lib/deck-gym-campaign.mjs'; import { buildNodeGymMatrixInput } from './lib/node-gym-config-core.mjs'; import { buildNodeGymPairedDeltaReport, @@ -21,14 +22,20 @@ import { assertNodeGymPassedSemanticEvaluation, assertNodeGymRealPathContained, assertNodeGymSafePathSyntax, + chargeNodeGymAttempt, + createNodeGymChildGuard, digestJson, + loadNodeGymOrphanCharges, nodeGymReceiptArtifactBindings, + nodeGymRunReservationMicroUsd, selectNodeGymSubset, + setAsideNodeGymOrphanAttempts, shouldStopCampaign, summarizeNodeGymAttemptHistory, validateNodeGymExecutorResult, writeNodeGymFileAtomic, } from './lib/node-gym-runner-core.mjs'; +import { selectNodeGymCampaignRuns } from './lib/node-gym-selection-core.mjs'; import { assertNoProtectedFixtureLeakage, bindNodeGymRunPlanToFixture, @@ -38,6 +45,7 @@ import { loadNodeGymTaskFixture, projectNodeGymProtectedFixtureForEgress, } from './lib/node-gym-task-core.mjs'; +import { createNodeSlideBackendClient, readLedgerReceipts } from './lib/nodeslide-backend-runs.mjs'; if (process.argv.includes('--help') || process.argv.includes('-h')) { console.log(`Usage: node scripts/run-node-gym.mjs [options] @@ -55,6 +63,8 @@ Execution: --allow-live Required by the production UI executor --campaign-id --max-total-cost-micro-usd + --convex-url Production Convex deployment the ledger is read from + --include-disabled Run models whose gym.json row sets execution.disabled --max-failures --max-attempts --source-campaign Required by recovery executor @@ -94,24 +104,18 @@ const filters = { harnesses: csvOption('harness'), repetitions: csvOption('repetition').map(Number), }; -const explicitlyFilteredRuns = matrix.runs.filter( - (run) => - (!filters.tasks.length || filters.tasks.includes(run.task.id)) && - (!filters.models.length || filters.models.includes(run.model.id)) && - (!filters.harnesses.length || filters.harnesses.includes(run.harness.id)) && - (!filters.repetitions.length || filters.repetitions.includes(run.repetition)), -); -const filteredRuns = filterNodeGymRunsForRuntime({ - runs: explicitlyFilteredRuns, - tasks: config.tasks, +// A model row marked `execution.disabled` stays in the matrix (its identity keys on model.id) but is +// partitioned out inside the selection, before runtime filtering and subset selection. +const { selectedRuns, skippedDisabled } = selectNodeGymCampaignRuns({ + matrix, + config, + filters, + subset, + limit: positiveInteger(option('limit'), Number.POSITIVE_INFINITY), + includeDisabled: process.argv.includes('--include-disabled'), runtime: process.env, - explicitTaskIds: filters.tasks, }); -if (!filteredRuns.length) throw new Error('Explicit NodeGym selection matched no matrix runs.'); -const selectedEntries = applyPairSafeLimit( - selectNodeGymSubset({ ...matrix, runs: filteredRuns }, subset), - positiveInteger(option('limit'), Number.POSITIVE_INFINITY), -).map((run) => { +const selectedEntries = selectedRuns.map((run) => { const task = config.tasks.find((entry) => entry.id === run.task.id); if (!task) throw new Error(`Matrix task ${run.task.id} is absent from the gym config.`); const loadedFixture = loadNodeGymTaskFixture({ task }); @@ -147,12 +151,34 @@ const maxTotalCostMicroUsd = nonNegativeInteger( ); if (maxTotalCostMicroUsd === null) throw new Error('An explicit --max-total-cost-micro-usd is required for full execution.'); +// A run reserves the backend ledger cap that binds it (1 USD, mirrored in node-gym-runner-core.mjs and +// pinned to the backend by a test). It is not a flag: a reservation below the enforced cap lets the +// campaign dispatch paid work it has not budgeted for. Only local, `:free` and `openrouter/free` +// routes reserve 0, whichever executor runs them. +const reservationFor = (plan) => nodeGymRunReservationMicroUsd(plan); +const convexUrl = + option('convex-url') ?? + process.env.NODE_GYM_PROD_CONVEX_URL ?? + 'https://agile-stoat-411.convex.cloud'; +let backendClient = null; const maxFailures = positiveInteger(option('max-failures'), subset === 'all' ? 6 : 2); const maxAttempts = positiveInteger(option('max-attempts'), 2); await assertNodeGymRealPathContained(root, artifactRoot, 'NodeGym artifact root'); await assertNodeGymRealPathContained(artifactRoot, campaignRoot, 'campaign artifact directory'); await mkdir(campaignRoot, { recursive: true }); await assertNodeGymRealPathContained(artifactRoot, campaignRoot, 'campaign artifact directory'); +// One invocation at a time per campaign directory, held until exit and taken before any attempt +// directory is read: the default campaign id is the same for every launch, and a live attempt has no +// receipt yet, exactly like a dead one, so a second run would set the first run's workspace aside, +// restore its reservation and dispatch past the cap. A signal first stops the running executor and +// waits for it to close, then exits through process.exit so the 'exit' handler releases the lock: on +// POSIX a child outlives its parent, so exiting first would free the lock under a live executor. +const releaseCampaignLock = acquireDeckGymCampaignLock(campaignRoot, 'NodeGym'); +const childGuard = createNodeGymChildGuard(); +process.once('exit', childGuard.killNow); +process.once('exit', releaseCampaignLock); +for (const signal of ['SIGINT', 'SIGTERM']) + process.once(signal, () => void childGuard.stop().finally(() => process.exit(1))); const campaignPlan = { schemaVersion: 'nodekit.gym-campaign-plan/v1', @@ -182,6 +208,7 @@ for (const entry of selectedEntries) assertProtectedOutput(campaignPlan, entry.l await writeImmutableJson(path.join(campaignRoot, 'campaign-plan.json'), campaignPlan); let spentCostMicroUsd = 0; +let reservedUnknownMicroUsd = 0; let failures = 0; const summaryRuns = []; const semanticEvaluations = new Map(); @@ -201,8 +228,15 @@ for (const entry of selectedEntries) { await assertNodeGymRealPathContained(campaignRoot, attemptsDir, 'run artifact directory'); assertProtectedOutput(plan, entry.loadedFixture); await writeImmutableJson(path.join(runDir, 'plan.json'), plan); - const history = await loadNodeGymAttemptHistory({ plan, runDir, attemptsDir, executor }); + const history = await loadNodeGymAttemptHistory({ + plan, + runDir, + attemptsDir, + executor, + reservationMicroUsd: reservationFor(plan), + }); spentCostMicroUsd += history.spentCostMicroUsd; + reservedUnknownMicroUsd += history.reservedUnknownMicroUsd; failures += history.failures; if (!Number.isSafeInteger(spentCostMicroUsd)) throw new Error('NodeGym campaign cumulative cost exceeds the safe integer range.'); @@ -259,7 +293,7 @@ for (const plan of selected) { maxTotalCostMicroUsd, failures, maxFailures, - nextRunMaxCostMicroUsd: projectedRunCostMicroUsd(plan), + nextRunMaxCostMicroUsd: reservationFor(plan), }); if (circuit.stop) { stoppedBy = circuit.issueCode; @@ -308,6 +342,7 @@ for (const plan of selected) { })); const result = await bindArtifacts(rawResult, attemptWorkspace); assertProtectedOutput(result, entry.loadedFixture); + const charge = await chargeAttempt(plan, result); await writeImmutableJson(resultPath, result); const semanticEvaluation = evaluateEvidenceBoundNodeGymRun({ plan, @@ -336,6 +371,9 @@ for (const plan of selected) { semanticEvaluation, }), attempt, + // What this attempt cost the campaign: the backend ledger's figure, or the full reservation + // when that figure could not be read. `usage.costMicroUsd` stays above as attribution only. + budget: charge, attemptEvidence: { schemaVersion: 'nodekit.gym-attempt-evidence/v1', artifactRoot: path.relative(runDir, attemptWorkspace).replaceAll('\\', '/'), @@ -358,7 +396,8 @@ for (const plan of selected) { await writeImmutableJson(attemptPath, receipt); await writeJson(path.join(runDir, 'latest.json'), receipt); attemptReceiptCount += 1; - spentCostMicroUsd += receipt.usage.costMicroUsd; + spentCostMicroUsd += charge.chargedMicroUsd; + if (charge.source === 'reservation') reservedUnknownMicroUsd += charge.chargedMicroUsd; if (receipt.status !== 'passed') failures += 1; summaryRuns.push({ runId: plan.runId, @@ -420,6 +459,14 @@ const summary = { .length, unrun: selected.filter((run) => !completedRunIds.has(run.runId)).map((run) => run.runId), spentCostMicroUsd, + budget: { + maxTotalCostMicroUsd, + spentCostMicroUsd, + reservedUnknownMicroUsd, + stoppedBy, + }, + skippedDisabled, + skippedDisabledCount: skippedDisabled.length, failureAttempts: failures, attemptReceiptCount, historicSpentCostMicroUsd, @@ -548,6 +595,7 @@ async function runProcess(executable, args, timeoutMs, childEnvironment) { env: childEnvironment, stdio: ['ignore', 'pipe', 'pipe'], }); + childGuard.track(child); let stderr = ''; child.stderr.setEncoding('utf8'); child.stderr.on('data', (chunk) => { @@ -620,6 +668,7 @@ async function loadNodeGymAttemptHistory({ runDir, attemptsDir, executor: selectedExecutor, + reservationMicroUsd, }) { const entries = await readdir(attemptsDir, { withFileTypes: true }); const receipts = []; @@ -650,17 +699,31 @@ async function loadNodeGymAttemptHistory({ receipts.push(receipt); } const receiptAttempts = new Set(receipts.map((receipt) => receipt.attempt)); - if ( - workspaceAttempts.size !== receiptAttempts.size || - [...workspaceAttempts].some((attempt) => !receiptAttempts.has(attempt)) - ) + // A receipt without its workspace is corruption. A workspace without its receipt is the runner + // having died mid-attempt: its spend is unknown, so it is charged its reservation and set aside. + if ([...receiptAttempts].some((attempt) => !workspaceAttempts.has(attempt))) throw new Error( `NodeGym immutable attempt workspaces do not match receipts for ${plan.runId}.`, ); + const orphanAttempts = [...workspaceAttempts].filter((attempt) => !receiptAttempts.has(attempt)); + if (orphanAttempts.length) { + await setAsideNodeGymOrphanAttempts({ + campaignRoot, + attemptsDir, + runId: plan.runId, + orphanAttempts, + reservationMicroUsd, + }); + console.warn( + `[node-gym] ${plan.runId}: attempt(s) ${orphanAttempts.join(', ')} had no receipt; charged ${reservationMicroUsd} micro-USD each and set aside`, + ); + } const history = summarizeNodeGymAttemptHistory({ plan, receipts, executor: selectedExecutor, + reservationMicroUsd, + orphanCharges: await loadNodeGymOrphanCharges({ attemptsDir, runId: plan.runId }), }); const latest = await readOptionalJson(path.join(runDir, 'latest.json')); assertNodeGymLatestReceipt(history, latest); @@ -785,14 +848,16 @@ function executorEnvironment(gymConfig, evaluationFixture, protectedFixture) { return environment; } -function projectedRunCostMicroUsd(plan) { - if ( - plan.model.provider === 'local' || - plan.model.route === 'openrouter/free' || - plan.model.route.endsWith(':free') - ) - return 0; - return plan.budget.maxCostMicroUsd; +/** Charges one finished attempt to the campaign; the rule lives in node-gym-runner-core.mjs. */ +async function chargeAttempt(plan, result) { + return await chargeNodeGymAttempt({ + reservationMicroUsd: reservationFor(plan), + result, + readLedger: async (runIds) => { + backendClient ??= await createNodeSlideBackendClient(convexUrl); + return await readLedgerReceipts({ backend: backendClient, runIds }); + }, + }); } function assertProtectedOutput(value, loadedFixture) { diff --git a/scripts/tests/deck-gym-campaign-budget.test.mjs b/scripts/tests/deck-gym-campaign-budget.test.mjs new file mode 100644 index 00000000..45b10550 --- /dev/null +++ b/scripts/tests/deck-gym-campaign-budget.test.mjs @@ -0,0 +1,578 @@ +/** + * Deck Gym campaign budget (SPEC Part A section A.2.8; Codex N1). + * + * Situation: someone points `npm run deck-gym:run` at production with two concurrent browsers and + * leaves. Before this change nothing counted dollars. These tests drive the REAL worker loop + * (`deckGymWorker`, the same function `scripts/run-deck-gym.mjs` runs) with fake runs standing in for + * the browser page and a fake backend budget ledger, and assert the queue stops before the cap even + * when two runs are in flight, each reserved at its worst case. + */ +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + DECK_GYM_CHARGES_FILE, + DECK_GYM_LOCK_FILE, + acquireDeckGymCampaignLock, + assertUniqueDeckGymRunIds, + createDeckGymCampaignBudget, + deckGymBudgetSummary, + deckGymWorker, + recordDeckGymCharge, + recordDeckGymReservation, + resolveDeckGymMaxTotalCostMicroUsd, + restoreDeckGymSpend, +} from '../lib/deck-gym-campaign.mjs'; +import { NODE_GYM_LEDGER_RECEIPT_VERSION } from '../lib/node-gym-runner-core.mjs'; + +// Lets one test kill the publish step of an atomic write, the way a killed process would, and make +// the listing of one run directory fail the way a permissions or sharing error does. +const publish = vi.hoisted(() => ({ failNext: false, denyListing: null })); +vi.mock('node:fs/promises', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + readdir: async (...args) => { + if (publish.denyListing !== null && String(args[0]) === publish.denyListing) { + throw Object.assign(new Error('EACCES: permission denied, scandir'), { code: 'EACCES' }); + } + return actual.readdir(...args); + }, + rename: async (...args) => { + if (publish.failNext) { + publish.failNext = false; + throw new Error('simulated kill while publishing the charge history'); + } + return actual.rename(...args); + }, + }; +}); + +const ledger = (actual) => ({ + version: NODE_GYM_LEDGER_RECEIPT_VERSION, + status: 'finalized', + spend: { actualMicroUsd: actual, reservedMicroUsd: 0, unreconciledMicroUsd: 0 }, +}); + +/** A gate the test opens by hand, so runs stay "in flight" for as long as the scenario needs. */ +function gate() { + let open; + const promise = new Promise((resolve) => { + open = resolve; + }); + return { promise, open }; +} + +describe('deck-gym campaign cap', () => { + it('stops the queue before the cap with two in-flight runs reserved at their worst case', async () => { + const PER_RUN = 1_000_000; + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: 2_500_000, + }); + const queue = Array.from({ length: 6 }, (_, index) => ({ runId: `run-${index + 1}` })); + const receipts = []; + const gates = new Map(queue.map((run) => [run.runId, gate()])); + const exposureAtDispatch = []; + const started = []; + const outcomes = new Map([ + ['run-1', { status: 'completed', backendRunIds: ['job-1'] }], + ['run-2', { status: 'failed' }], // crash: names no backend run + ['run-3', { status: 'completed', backendRunIds: ['job-3'] }], + ]); + const ledgerByJob = new Map([ + ['job-1', ledger(300_000)], + ['job-3', ledger(200_000)], + ]); + const common = { + queue, + budget, + receipts, + isResumable: async () => false, + executeRun: async (run) => { + // What the campaign has already committed, plus every run now in flight at its worst case. + exposureAtDispatch.push(budget.spentCostMicroUsd + budget.inFlight * PER_RUN); + started.push(run.runId); + await gates.get(run.runId).promise; + return { runId: run.runId, ...outcomes.get(run.runId) }; + }, + readLedger: async (ids) => new Map(ids.map((id) => [id, ledgerByJob.get(id) ?? null])), + }; + + const workers = [deckGymWorker(common), deckGymWorker(common)]; + await Promise.resolve(); + await new Promise((resolve) => setTimeout(resolve, 0)); + // Two runs are in flight, each reserved at 1,000,000. + expect(started).toEqual(['run-1', 'run-2']); + expect(budget.inFlight).toBe(2); + expect(deckGymBudgetSummary(budget).reservedInFlightMicroUsd).toBe(2_000_000); + + // run-1 finishes with a readable ledger receipt: 300,000 charged, headroom for one more. + gates.get('run-1').open(); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(budget.spentCostMicroUsd).toBe(300_000); + expect(started).toEqual(['run-1', 'run-2', 'run-3']); + + // run-2 crashes with no readable receipt: its full 1,000,000 reservation is charged. Spent + // 1,300,000 + (1 in flight + 1 new) x 1,000,000 = 3,300,000 > 2,500,000, so the queue stops. + gates.get('run-2').open(); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(budget.spentCostMicroUsd).toBe(1_300_000); + expect(budget.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + + gates.get('run-3').open(); + await Promise.all(workers); + + expect(started).toEqual(['run-1', 'run-2', 'run-3']); + expect(queue.map((run) => run.runId)).toEqual(['run-4', 'run-5', 'run-6']); + expect(budget.spentCostMicroUsd).toBe(1_500_000); + expect(budget.inFlight).toBe(0); + // The invariant the cap exists for: committed spend plus in-flight worst cases never crossed it. + expect(Math.max(...exposureAtDispatch)).toBeLessThanOrEqual(2_500_000); + expect(receipts.map((entry) => [entry.runId, entry.budget])).toEqual([ + ['run-1', { chargedMicroUsd: 300_000, source: 'ledger' }], + ['run-2', { chargedMicroUsd: 1_000_000, source: 'reservation' }], + ['run-3', { chargedMicroUsd: 200_000, source: 'ledger' }], + ]); + expect(deckGymBudgetSummary(budget)).toEqual({ + maxTotalCostMicroUsd: 2_500_000, + spentCostMicroUsd: 1_500_000, + reservedInFlightMicroUsd: 0, + stoppedBy: 'campaign_projected_cost_limit_reached', + }); + }); + + it('keeps the full reservation when the ledger lookup itself throws', async () => { + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: 5_000_000, + }); + const receipts = []; + await deckGymWorker({ + queue: [{ runId: 'run-1' }], + budget, + receipts, + isResumable: async () => false, + executeRun: async () => ({ runId: 'run-1', status: 'completed', backendRunIds: ['job-1'] }), + readLedger: async () => { + throw new Error('convex unreachable'); + }, + }); + expect(budget.spentCostMicroUsd).toBe(1_000_000); + expect(receipts[0].budget.source).toBe('reservation'); + }); + + it('charges a run whose execution throws outright its full reservation', async () => { + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: 5_000_000, + }); + const receipts = []; + await deckGymWorker({ + queue: [{ runId: 'run-1' }], + budget, + receipts, + isResumable: async () => false, + executeRun: async () => { + throw new Error('browser crashed'); + }, + readLedger: async () => new Map(), + }); + expect(budget.spentCostMicroUsd).toBe(1_000_000); + expect(receipts[0]).toMatchObject({ runId: 'run-1', status: 'failed' }); + }); + + it('never charges a resumed (skipped) run and never reserves for it', async () => { + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: 1_000_000, + }); + const receipts = []; + const executed = []; + await deckGymWorker({ + queue: [{ runId: 'done-1' }, { runId: 'done-2' }, { runId: 'fresh' }], + budget, + receipts, + isResumable: async (run) => run.runId.startsWith('done'), + executeRun: async (run) => { + executed.push(run.runId); + return { runId: run.runId, status: 'completed', backendRunIds: ['job'] }; + }, + readLedger: async () => new Map([['job', ledger(10)]]), + }); + expect(executed).toEqual(['fresh']); + expect(receipts.filter((entry) => entry.status === 'skipped')).toHaveLength(2); + expect(budget.spentCostMicroUsd).toBe(10); + expect(budget.stoppedBy).toBeNull(); + }); + + it('refuses to start any run when even one worst case exceeds the cap', async () => { + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd: 999_999, + }); + const queue = [{ runId: 'run-1' }]; + await deckGymWorker({ + queue, + budget, + receipts: [], + isResumable: async () => false, + executeRun: async () => { + throw new Error('must not dispatch'); + }, + readLedger: async () => new Map(), + }); + expect(budget.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + expect(queue).toHaveLength(1); + }); +}); + +describe('deck-gym cap resolution mirrors node-gym', () => { + it('requires an explicit cap unless the run count itself bounds the spend', () => { + expect( + resolveDeckGymMaxTotalCostMicroUsd({ + explicit: undefined, + limit: 12, + }), + ).toBe(12_000_000); + expect(() => + resolveDeckGymMaxTotalCostMicroUsd({ + explicit: undefined, + limit: 13, + }), + ).toThrow(/--max-total-cost-micro-usd is required/u); + expect(() => + resolveDeckGymMaxTotalCostMicroUsd({ + explicit: undefined, + limit: undefined, + }), + ).toThrow(/required/u); + expect( + resolveDeckGymMaxTotalCostMicroUsd({ + explicit: '2500000', + limit: 72, + }), + ).toBe(2_500_000); + expect(() => + resolveDeckGymMaxTotalCostMicroUsd({ + explicit: '-1', + limit: 1, + }), + ).toThrow(/non-negative integer/u); + }); +}); + +/** + * Situation (round 1, Codex): a person runs `deck-gym:run` with a 2 USD cap, it spends 1 USD, they + * stop it and run it again to finish. Each process used to start its meter at 0, so the second one + * spent another 2 USD under the same cap. These tests run the real restore and the real worker over + * real run directories. + */ +describe('deck-gym campaign cap binds the whole campaign across invocations', () => { + let runsDir; + beforeEach(async () => { + runsDir = await mkdtemp(path.join(os.tmpdir(), 'deck-gym-budget-')); + }); + afterEach(async () => { + await rm(runsDir, { recursive: true, force: true }); + }); + + const charges = async (runId) => + JSON.parse(await readFile(path.join(runsDir, runId, DECK_GYM_CHARGES_FILE), 'utf8')).charges; + + /** One invocation of the runner: restore, then drain the queue with the real worker. */ + async function invocation({ runs, maxTotalCostMicroUsd, ledgerMicroUsd, resumable = new Set() }) { + const budget = createDeckGymCampaignBudget({ + maxTotalCostMicroUsd, + spentCostMicroUsd: await restoreDeckGymSpend({ runsDir }), + }); + const queue = [...runs]; + const executed = []; + await deckGymWorker({ + queue, + budget, + receipts: [], + isResumable: async (run) => resumable.has(run.runId), + executeRun: async (run) => { + executed.push(run.runId); + return { runId: run.runId, status: 'completed', backendRunIds: [`job-${run.runId}`] }; + }, + readLedger: async (ids) => new Map(ids.map((id) => [id, ledger(ledgerMicroUsd)])), + recordReservation: (run, reservation) => + recordDeckGymReservation(path.join(runsDir, run.runId), reservation), + recordCharge: (run, charge) => recordDeckGymCharge(path.join(runsDir, run.runId), charge), + }); + return { budget, executed }; + } + + const runIds = (...ids) => ids.map((runId) => ({ runId })); + + it('does not let a second invocation spend a fresh cap: 1,000,000 before plus 2,000,000 after against 2,000,000', async () => { + const first = await invocation({ + runs: runIds('run-1'), + maxTotalCostMicroUsd: 2_000_000, + ledgerMicroUsd: 1_000_000, + }); + expect(first.budget.spentCostMicroUsd).toBe(1_000_000); + + const second = await invocation({ + runs: runIds('run-1', 'run-2', 'run-3'), + maxTotalCostMicroUsd: 2_000_000, + ledgerMicroUsd: 1_000_000, + resumable: new Set(['run-1']), + }); + // run-1 was skipped, yet its 1,000,000 counts; run-2 spends the other 1,000,000; run-3 is refused. + expect(second.executed).toEqual(['run-2']); + expect(second.budget.spentCostMicroUsd).toBe(2_000_000); + expect(second.budget.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + }); + + it('keeps the spend of a failed run that is re-run on resume', async () => { + await invocation({ + runs: runIds('run-1'), + maxTotalCostMicroUsd: 5_000_000, + ledgerMicroUsd: 300_000, + }); + await invocation({ + runs: runIds('run-1'), + maxTotalCostMicroUsd: 5_000_000, + ledgerMicroUsd: 400_000, + }); + expect((await charges('run-1')).map((entry) => entry.chargedMicroUsd)).toEqual([ + 300_000, 400_000, + ]); + expect(await restoreDeckGymSpend({ runsDir })).toBe(700_000); + }); + + it('charges an attempt whose process died before it was charged its full reservation', async () => { + await recordDeckGymReservation(path.join(runsDir, 'run-1'), 1_000_000); + expect(await restoreDeckGymSpend({ runsDir })).toBe(1_000_000); + // The re-run adds its own charge on top of the dead attempt's reservation. + await invocation({ + runs: runIds('run-1'), + maxTotalCostMicroUsd: 5_000_000, + ledgerMicroUsd: 200_000, + }); + expect(await restoreDeckGymSpend({ runsDir })).toBe(1_200_000); + }); + + it('charges a run directory from before charge records one reservation, and writes it down', async () => { + const legacyDir = path.join(runsDir, 'run-1'); + await mkdir(legacyDir, { recursive: true }); + await writeFile(path.join(legacyDir, 'run.json'), '{}'); + expect(await restoreDeckGymSpend({ runsDir })).toBe(1_000_000); + expect(await charges('run-1')).toEqual([{ chargedMicroUsd: 1_000_000, source: 'reservation' }]); + // Idempotent: a second restore does not charge it again, and a re-run cannot erase it. + expect(await restoreDeckGymSpend({ runsDir })).toBe(1_000_000); + }); + + // Before: `readdir(runDir).catch(() => [])` read any listing failure as an empty directory, so a + // prior run directory holding run.json but no charges file was skipped and its spend counted as 0 + // instead of one reservation (replayed with EACCES: restoreDeckGymSpend returned 0). + it('stops the campaign when a prior run directory cannot be listed (EACCES), not counting it as 0', async () => { + const runDir = path.join(runsDir, 'run-1'); + await mkdir(runDir, { recursive: true }); + await writeFile(path.join(runDir, 'run.json'), '{}'); + publish.denyListing = runDir; + try { + await expect(restoreDeckGymSpend({ runsDir })).rejects.toMatchObject({ code: 'EACCES' }); + } finally { + publish.denyListing = null; + } + // The failure wrote nothing down, and once the directory lists again it is one reservation. + expect(await readdir(runDir)).toEqual(['run.json']); + expect(await restoreDeckGymSpend({ runsDir })).toBe(1_000_000); + }); + + // Before: an unreadable charges file was restored as ONE reservation, so a two-attempt history + // (2,000,000 micro-USD) came back as 1,000,000 and, against a 2,000,000 cap, one more paid run was + // dispatched (true exposure 3,000,000). The history is unknown, so the campaign refuses instead. + describe.each([ + ['is not valid JSON', (dir) => writeFile(path.join(dir, DECK_GYM_CHARGES_FILE), '{not json')], + [ + 'fails the schema', + (dir) => + writeFile( + path.join(dir, DECK_GYM_CHARGES_FILE), + JSON.stringify({ schemaVersion: 'other/v9', charges: [] }), + ), + ], + [ + 'has a negative charge', + (dir) => + writeFile( + path.join(dir, DECK_GYM_CHARGES_FILE), + JSON.stringify({ + schemaVersion: 'nodeslide.deck-gym-run-charges/v1', + charges: [{ chargedMicroUsd: -1, source: 'ledger' }], + }), + ), + ], + // Stands in for EACCES / EBUSY: any read error other than ENOENT (here EISDIR). + ['cannot be read (not ENOENT)', (dir) => mkdir(path.join(dir, DECK_GYM_CHARGES_FILE))], + ])('a charges file that %s', (_name, corrupt) => { + it('stops the campaign instead of counting one reservation, and keeps the file', async () => { + const dir = path.join(runsDir, 'run-1'); + await recordDeckGymReservation(dir, 1_000_000); + await recordDeckGymReservation(dir, 1_000_000); + expect(await restoreDeckGymSpend({ runsDir })).toBe(2_000_000); + await rm(path.join(dir, DECK_GYM_CHARGES_FILE)); + await corrupt(dir); + + await expect(restoreDeckGymSpend({ runsDir })).rejects.toThrow(/spend is unknown/u); + // The lost history is not overwritten by a new reservation or charge either. + await expect(recordDeckGymReservation(dir, 1_000_000)).rejects.toThrow(/spend is unknown/u); + await expect( + recordDeckGymCharge(dir, { chargedMicroUsd: 1, source: 'ledger' }), + ).rejects.toThrow(/spend is unknown/u); + }); + }); + + it('counts the spend of runs this invocation did not select (a narrower --limit re-run)', async () => { + // First invocation: two runs, 1,000,000 each, against a 2,000,000 cap. + await invocation({ + runs: runIds('run-1', 'run-2'), + maxTotalCostMicroUsd: 2_000_000, + ledgerMicroUsd: 1_000_000, + }); + // Second invocation selects only run-3 (a smaller --limit or a narrower matrix). The earlier + // 2,000,000 still counts, so run-3 is refused instead of being admitted under a fresh cap. + const narrower = await invocation({ + runs: runIds('run-3'), + maxTotalCostMicroUsd: 2_000_000, + ledgerMicroUsd: 1_000_000, + }); + expect(narrower.budget.spentCostMicroUsd).toBe(2_000_000); + expect(narrower.executed).toEqual([]); + expect(narrower.budget.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + }); + + it('keeps the previous history intact when the rewrite is killed before it is published', async () => { + const dir = path.join(runsDir, 'run-1'); + await recordDeckGymReservation(dir, 1_000_000); + await recordDeckGymReservation(dir, 1_000_000); + expect(await restoreDeckGymSpend({ runsDir })).toBe(2_000_000); + + publish.failNext = true; + await expect(recordDeckGymReservation(dir, 1_000_000)).rejects.toThrow(/simulated kill/u); + + // Before: a truncating write that died here left an unreadable file, restored as ONE + // reservation (1,000,000 for a 2,000,000 history). Now the old history survives whole and no + // temporary file is left behind. + expect(await restoreDeckGymSpend({ runsDir })).toBe(2_000_000); + expect(await charges('run-1')).toHaveLength(2); + expect(await readdir(dir)).toEqual([DECK_GYM_CHARGES_FILE]); + }); + + it('charges nothing for a run that has never been started', async () => { + expect(await restoreDeckGymSpend({ runsDir })).toBe(0); + }); +}); + +/** + * Scenario: someone starts `deck-gym:run` twice on the same runs directory (a second terminal, a + * retry while the first still runs). Each would restore the same balance, create its own in-memory + * budget and rewrite the same charge files; replayed, two dispatched runs finalized 1,600,000 + * micro-USD against a 1,000,000 cap while 800,000 was persisted and both stopped with no cap hit. The + * second invocation must be refused before it restores or spends anything. + */ +describe('deck-gym campaign lock', () => { + let runsDir; + beforeEach(async () => { + runsDir = await mkdtemp(path.join(os.tmpdir(), 'deck-gym-lock-')); + }); + afterEach(async () => { + await rm(runsDir, { recursive: true, force: true }); + }); + + it('refuses the second of two racing invocations and admits one again after the first exits', async () => { + const start = async () => { + const release = acquireDeckGymCampaignLock(runsDir); + await restoreDeckGymSpend({ runsDir }); + return release; + }; + const outcomes = await Promise.allSettled([start(), start()]); + const winners = outcomes.filter((outcome) => outcome.status === 'fulfilled'); + const refused = outcomes.filter((outcome) => outcome.status === 'rejected'); + expect(winners).toHaveLength(1); + expect(refused).toHaveLength(1); + expect(refused[0].reason.message).toMatch(/already running .*"pid":\d+/u); + // The lock file is not a run directory: it adds no spend. + expect(await restoreDeckGymSpend({ runsDir })).toBe(0); + + winners[0].value(); + winners[0].value(); // releasing twice is harmless + expect(await readdir(runsDir)).not.toContain(DECK_GYM_LOCK_FILE); + acquireDeckGymCampaignLock(runsDir)(); + }); + + it('does not delete a lock another invocation took after the first one lost its file', async () => { + const releaseA = acquireDeckGymCampaignLock(runsDir); + await rm(path.join(runsDir, DECK_GYM_LOCK_FILE)); // an operator deleted it while A is alive + const releaseB = acquireDeckGymCampaignLock(runsDir); + releaseA(); + expect(await readdir(runsDir)).toContain(DECK_GYM_LOCK_FILE); + expect(() => acquireDeckGymCampaignLock(runsDir)).toThrow(/already running/u); + releaseB(); + expect(await readdir(runsDir)).not.toContain(DECK_GYM_LOCK_FILE); + }); +}); + +// Scenario: an operator hand-edits a matrix and pastes one run twice. Two workers would then hold the +// same run directory and read-modify-write its one budget-charges.json: one reservation or charge is +// lost and the next invocation restores less than was spent (replayed: $1.20 spent, $0.60 durable, +// $2.10 actual against a $2 cap). The matrix is refused before anything is dispatched. +describe('deck-gym matrix run directories are unique', () => { + it('accepts distinct runIds', () => { + expect(() => assertUniqueDeckGymRunIds([{ runId: 'a' }, { runId: 'b' }])).not.toThrow(); + }); + + it('refuses a repeated runId and ids that share a directory on a case-insensitive filesystem', () => { + expect(() => assertUniqueDeckGymRunIds([{ runId: 'run-1' }, { runId: 'run-1' }])).toThrow( + /repeats a run directory/, + ); + expect(() => assertUniqueDeckGymRunIds([{ runId: 'Run-1' }, { runId: 'run-1' }])).toThrow( + /repeats a run directory/, + ); + }); + + // Codex round 3, defect 2: lowercase string comparison does not see path aliases. run-deck-gym.mjs + // joins runId onto runsDir, so these three pass the old guard but resolve to one directory / outside. + it('refuses runIds that are not one path component, including aliases of another run directory', async () => { + const path = await import('node:path'); + const runsDir = path.resolve('artifacts', 'deck-gym-test', 'runs'); + for (const runId of [ + 'group/../same', + 'group\\..\\same', + '../../escape', + '..', + '.', + 'a/b', + 'same.', + 'C:evil', + 'nul\0byte', + ]) { + expect(() => assertUniqueDeckGymRunIds([{ runId }]), runId).toThrow( + /single safe path component/, + ); + } + // The failing replay: the guard accepted ['same','group/../same','../../escape']. + const aliases = ['same', 'group/../same', '../../escape']; + expect(() => assertUniqueDeckGymRunIds(aliases.map((runId) => ({ runId })))).toThrow( + /single safe path component/, + ); + // And the property the guard exists for: every accepted id is its own direct child of runsDir. + for (const runId of ['run-1', 'v1.model_a.task-3']) { + expect(() => assertUniqueDeckGymRunIds([{ runId }])).not.toThrow(); + expect(path.dirname(path.resolve(runsDir, runId))).toBe(runsDir); + } + }); + + it('refuses a run with no usable runId', () => { + expect(() => assertUniqueDeckGymRunIds([{ runId: 'a' }, {}])).toThrow(/without a runId/); + }); + + it('accepts the committed v1 matrix', async () => { + const { readDeckGymConfig, buildDeckGymMatrix } = await import('../lib/deck-gym-core.mjs'); + const { corpus, harness } = await readDeckGymConfig(process.cwd()); + const matrix = buildDeckGymMatrix(corpus, harness); + expect(matrix.runs).toHaveLength(72); + expect(() => assertUniqueDeckGymRunIds(matrix.runs)).not.toThrow(); + }); +}); diff --git a/scripts/tests/executor-split-probe.test.mjs b/scripts/tests/executor-split-probe.test.mjs new file mode 100644 index 00000000..0c6fc7ce --- /dev/null +++ b/scripts/tests/executor-split-probe.test.mjs @@ -0,0 +1,634 @@ +/** + * Candidate-bound executor receipt (SPEC Part A section A.2.8, Codex N1; rule 3 after round 1). + * + * Situation: an operator wants proof that, after Google retired Gemini 3.5 Flash, NodeSlide's routed + * copy executor really runs Gemini 3.8 Flash. The probe runs one premium-planner edit turn through + * the real planner, router and reserve-before-dispatch provider. Only the HTTP call is faked here + * (no provider is contacted, nothing is spent), so these tests prove the plumbing and the + * acceptance rule; the paid run itself is the operator's. + * + * Round 1 found the acceptance rule admitted a receipt with no planner span, a wrong executor + * identity, a wrong planner and no spend evidence. Each of those is a rejection case below. + */ +import { nodeSlideBudgetLedgerStubResponse } from '@nodeslide/testing'; +import { describe, expect, it, vi } from 'vitest'; +import { bindNodeSlideBudgetLedgerClient } from '../../convex/lib/nodeslideBudgetedProvider.ts'; +import { + NODESLIDE_EXECUTOR_SPLIT_PROBE_COMMAND, + executorSplitProbeBudgetUsd, + runNodeSlideExecutorSplitProbe, +} from '../../convex/lib/nodeslideExecutorSplitProbe.ts'; +import { NODESLIDE_ROUTING_EXECUTOR_MODEL } from '../../convex/lib/nodeslideRoutingPolicy.ts'; +import { buildGoldenNodeSlide } from '../../convex/lib/nodeslideSeed.ts'; +import { executorSplitReceiptFailures } from '../lib/model-fleet-receipt-core.mjs'; + +/** The committed executor id. Every executor figure below follows the constant, never a typed copy. */ +const EXECUTOR = NODESLIDE_ROUTING_EXECUTOR_MODEL; + +const COMMIT = 'a'.repeat(40); +const attempt = (name) => ({ + attempt: name, + attempted: true, + settled: true, + ambiguous: false, + unreconciled: false, + elapsedMs: 1, +}); +const calls = []; +const dispatchPolicies = []; +let plannerFails = false; +// null = the provider's response carried no `model` string at all (telemetry.echoedModel absent). +let executorEchoes = EXECUTOR; +let executorAttempts = [attempt('initial')]; +let plannerValue; + +vi.mock('../../convex/lib/nodeslideProvider.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + callNodeSlideFreeJson: vi.fn(async (request, dependencies) => { + calls.push(request.model); + dispatchPolicies.push(dependencies?.dispatchPolicy); + const isExecutor = request.jsonSchema?.name === 'nodeslide_copy_execution'; + // A planner that made two HTTP calls (initial + repair) and still failed. + if (plannerFails && !isExecutor) + return { + ok: false, + reason: 'The planner returned invalid JSON.', + telemetry: { + provider: 'openrouter', + requestedModel: request.model, + model: request.model, + costMicroUsd: 30_000, + inputTokens: 200, + outputTokens: 80, + attempts: [attempt('initial'), attempt('repair')], + }, + }; + return { + ok: true, + value: isExecutor + ? { + copy: plannerValue.operations.map((operation) => ({ + elementId: operation.elementId, + text: 'Executor copy', + })), + } + : plannerValue, + telemetry: { + provider: 'openrouter', + requestedModel: request.model, + model: request.model, + actualProvider: 'openrouter', + actualModel: isExecutor ? executorEchoes : 'moonshotai/kimi-k3', + // `actualModel` falls back to the requested id in the real provider; only `echoedModel` is + // the provider's own string, and it is absent when the response carried none. + ...((isExecutor ? executorEchoes : 'moonshotai/kimi-k3') === null + ? {} + : { echoedModel: isExecutor ? executorEchoes : 'moonshotai/kimi-k3' }), + costMicroUsd: isExecutor ? 1_000 : 20_000, + inputTokens: 120, + outputTokens: 40, + attempts: isExecutor ? executorAttempts : [attempt('initial')], + }, + }; + }), + }; +}); + +/** + * A ledger that keeps books: settle adds the call's actual cost, replay reports the total, as the + * real one does. The shared stub always answers zero spend, which would make `budget.spentUsd` + * unprovable here. + */ +function fakeLedger() { + const actualMicroUsd = new Map(); + // The shared stub quotes 1 USD per call, which no 0.25 USD probe could ever authorize; a real + // worst-case quote for these two calls is a few cents, so the books here use 50,000 micro-USD. + const withActual = (response, budgetId) => ({ + ...response, + ...(response.call ? { call: { ...response.call, quoteMicroUsd: 50_000 } } : {}), + budget: { + ...response.budget, + actualMicroUsd: actualMicroUsd.get(budgetId) ?? 0, + }, + }); + const ctx = { + runMutation: async (_reference, args) => { + if ('actualMicroUsd' in args) + actualMicroUsd.set( + args.budgetId, + (actualMicroUsd.get(args.budgetId) ?? 0) + args.actualMicroUsd, + ); + return withActual(nodeSlideBudgetLedgerStubResponse(args), args.budgetId); + }, + // A replay of one call id finds no prior record (a fresh call); a replay of the budget reports its books. + runQuery: async (_reference, args) => + 'callId' in args ? null : withActual(nodeSlideBudgetLedgerStubResponse(args), args.budgetId), + }; + const names = ['create', 'reserve', 'settle', 'captureTimeout', 'release', 'replay']; + return bindNodeSlideBudgetLedgerClient( + ctx, + Object.fromEntries(names.map((name) => [name, name])), + ); +} + +async function run() { + calls.length = 0; + dispatchPolicies.length = 0; + // The planner reply must name real element ids of the probe deck; the probe builds the same deck. + const snapshot = buildGoldenNodeSlide('executor-split-probe', 1_700_000_000_000).snapshot; + const bySlide = new Map(); + for (const element of snapshot.elements) { + if (element.kind !== 'text' || element.locked) continue; + bySlide.set(element.slideId, [...(bySlide.get(element.slideId) ?? []), element]); + } + const [a, b] = [...bySlide.values()].find((elements) => elements.length >= 2); + plannerValue = { + summary: 'Rewrite two blocks.', + operations: [ + { op: 'replace_text', slideId: a.slideId, elementId: a.id, text: 'Planner one' }, + { op: 'replace_text', slideId: b.slideId, elementId: b.id, text: 'Planner two' }, + ], + copyBriefs: [ + { slideId: a.slideId, elementId: a.id, brief: 'Opening statement.' }, + { slideId: b.slideId, elementId: b.id, brief: 'Proof point.' }, + ], + }; + return await runNodeSlideExecutorSplitProbe({ + ledger: fakeLedger(), + buildIdentity: { schemaVersion: 'nodeslide.convex-build-identity/v1', commitSha: COMMIT }, + budgetUsd: executorSplitProbeBudgetUsd({}), + }); +} + +async function acceptedReceipt() { + plannerFails = false; + executorEchoes = EXECUTOR; + executorAttempts = [attempt('initial')]; + return await run(); +} + +describe('runNodeSlideExecutorSplitProbe', () => { + it('splits a kimi-k3 plan to the committed executor and records what each provider echoed', async () => { + const receipt = await acceptedReceipt(); + expect(calls).toEqual(['moonshotai/kimi-k3', EXECUTOR]); + expect(receipt.routing).toMatchObject({ + plannerModel: 'moonshotai/kimi-k3', + executorModel: EXECUTOR, + reason: 'split_premium_planner_bulk_copy', + executorOutcome: 'applied', + }); + expect(receipt.spans.map((span) => [span.toolName, span.responseModel])).toEqual([ + ['planner', 'moonshotai/kimi-k3'], + ['executor', EXECUTOR], + ]); + expect(receipt.budget.refusals).toEqual([]); + expect(executorSplitReceiptFailures(receipt, COMMIT)).toEqual([]); + }); + + it('carries the Part A rule 3 fields: candidate, rows, revision, constant hash, ledger books, policy', async () => { + const receipt = await acceptedReceipt(); + expect(receipt.command).toBe(NODESLIDE_EXECUTOR_SPLIT_PROBE_COMMAND); + expect(receipt.candidateIds).toEqual([NODESLIDE_ROUTING_EXECUTOR_MODEL]); + expect(receipt.echoedModels.sort()).toEqual([EXECUTOR, 'moonshotai/kimi-k3'].sort()); + expect(receipt.rows).toEqual([ + { + toolName: 'planner', + requestedModel: 'moonshotai/kimi-k3', + resolvedModel: 'moonshotai/kimi-k3', + echoedModel: 'moonshotai/kimi-k3', + usage: { inputTokens: 120, outputTokens: 40 }, + costUsd: 0.02, + fallbackUsed: false, + dispatches: 1, + }, + { + toolName: 'executor', + requestedModel: EXECUTOR, + resolvedModel: EXECUTOR, + echoedModel: EXECUTOR, + usage: { inputTokens: 120, outputTokens: 40 }, + costUsd: 0.001, + fallbackUsed: false, + dispatches: 1, + }, + ]); + expect(receipt.testedCommit).toBe(COMMIT); + expect(receipt.constantSha256).toMatch(/^sha256:[0-9a-f]{64}$/u); + expect(receipt.dispatchPolicy).toEqual({ maxRetries: 0, crossModelFallback: false }); + expect(receipt.budget).toMatchObject({ + maxUsd: executorSplitProbeBudgetUsd({}), + requests: 2, + stoppedBy: null, + refusals: [], + }); + // Ledger books, not the rows: settled actual cost, at least what the provider reported. + expect(receipt.budget.spentUsd).toBeGreaterThanOrEqual(0.021); + expect(receipt.budget.estimateUsd).toBeGreaterThan(0); + expect(Number.isNaN(Date.parse(receipt.startedAt))).toBe(false); + expect(receipt.environment.runtime).toBe('convex-node-action'); + }); + + it('turns the provider retry off for every paid dispatch and records the enforced policy', async () => { + const receipt = await acceptedReceipt(); + // The policy reaches the provider call; it is not inferred afterwards from what happened. + expect(dispatchPolicies).toHaveLength(2); + for (const policy of dispatchPolicies) expect(policy?.maxRetries).toBe(0); + expect(receipt.dispatchPolicy).toEqual({ + maxRetries: 0, + crossModelFallback: false, + }); + }); + + it('rejects a span that nevertheless dispatched twice, and still reports the enforced policy', async () => { + executorEchoes = EXECUTOR; + plannerFails = false; + executorAttempts = [attempt('initial'), attempt('repair')]; + const receipt = await run(); + expect(receipt.rows.find((row) => row.toolName === 'executor')?.dispatches).toBe(2); + expect(receipt.budget.requests).toBe(3); + // Round 1 derived maxRetries from the observed count; it is the policy that was enforced. + expect(receipt.dispatchPolicy).toEqual({ + maxRetries: 0, + crossModelFallback: false, + }); + expect(executorSplitReceiptFailures(receipt, COMMIT)).toEqual( + expect.arrayContaining([ + 'executor row dispatched 2 times, not exactly once', + 'budget.requests is 3, not the 2 one planner and one executor request make', + 'budget.requests is 3, above the pre-flight ceiling of 2', + ]), + ); + }); + + it('reports the requests a failed planner made instead of zero', async () => { + plannerFails = true; + executorAttempts = [attempt('initial')]; + const receipt = await run(); + expect(receipt.routing.reason).toBe('planner_failed'); + expect(receipt.rows.map((row) => [row.toolName, row.dispatches])).toEqual([['planner', 2]]); + expect(receipt.budget.requests).toBe(2); + expect(receipt.budget.stoppedBy).toBe('The planner returned invalid JSON.'); + expect(executorSplitReceiptFailures(receipt, COMMIT).length).toBeGreaterThan(0); + }); + + it('is rejected when the provider echoed a different executor than the one requested', async () => { + plannerFails = false; + executorEchoes = 'google/gemini-3.6-flash'; + executorAttempts = [attempt('initial')]; + const receipt = await run(); + expect(receipt.rows.find((row) => row.toolName === 'executor')?.fallbackUsed).toBe(true); + // The policy is what was enforced (no code path re-dispatches to another model); the echo + // mismatch itself is what the row and the validator catch. + expect(receipt.dispatchPolicy.crossModelFallback).toBe(false); + const failures = executorSplitReceiptFailures(receipt, COMMIT); + expect(failures).toEqual( + expect.arrayContaining([ + 'executor responseModel is google/gemini-3.6-flash', + 'executor row used a fallback', + 'echoedModels does not include the executor', + ]), + ); + }); + + it('is rejected when the executor response carried no model string (Codex round 3, defect 1)', async () => { + // pi-ai fills AssistantMessage.model with the requested id, so a response that names no model used + // to read back as an echo of the requested one. The receipt must record null and refuse it. + plannerFails = false; + executorEchoes = null; + executorAttempts = [attempt('initial')]; + const receipt = await run(); + const executor = receipt.rows.find((row) => row.toolName === 'executor'); + expect(executor?.echoedModel).toBeNull(); + expect(receipt.spans.find((span) => span.toolName === 'executor')?.responseModel).toBeNull(); + expect(executorSplitReceiptFailures(receipt, COMMIT)).toEqual( + expect.arrayContaining([ + 'executor responseModel is null', + 'executor row echoedModel is null', + 'echoedModels does not include the executor', + ]), + ); + }); + + it('is rejected when the deployment is not the tested commit', async () => { + const receipt = await acceptedReceipt(); + expect(executorSplitReceiptFailures(receipt, 'b'.repeat(40))).toEqual([ + `testedCommit is ${COMMIT}`, + `buildIdentity.commitSha is ${COMMIT}`, + ]); + const unstamped = { ...receipt, testedCommit: null, buildIdentity: null }; + expect(executorSplitReceiptFailures(unstamped, COMMIT)).toEqual([ + 'testedCommit is null', + 'buildIdentity.commitSha is null', + ]); + }); + + it('is rejected when the turn did not split (a single-model turn is not executor evidence)', () => { + const failures = executorSplitReceiptFailures( + { + schemaVersion: 'nodeslide.executor-split-probe/v1', + routing: { + plannerModel: 'moonshotai/kimi-k3', + executorModel: null, + reason: 'single_model', + executorOutcome: null, + }, + spans: [], + budget: { refusals: [] }, + buildIdentity: { commitSha: COMMIT }, + }, + COMMIT, + ); + expect(failures).toEqual( + expect.arrayContaining(['routing.reason is single_model', 'no executor span']), + ); + }); +}); + +/** + * Round 1 (Codex): a receipt with no planner span, a wrong requested executor spanModel, plannerModel + * 'not-the-planner' and no spend evidence returned `[]`. Each mutation below starts from an accepted + * receipt and must change the verdict. + */ +describe('executorSplitReceiptFailures rejects incomplete or inconsistent evidence', () => { + const mutate = (receipt, change) => change(structuredClone(receipt)); + const cases = [ + [ + 'no planner span', + (r) => { + r.spans = r.spans.filter((span) => span.toolName !== 'planner'); + return r; + }, + 'no planner span', + ], + [ + 'no planner row', + (r) => { + r.rows = r.rows.filter((row) => row.toolName !== 'planner'); + return r; + }, + 'no planner row', + ], + [ + 'a wrong requested executor spanModel', + (r) => { + r.spans.find((span) => span.toolName === 'executor').spanModel = 'google/gemini-3.5-flash'; + return r; + }, + 'executor spanModel is google/gemini-3.5-flash', + ], + [ + 'a wrong requested executor on the row', + (r) => { + r.rows.find((row) => row.toolName === 'executor').requestedModel = + 'google/gemini-3.5-flash'; + return r; + }, + 'executor row requestedModel is google/gemini-3.5-flash', + ], + [ + 'a resolver that chose another model than was requested', + (r) => { + r.rows.find((row) => row.toolName === 'executor').resolvedModel = 'z-ai/glm-5.2'; + return r; + }, + 'executor row resolvedModel z-ai/glm-5.2 differs from requestedModel', + ], + [ + "plannerModel 'not-the-planner'", + (r) => { + r.routing.plannerModel = 'not-the-planner'; + return r; + }, + 'routing.plannerModel is not-the-planner', + ], + [ + 'a planner span on another model', + (r) => { + r.spans.find((span) => span.toolName === 'planner').spanModel = 'not-the-planner'; + return r; + }, + 'planner spanModel is not-the-planner', + ], + [ + 'no spend evidence (zero ledger spend)', + (r) => { + r.budget.spentUsd = 0; + return r; + }, + 'budget.spentUsd shows no spend', + ], + [ + 'a ledger that spent less than the rows report', + (r) => { + r.budget.spentUsd = 0.000001; + return r; + }, + 'budget.spentUsd is below the cost the rows report', + ], + [ + 'spend above the ceiling', + (r) => { + r.budget.spentUsd = r.budget.maxUsd + 1; + return r; + }, + 'budget.spentUsd exceeds budget.maxUsd', + ], + [ + 'no reservation recorded', + (r) => { + r.budget.estimateUsd = 0; + return r; + }, + 'budget.estimateUsd shows no reservation', + ], + [ + 'a budget stop', + (r) => { + r.budget.stoppedBy = 'The hard run budget could not authorize this provider call.'; + return r; + }, + 'budget.stoppedBy is The hard run budget could not authorize this provider call.', + ], + [ + 'a missing budget', + (r) => { + r.budget = undefined; + return r; + }, + 'budget is missing', + ], + [ + 'a missing dispatch policy', + (r) => { + r.dispatchPolicy = undefined; + return r; + }, + 'dispatchPolicy is null, not maxRetries 0 and no cross-model fallback', + ], + [ + 'retries enabled', + (r) => { + r.dispatchPolicy = { maxRetries: 1, crossModelFallback: false }; + return r; + }, + 'dispatchPolicy is {"maxRetries":1,"crossModelFallback":false}, not maxRetries 0 and no cross-model fallback', + ], + [ + 'a request count that disagrees with the rows', + (r) => { + r.budget.requests = 1; + return r; + }, + 'budget.requests is 1, rows dispatched 2', + ], + [ + 'rows stripped of usage, cost and dispatches with requests 0', + (r) => { + for (const row of r.rows) { + row.usage = undefined; + row.costUsd = undefined; + row.dispatches = undefined; + } + r.budget.requests = 0; + return r; + }, + 'planner row usage is missing', + ], + [ + 'row dispatches missing (counted as zero before)', + (r) => { + for (const row of r.rows) row.dispatches = undefined; + r.budget.requests = 0; + return r; + }, + 'executor row dispatched null times, not exactly once', + ], + [ + 'rows costed at 10 USD each against a ledger that settled 0.021', + (r) => { + for (const row of r.rows) row.costUsd = 10; + return r; + }, + 'budget.spentUsd is below the cost the rows report', + ], + [ + 'rows whose cost disagrees with their spans', + (r) => { + r.rows.find((row) => row.toolName === 'executor').costUsd = 0.5; + return r; + }, + 'executor row costUsd and span costMicroUsd disagree', + ], + [ + 'rows whose usage disagrees with their spans', + (r) => { + r.rows.find((row) => row.toolName === 'planner').usage = { + inputTokens: 1, + outputTokens: 1, + }; + return r; + }, + 'planner row usage and span usage disagree', + ], + [ + 'every row at zero dispatches and zero requests', + (r) => { + for (const row of r.rows) row.dispatches = 0; + r.budget.requests = 0; + return r; + }, + 'budget.requests is 0, not the 2 one planner and one executor request make', + ], + [ + 'a reservation estimate above the ceiling', + (r) => { + r.budget.estimateUsd = r.budget.maxUsd + 0.01; + return r; + }, + 'budget.estimateUsd exceeds budget.maxUsd', + ], + [ + 'settled spend above the summed reservation quotes', + (r) => { + r.budget.estimateUsd = 0.005; + return r; + }, + 'budget.spentUsd exceeds budget.estimateUsd', + ], + [ + 'two planner spans and no executor span', + (r) => { + r.spans.find((span) => span.toolName === 'executor').toolName = 'planner'; + return r; + }, + 'spans and rows are not exactly one planner and one executor', + ], + [ + 'the wrong candidate', + (r) => { + r.candidateIds = ['google/gemini-3.5-flash']; + return r; + }, + 'candidateIds does not name the executor under test', + ], + [ + 'a constant hash of another executor', + (r) => { + r.constantSha256 = `sha256:${'0'.repeat(64)}`; + return r; + }, + 'constantSha256 does not match the executor constant', + ], + [ + 'another command', + (r) => { + r.command = 'npx convex run nodeslideModelProbe:runFleet'; + return r; + }, + 'command is npx convex run nodeslideModelProbe:runFleet', + ], + [ + 'a row that no longer matches its span', + (r) => { + r.rows.find((row) => row.toolName === 'executor').echoedModel = 'google/gemini-3.6-flash'; + return r; + }, + 'executor row echoedModel is google/gemini-3.6-flash', + ], + ]; + + it('accepts the unmutated receipt (so each rejection below is caused by its mutation)', async () => { + expect(executorSplitReceiptFailures(await acceptedReceipt(), COMMIT)).toEqual([]); + }); + + it.each(cases)('rejects %s', async (_label, change, expectedFailure) => { + const receipt = mutate(await acceptedReceipt(), change); + expect(executorSplitReceiptFailures(receipt, COMMIT)).toContain(expectedFailure); + }); + + it('never throws on a malformed receipt', () => { + for (const bad of [null, undefined, {}, [], 'x', { schemaVersion: 'other' }]) { + expect(() => executorSplitReceiptFailures(bad, COMMIT)).not.toThrow(); + expect(executorSplitReceiptFailures(bad, COMMIT).length).toBeGreaterThan(0); + } + expect( + executorSplitReceiptFailures({ schemaVersion: 'nodeslide.executor-split-probe/v1' }, COMMIT) + .length, + ).toBeGreaterThan(0); + }); +}); + +describe('executorSplitProbeBudgetUsd', () => { + it('defaults to 0.55 USD and honours NODESLIDE_PROBE_BUDGET_USD', () => { + // Was 0.25 USD, which the real ledger refuses before any dispatch (SPEC D3, 2026-10-16; + // convex/nodeslideExecutorSplitProbeBudget.test.ts holds the real-ledger figures). + expect(executorSplitProbeBudgetUsd({})).toBe(0.55); + expect(executorSplitProbeBudgetUsd({ NODESLIDE_PROBE_BUDGET_USD: '0.1' })).toBe(0.1); + }); + it('refuses an unreadable or non-positive ceiling instead of substituting a larger one', () => { + expect(() => executorSplitProbeBudgetUsd({ NODESLIDE_PROBE_BUDGET_USD: 'abc' })).toThrow(); + expect(() => executorSplitProbeBudgetUsd({ NODESLIDE_PROBE_BUDGET_USD: '0' })).toThrow(); + }); +}); diff --git a/scripts/tests/node-gym-campaign-budget.test.mjs b/scripts/tests/node-gym-campaign-budget.test.mjs new file mode 100644 index 00000000..5d0d3099 --- /dev/null +++ b/scripts/tests/node-gym-campaign-budget.test.mjs @@ -0,0 +1,543 @@ +/** + * Node-gym campaign accounting (SPEC Part A section A.2.8, Codex v4-new-1). + * + * Situation: someone starts a keyed node-gym campaign with a 100,000 micro-USD cap and walks away. + * The old runner checked the cap against the gym plan's own projection (200,000) but charged the + * executor's self-reported figure afterwards: 0 when the executor crashed or timed out, 0 in its + * failure result, and a number scraped from the Trace inspector text otherwise. Codex replayed it: + * cap 100,000, 180,000 really charged by the backend before a crash, meter 0, second run admitted. + * + * These tests run the REAL charge rule (`chargeNodeGymAttempt`, `nodeGymRunCharge`) and the REAL + * stop rule (`shouldStopCampaign`) in campaign order against a fake backend ledger. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + NODESLIDE_RUN_BUDGET_LEDGER_RECEIPT_VERSION, + normalizeNodeSlideRunBudget, +} from '../../shared/nodeslideRunBudget.ts'; +import { acquireDeckGymCampaignLock } from '../lib/deck-gym-campaign.mjs'; +import { + NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD, + NODE_GYM_LEDGER_RECEIPT_VERSION, + chargeNodeGymAttempt, + createNodeGymChildGuard, + loadNodeGymOrphanCharges, + nodeGymRunReservationMicroUsd, + setAsideNodeGymOrphanAttempts, + shouldStopCampaign, + summarizeNodeGymAttemptHistory, +} from '../lib/node-gym-runner-core.mjs'; + +const paidPlan = (runId) => ({ + runId, + comparisonKey: 'c', + harnessPairingKey: 'p', + pairingKey: 'p', + repetition: 1, + model: { id: 'moonshotai/kimi-k3', route: 'moonshotai/kimi-k3', provider: 'openrouter' }, + // The gym plan's own cap: what the old runner reserved, and which the backend never sees. + budget: { maxCostMicroUsd: 200_000 }, +}); + +function ledgerReceipt(actual, { reserved = 0, unreconciled = 0 } = {}) { + return { + version: NODE_GYM_LEDGER_RECEIPT_VERSION, + budgetId: 'nsbudget_x', + status: 'finalized', + spend: { + actualMicroUsd: actual, + reservedMicroUsd: reserved, + unreconciledMicroUsd: unreconciled, + }, + }; +} + +/** The campaign loop of `scripts/run-node-gym.mjs`, with a fake executor and a fake backend ledger. */ +async function runCampaign({ plans, maxTotalCostMicroUsd, execute, ledger }) { + let spentCostMicroUsd = 0; + let reservedUnknownMicroUsd = 0; + let stoppedBy = null; + const dispatched = []; + for (const plan of plans) { + const reservationMicroUsd = nodeGymRunReservationMicroUsd(plan); + const circuit = shouldStopCampaign({ + spentCostMicroUsd, + maxTotalCostMicroUsd, + failures: 0, + maxFailures: 2, + nextRunMaxCostMicroUsd: reservationMicroUsd, + }); + if (circuit.stop) { + stoppedBy = circuit.issueCode; + break; + } + dispatched.push(plan.runId); + const result = await execute(plan).catch(() => ({ + status: 'failed', + issueCodes: ['executor_process_failed'], + })); + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd, + result, + readLedger: async (ids) => new Map(ids.map((id) => [id, ledger.get(id) ?? null])), + }); + spentCostMicroUsd += charge.chargedMicroUsd; + if (charge.source === 'reservation') reservedUnknownMicroUsd += charge.chargedMicroUsd; + } + return { spentCostMicroUsd, reservedUnknownMicroUsd, stoppedBy, dispatched }; +} + +describe('the mirrored backend per-run cap cannot drift from the backend', () => { + it('reserves exactly what the ledger binds to a default run', () => { + expect(NODE_GYM_BACKEND_RUN_RESERVATION_MICRO_USD).toBe( + normalizeNodeSlideRunBudget({}).maxCostMicroUsd, + ); + expect(NODE_GYM_LEDGER_RECEIPT_VERSION).toBe(NODESLIDE_RUN_BUDGET_LEDGER_RECEIPT_VERSION); + }); + + it('keeps local, :free and openrouter/free routes at a zero reservation, and charges paid routes the backend cap', () => { + const free = (route, provider = 'openrouter') => ({ model: { route, provider } }); + expect(nodeGymRunReservationMicroUsd(free('google/gemma:free'))).toBe(0); + expect(nodeGymRunReservationMicroUsd(free('openrouter/free'))).toBe(0); + expect(nodeGymRunReservationMicroUsd(free('deterministic', 'local'))).toBe(0); + expect(nodeGymRunReservationMicroUsd(paidPlan('r'))).toBe(1_000_000); + // No override exists: a reservation below the enforced cap cannot be requested. + expect(nodeGymRunReservationMicroUsd(paidPlan('r'), 0)).toBe(1_000_000); + }); +}); + +describe('a run is charged what the backend ledger recorded, or its full reservation', () => { + it('(a) a crashed run with no readable receipt leaves its full reservation in the meter', async () => { + const outcome = await runCampaign({ + plans: [paidPlan('run-crash')], + maxTotalCostMicroUsd: 1_000_000, + execute: async () => { + throw new Error('executor process killed at its timeout'); + }, + ledger: new Map(), + }); + expect(outcome.spentCostMicroUsd).toBe(1_000_000); + expect(outcome.reservedUnknownMicroUsd).toBe(1_000_000); + }); + + it('(b) the same failure with a readable ledger receipt is charged the ledger figure', async () => { + // The page started two backend jobs and then the export failed: the failure result names the + // runs it had already started, so the ledger (not the whole reservation) is the charge. + const outcome = await runCampaign({ + plans: [paidPlan('run-ledger')], + maxTotalCostMicroUsd: 1_000_000, + execute: async () => ({ status: 'failed', backendRunIds: ['job-1', 'job-2'] }), + ledger: new Map([ + ['job-1', ledgerReceipt(40_000)], + ['job-2', ledgerReceipt(25_000, { unreconciled: 5_000 })], + ]), + }); + expect(outcome.spentCostMicroUsd).toBe(70_000); + expect(outcome.reservedUnknownMicroUsd).toBe(0); + }); + + it.each([ + [ + 'an executor failure result that names no backend run', + { status: 'failed', issueCodes: ['ui_executor_failed'] }, + ], + ['a missing result', undefined], + ['a completed result naming no backend run', { status: 'completed', backendRunIds: [] }], + ['a completed result with malformed run ids', { status: 'completed', backendRunIds: [7] }], + [ + 'a completed result whose receipt is unreadable', + { status: 'completed', backendRunIds: ['ghost'] }, + ], + ])('keeps the full reservation for %s', async (_label, result) => { + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 180_000, + result, + readLedger: async (ids) => new Map(ids.map((id) => [id, null])), + }); + expect(charge).toEqual({ chargedMicroUsd: 180_000, source: 'reservation' }); + }); + + it('never trusts the executor-reported cost: a cheap claim does not lower the charge', async () => { + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 180_000, + result: { status: 'failed', usage: { costMicroUsd: 0 } }, + readLedger: async () => new Map(), + }); + expect(charge.chargedMicroUsd).toBe(180_000); + }); + + it('counts reserved and unreconciled exposure: a dispatch whose outcome never came back may be billed', async () => { + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 1_000_000, + result: { status: 'completed', backendRunIds: ['job-1'] }, + readLedger: async () => + new Map([['job-1', ledgerReceipt(10_000, { reserved: 20_000, unreconciled: 30_000 })]]), + }); + expect(charge).toEqual({ chargedMicroUsd: 60_000, source: 'ledger' }); + }); + + it('keeps the full reservation while the ledger row is still open: a job outlives a UI timeout', async () => { + // The browser gave up (export timed out) but the backend job is still running and still billing. + const open = { ...ledgerReceipt(0), status: 'open' }; + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 1_000_000, + result: { status: 'failed', issueCodes: ['pptx_export_timeout'], backendRunIds: ['job-1'] }, + readLedger: async () => new Map([['job-1', open]]), + }); + expect(charge).toEqual({ chargedMicroUsd: 1_000_000, source: 'reservation' }); + }); + + it('keeps the reservation when any one of several named ledger rows is not finalized', async () => { + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 1_000_000, + result: { status: 'completed', backendRunIds: ['job-1', 'job-2'] }, + readLedger: async () => + new Map([ + ['job-1', ledgerReceipt(10_000)], + ['job-2', { ...ledgerReceipt(10_000), status: 'open' }], + ]), + }); + expect(charge).toEqual({ chargedMicroUsd: 1_000_000, source: 'reservation' }); + }); + + it('charges a zero reservation for a free route even when its result is a failure', async () => { + const charge = await chargeNodeGymAttempt({ + reservationMicroUsd: 0, + result: { status: 'failed' }, + readLedger: async () => new Map(), + }); + expect(charge).toEqual({ chargedMicroUsd: 0, source: 'reservation' }); + }); +}); + +// Codex's v4 figures were a 100,000 cap against a run whose binding backend cap was 180,000. The +// binding cap cannot be chosen (round 1: the per-run flag was removed), so the same scenario now runs +// at the real 1,000,000 cap; the cap stays 100,000. The refusal is the same and the margin larger. +describe('(c) cap 100,000 micro-USD against the binding backend cap of 1,000,000', () => { + it('refuses the first run before dispatch, because its reservation alone exceeds the cap', async () => { + const outcome = await runCampaign({ + plans: [paidPlan('run-1'), paidPlan('run-2')], + maxTotalCostMicroUsd: 100_000, + execute: async () => { + throw new Error('must never be dispatched'); + }, + ledger: new Map(), + }); + expect(outcome.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + expect(outcome.dispatched).toEqual([]); + expect(outcome.spentCostMicroUsd).toBe(0); + }); + + it('the old runner admitted a second run (the defect): reservation 200,000 / meter 0 after a crash', () => { + // What the old campaign loop computed for the same inputs, kept as the knockout reference: + // a crash charged 0 and the gym plan's 200,000 projection was compared to a cap it never bound. + const oldMeterAfterCrash = 0; + expect( + shouldStopCampaign({ + spentCostMicroUsd: oldMeterAfterCrash, + maxTotalCostMicroUsd: 100_000, + failures: 1, + maxFailures: 2, + nextRunMaxCostMicroUsd: 0, + }).stop, + ).toBe(false); + // Under the new rule the crash is charged its reservation and the campaign is over. + expect( + shouldStopCampaign({ + spentCostMicroUsd: 1_000_000, + maxTotalCostMicroUsd: 100_000, + failures: 1, + maxFailures: 2, + nextRunMaxCostMicroUsd: 1_000_000, + }), + ).toEqual({ stop: true, issueCode: 'campaign_cost_limit_reached' }); + }); + + it('a campaign that can afford one run admits it, charges the ledger, and refuses the next on projection', async () => { + const outcome = await runCampaign({ + plans: [paidPlan('run-1'), paidPlan('run-2'), paidPlan('run-3')], + maxTotalCostMicroUsd: 1_200_000, + execute: async (plan) => ({ status: 'completed', backendRunIds: [`job-${plan.runId}`] }), + ledger: new Map([ + ['job-run-1', ledgerReceipt(150_000)], + ['job-run-2', ledgerReceipt(150_000)], + ]), + }); + expect(outcome.dispatched).toEqual(['run-1', 'run-2']); + expect(outcome.spentCostMicroUsd).toBe(300_000); + // 300,000 spent + 1,000,000 reserved for run-3 > 1,200,000. + expect(outcome.stoppedBy).toBe('campaign_projected_cost_limit_reached'); + }); +}); + +describe('attempt history: legacy receipts and orphaned attempts', () => { + let campaignRoot; + let attemptsDir; + beforeEach(async () => { + campaignRoot = await mkdtemp(path.join(os.tmpdir(), 'node-gym-budget-')); + attemptsDir = path.join(campaignRoot, 'runs', 'run-1', 'attempts'); + await mkdir(attemptsDir, { recursive: true }); + }); + afterEach(async () => { + await rm(campaignRoot, { recursive: true, force: true }); + }); + + const plan = paidPlan('run-1'); + + function receipt(attempt, overrides = {}) { + return { + schemaVersion: 'nodekit.gym-run-receipt/v2', + attempt, + runId: 'run-1', + comparisonKey: 'c', + harnessPairingKey: 'p', + pairingKey: 'p', + repetition: 1, + executor: 'ui', + status: 'failed', + automatedHardGatesPassed: false, + issueCodes: ['execution_failed'], + planDigest: undefined, + executorResultDigest: `sha256:${'1'.repeat(64)}`, + semanticEvaluationDigest: `sha256:${'2'.repeat(64)}`, + usage: { latencyMs: 1, inputTokens: 1, outputTokens: 1, repairCount: 0, costMicroUsd: 0 }, + ...overrides, + }; + } + + async function digestedPlan() { + const { digestJson } = await import('../lib/node-gym-runner-core.mjs'); + return { plan, planDigest: digestJson(plan) }; + } + + it('charges a receipt written before charges were recorded the run full reservation, not its own usage figure', async () => { + const { planDigest } = await digestedPlan(); + const legacy = receipt(1, { planDigest }); + expect(legacy.budget).toBeUndefined(); + const history = summarizeNodeGymAttemptHistory({ + plan, + receipts: [legacy], + executor: 'ui', + reservationMicroUsd: 180_000, + }); + expect(history.spentCostMicroUsd).toBe(180_000); + expect(history.reservedUnknownMicroUsd).toBe(180_000); + }); + + it('sums the recorded charge of a current receipt and ignores its usage figure', async () => { + const { planDigest } = await digestedPlan(); + const current = receipt(1, { + planDigest, + usage: { + latencyMs: 1, + inputTokens: 1, + outputTokens: 1, + repairCount: 0, + costMicroUsd: 999_999, + }, + budget: { chargedMicroUsd: 42_000, source: 'ledger' }, + }); + const history = summarizeNodeGymAttemptHistory({ + plan, + receipts: [current], + executor: 'ui', + reservationMicroUsd: 180_000, + }); + expect(history.spentCostMicroUsd).toBe(42_000); + expect(history.reservedUnknownMicroUsd).toBe(0); + }); + + it('rejects a malformed recorded charge instead of reading it as zero', async () => { + const { planDigest } = await digestedPlan(); + expect(() => + summarizeNodeGymAttemptHistory({ + plan, + receipts: [receipt(1, { planDigest, budget: { chargedMicroUsd: -1, source: 'ledger' } })], + executor: 'ui', + reservationMicroUsd: 180_000, + }), + ).toThrow(/invalid budget charge/u); + }); + + it('(d) a resume over an attempt directory without its receipt charges that reservation, once', async () => { + await mkdir(path.join(attemptsDir, 'attempt-001', 'work'), { recursive: true }); + await writeFile(path.join(attemptsDir, 'attempt-001', 'plan.json'), '{}\n'); + + // First resume: the directory has no attempt-001.json receipt (the runner died). + await setAsideNodeGymOrphanAttempts({ + campaignRoot, + attemptsDir, + runId: 'run-1', + orphanAttempts: [1], + reservationMicroUsd: 180_000, + }); + let charges = await loadNodeGymOrphanCharges({ attemptsDir, runId: 'run-1' }); + expect(charges).toHaveLength(1); + expect(charges[0].budget).toEqual({ chargedMicroUsd: 180_000, source: 'reservation' }); + // The evidence is kept, under a name the attempt scanner ignores, and attempt 1 can be re-issued. + const names = await readdir(attemptsDir); + expect(names).toContain('orphaned-attempt-001-1'); + expect(names).not.toContain('attempt-001'); + + const history = summarizeNodeGymAttemptHistory({ + plan, + receipts: [], + executor: 'ui', + reservationMicroUsd: 180_000, + orphanCharges: charges, + }); + expect(history).toMatchObject({ + spentCostMicroUsd: 180_000, + reservedUnknownMicroUsd: 180_000, + latestAttempt: 0, + }); + + // A second resume must not charge the same directory again. + charges = await loadNodeGymOrphanCharges({ attemptsDir, runId: 'run-1' }); + expect(charges).toHaveLength(1); + + // The re-issued attempt dies too: a second orphan, a second (distinct) charge. + await mkdir(path.join(attemptsDir, 'attempt-001'), { recursive: true }); + await setAsideNodeGymOrphanAttempts({ + campaignRoot, + attemptsDir, + runId: 'run-1', + orphanAttempts: [1], + reservationMicroUsd: 180_000, + }); + charges = await loadNodeGymOrphanCharges({ attemptsDir, runId: 'run-1' }); + expect(charges).toHaveLength(2); + expect((await readdir(attemptsDir)).sort()).toEqual( + [ + 'orphaned-attempt-001-1', + 'orphaned-attempt-001-1.charge.json', + 'orphaned-attempt-001-2', + 'orphaned-attempt-001-2.charge.json', + ].sort(), + ); + }); + + it('does not double-charge a directory whose charge was written but whose rename never ran', async () => { + await mkdir(path.join(attemptsDir, 'attempt-002'), { recursive: true }); + // The runner died between writing the charge and renaming the directory. + await writeFile( + path.join(attemptsDir, 'orphaned-attempt-002-1.charge.json'), + `${JSON.stringify({ + schemaVersion: 'nodekit.gym-orphan-attempt-charge/v1', + runId: 'run-1', + attempt: 2, + budget: { chargedMicroUsd: 180_000, source: 'reservation' }, + })}\n`, + ); + await setAsideNodeGymOrphanAttempts({ + campaignRoot, + attemptsDir, + runId: 'run-1', + orphanAttempts: [2], + reservationMicroUsd: 180_000, + }); + expect(await loadNodeGymOrphanCharges({ attemptsDir, runId: 'run-1' })).toHaveLength(1); + expect(await readdir(attemptsDir)).toContain('orphaned-attempt-002-1'); + }); + + it('rejects a tampered orphan charge', async () => { + await writeFile( + path.join(attemptsDir, 'orphaned-attempt-001-1.charge.json'), + `${JSON.stringify({ + schemaVersion: 'nodekit.gym-orphan-attempt-charge/v1', + runId: 'run-1', + attempt: 1, + budget: { chargedMicroUsd: 0, source: 'ledger' }, + })}\n`, + ); + await expect(loadNodeGymOrphanCharges({ attemptsDir, runId: 'run-1' })).rejects.toThrow( + /orphan charge/u, + ); + }); +}); + +/** + * Scenario: someone starts `node-gym:run` while an earlier launch of the same campaign is still + * running (the default campaign id is the same for every launch). The live attempt has no receipt + * yet, exactly like a dead one, so a second run used to set its workspace aside, restore its + * reservation and re-issue the attempt: replayed, 3,000,000 micro-USD dispatched against a 2,000,000 + * cap. The second launch must be refused before it reads or writes anything in the campaign. + */ +describe('two invocations on one campaign', () => { + const campaignDir = path.join( + 'artifacts', + 'node-gym', + 'nodeslide-deck-gym-v2', + 'campaigns', + `lock-test-${process.pid}`, + ); + const launch = () => + spawnSync( + process.execPath, + ['scripts/run-node-gym.mjs', '--artifact-dir', campaignDir, '--limit', '2'], + { encoding: 'utf8' }, + ); + afterEach(async () => { + await rm(campaignDir, { recursive: true, force: true }); + }); + + it('refuses a launch while the campaign is held, touching nothing, and runs again once it is released', async () => { + await mkdir(campaignDir, { recursive: true }); + const release = acquireDeckGymCampaignLock(campaignDir, 'NodeGym'); + const refused = launch(); + expect(refused.status).not.toBe(0); + expect(refused.stderr).toMatch(/NodeGym campaign .* is already running/u); + expect(await readdir(campaignDir)).toEqual(['campaign.lock']); + + release(); + const admitted = launch(); + expect(admitted.stderr).not.toMatch(/already running/u); + expect(await readdir(campaignDir)).toContain('campaign-plan.json'); + expect(await readdir(campaignDir)).not.toContain('campaign.lock'); + }); +}); + +/** + * Scenario: a supervisor (`kill `, `docker stop` on PID 1) sends SIGTERM to the campaign parent + * only, while a paid executor child is mid-attempt. On POSIX the child outlives the parent, and the + * parent's exit handler used to release `campaign.lock` immediately, so a second launch could take the + * lock, treat the live workspace as an orphan and re-issue the attempt path the survivor still writes. + * The signal path must not release the lock until the child has closed. + */ +describe('stopping the executor before the lock is released', () => { + const alive = (pid) => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + const sleeper = (script) => spawn(process.execPath, ['-e', script], { stdio: 'ignore' }); + + it('resolves only after a running child is dead, and does nothing when none runs', async () => { + const guard = createNodeGymChildGuard(); + await guard.stop(); + const child = sleeper('setInterval(() => {}, 1000)'); + guard.track(child); + await new Promise((resolve) => child.once('spawn', resolve)); + await guard.stop(); + expect(alive(child.pid)).toBe(false); + }); + + it('escalates to SIGKILL for a child that ignores the first signal', async () => { + const guard = createNodeGymChildGuard({ graceMs: 200 }); + const child = sleeper( + "process.on('SIGTERM', () => {}); console.log('x'); setInterval(() => {}, 1000)", + ); + guard.track(child); + await new Promise((resolve) => child.once('spawn', resolve)); + await new Promise((resolve) => setTimeout(resolve, 300)); + await guard.stop(); + expect(alive(child.pid)).toBe(false); + }); +}); diff --git a/scripts/tests/node-gym-disabled-model.test.mjs b/scripts/tests/node-gym-disabled-model.test.mjs new file mode 100644 index 00000000..3ef3684a --- /dev/null +++ b/scripts/tests/node-gym-disabled-model.test.mjs @@ -0,0 +1,99 @@ +/** + * Disabled-model exclusion for the node-gym campaign (SPEC Part A section A.2.8, Codex v2-new-3). + * + * Situation: OpenRouter dropped `openai/gpt-oss-20b:free` from its catalog on 2026-10-10. Its row + * must stay in the benchmark (run ids and pairing keys hash `model.id`, so deleting it renumbers the + * whole matrix), yet a campaign must never try to run it. These tests load the COMMITTED config and + * matrix and drive the real selection path the runner uses. + */ +import { readFileSync } from 'node:fs'; +import { describe, expect, it } from 'vitest'; +import { validateNodeGymConfig } from '../lib/node-gym-config-core.mjs'; +import { selectNodeGymCampaignRuns } from '../lib/node-gym-selection-core.mjs'; + +const DISABLED_MODEL = 'openai/gpt-oss-20b:free'; +const config = JSON.parse(readFileSync('benchmarks/deck-gym/v2/gym.json', 'utf8')); +const matrix = JSON.parse( + readFileSync('artifacts/node-gym/nodeslide-deck-gym-v2/matrix.json', 'utf8'), +); +// Naming every task explicitly skips runtime filtering of protected-fixture tasks, which depends on +// the machine's environment; the disabled-model partition under test does not. +const noFilters = { + tasks: config.tasks.map((task) => task.id), + models: [], + harnesses: [], + repetitions: [], +}; +const select = (overrides = {}) => + selectNodeGymCampaignRuns({ + matrix, + config, + filters: noFilters, + subset: 'all', + runtime: {}, + ...overrides, + }); + +describe('execution.disabled on the committed v2 gym', () => { + it('keeps the row, so the matrix identity stays 720 runs', () => { + expect(matrix.runs).toHaveLength(720); + expect(matrix.runs.filter((run) => run.model.id === DISABLED_MODEL)).toHaveLength(120); + }); + + it('--subset all selects 600 runs and reports the 120 it skipped', () => { + const { selectedRuns, skippedDisabled } = select(); + expect(selectedRuns).toHaveLength(600); + expect(skippedDisabled).toHaveLength(120); + expect(selectedRuns.some((run) => run.model.id === DISABLED_MODEL)).toBe(false); + expect(skippedDisabled[0]).toMatchObject({ + modelId: DISABLED_MODEL, + since: '2026-10-10', + reason: expect.stringContaining('unlisted on OpenRouter'), + }); + }); + + it('--include-disabled is the only override and brings back all 720', () => { + const { selectedRuns, skippedDisabled } = select({ includeDisabled: true }); + expect(selectedRuns).toHaveLength(720); + expect(skippedDisabled).toHaveLength(0); + }); + + it('naming the disabled model without the override is an error, not an empty match', () => { + expect(() => select({ filters: { ...noFilters, models: [DISABLED_MODEL] } })).toThrow( + /disabled since 2026-10-10.*--include-disabled/u, + ); + }); +}); + +describe('validateNodeGymConfig accepts execution only as { disabled: true, since, reason }', () => { + const withExecution = (execution) => { + const copy = structuredClone(config); + copy.models.find((model) => model.id === DISABLED_MODEL).execution = execution; + return validateNodeGymConfig(copy).failures; + }; + + it('passes the committed config', () => { + expect(validateNodeGymConfig(config).failures).toEqual([]); + }); + + it('accepts a real leap day', () => { + expect( + withExecution({ disabled: true, since: '2028-02-29', reason: 'x' }).filter((failure) => + failure.includes('execution'), + ), + ).toEqual([]); + }); + + it.each([ + ['disabled false', { disabled: false, since: '2026-10-10', reason: 'x' }], + ['an extra key', { disabled: true, since: '2026-10-10', reason: 'x', note: 'y' }], + ['a non-ISO date', { disabled: true, since: 'yesterday', reason: 'x' }], + ['an impossible date', { disabled: true, since: '2026-02-30', reason: 'x' }], + ['Feb 29 in a non-leap year', { disabled: true, since: '2027-02-29', reason: 'x' }], + ['month 13', { disabled: true, since: '2026-13-01', reason: 'x' }], + ['an empty reason', { disabled: true, since: '2026-10-10', reason: ' ' }], + ['a non-object', true], + ])('rejects %s', (_label, execution) => { + expect(withExecution(execution).some((failure) => failure.includes('execution'))).toBe(true); + }); +}); diff --git a/shared/nodeslide.ts b/shared/nodeslide.ts index 736a5a12..69140b95 100644 --- a/shared/nodeslide.ts +++ b/shared/nodeslide.ts @@ -88,18 +88,71 @@ export const NODESLIDE_AGENT_MODELS = [ supportsTemperature: false, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], }, + { + id: 'anthropic/claude-sonnet-5.5', + upstreamId: 'anthropic/claude-sonnet-5.5', + provider: 'openrouter', + vendor: 'Anthropic', + label: 'Claude Sonnet 5.5', + description: 'Balanced Claude for agents and professional writing.', + costTier: 'premium', + bestFor: 'Executive writing and synthesis', + productionEnabled: true, + // Sampling parameters (temperature/top_p/top_k) are a 400 on Claude 5.5. + supportsTemperature: false, + supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], + }, + { + id: 'anthropic/claude-opus-5.5', + upstreamId: 'anthropic/claude-opus-5.5', + provider: 'openrouter', + vendor: 'Anthropic', + label: 'Claude Opus 5.5', + description: 'Most capable Claude for long-running, high-stakes agent work.', + costTier: 'premium', + bestFor: 'Complex planning and review', + productionEnabled: true, + // Sampling parameters are a 400 on Claude 5.5. Opus 5.5 defaults to medium effort on the + // vendor side (Opus 5 defaulted to high; spec A.2.8 "explicit per row"), so the row carries its + // own default and every request still names an explicit reasoning.effort. + supportsTemperature: false, + supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], + defaultEffort: 'medium', + }, { id: 'google/gemini-3.5-flash', upstreamId: 'google/gemini-3.5-flash', provider: 'openrouter', vendor: 'Google', label: 'Gemini 3.5 Flash', - description: 'Latest stable Gemini for sustained agentic and coding tasks.', + description: 'Previous Gemini Flash generation; kept so persisted job requests still resolve.', costTier: 'fast', bestFor: 'Fast iteration and large context', - productionEnabled: true, + // Google deprecated gemini-3.5-flash on 2026-10-08 and auto-routes requests to 3.6, so it is no + // longer offered. The row stays because persisted job requests name it (convex validators and + // the price table keep the literal). + productionEnabled: false, supportsTemperature: true, supportedEfforts: ['low', 'medium', 'high'], + structuredOutputMode: 'json_object', + }, + { + id: 'google/gemini-3.8-flash', + upstreamId: 'google/gemini-3.8-flash', + provider: 'openrouter', + vendor: 'Google', + label: 'Gemini 3.8 Flash', + description: 'Current Gemini Flash for sustained agentic and coding tasks.', + costTier: 'fast', + bestFor: 'Fast iteration and large context', + productionEnabled: true, + // Gemini 3.6+ deprecates sampling parameters (ignored today, a future 400): never send temperature. + supportsTemperature: false, + // thinking_level is low/medium/high on Gemini 3.x Flash; xhigh and max are unsupported. + supportedEfforts: ['low', 'medium', 'high'], + // Same OpenRouter Gemini route as 3.5: the edit planner's scoped union schema is rejected + // before generation, so the edit patch uses json_object transport and is validated locally. + structuredOutputMode: 'json_object', }, { id: 'google/gemini-3.1-pro-preview', @@ -140,6 +193,40 @@ export const NODESLIDE_AGENT_MODELS = [ supportsTemperature: false, supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], }, + { + id: 'openai/gpt-6.1-sol', + upstreamId: 'openai/gpt-6.1-sol', + provider: 'openrouter', + vendor: 'OpenAI', + label: 'GPT-6.1 Sol', + description: 'OpenAI flagship for highest-capability production workflows.', + costTier: 'premium', + bestFor: 'Highest-capability production work', + productionEnabled: true, + // Sampling parameters are removed (400) on GPT-6. + supportsTemperature: false, + supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], + }, + { + // The routed copy executor (convex/lib/nodeslideRoutingPolicy.ts). SPEC "Homen decisions", NodeSlide + // executor (2026-11-06): the paid OpenRouter route, an exception to D2, the exact dated id rather + // than the deepseek-v4.1-flash alias. OpenRouter public list read 2026-11-06T10:39:31Z: created + // 2026-10-17, tools + response_format + structured_outputs + reasoning, 1,048,576 context, no + // expiration_date. Executor only: not offered in the picker until someone measures it as a planner. + id: 'deepseek/deepseek-v4.1-flash-1017', + upstreamId: 'deepseek/deepseek-v4.1-flash-1017', + provider: 'openrouter', + vendor: 'DeepSeek', + label: 'DeepSeek V4.1 Flash', + description: 'Low-cost copy executor for routed bulk text edits.', + costTier: 'fast', + bestFor: 'Routed bulk copy execution', + productionEnabled: false, + // Not sent: reasoning mode ignores sampling, and an unsent key cannot narrow the + // require_parameters endpoint set. + supportsTemperature: false, + supportedEfforts: ['low', 'medium', 'high'], + }, { id: 'openrouter/free', upstreamId: 'openrouter/free', @@ -192,8 +279,9 @@ export const NODESLIDE_AGENT_MODELS = [ description: 'Zero-priced long-context OpenRouter route with native structured output.', costTier: 'free', bestFor: 'Free long-context deck planning', + // Absent from the OpenRouter catalog (GET /api/v1/models, 2026-10-31; the paid id remains): not a + // free-router candidate any more. The row stays for persisted requests, as gpt-oss-20b:free did. productionEnabled: false, - freeRouterCandidate: true, supportsTemperature: true, supportedEfforts: ['low', 'medium', 'high'], }, @@ -206,8 +294,9 @@ export const NODESLIDE_AGENT_MODELS = [ description: 'Zero-priced OpenRouter route with native structured-output support.', costTier: 'free', bestFor: 'Free fast iteration and repair', + // Absent from the OpenRouter catalog (GET /api/v1/models, 2026-10-10): not a free-router + // candidate any more. The row stays for persisted requests and the node-gym matrix identity. productionEnabled: false, - freeRouterCandidate: true, supportsTemperature: true, supportedEfforts: ['low', 'medium', 'high'], }, @@ -225,6 +314,8 @@ export type NodeSlideExternalProvider = (typeof NODESLIDE_AGENT_MODELS)[number][ export const NODESLIDE_DEFAULT_AGENT_MODEL: NodeSlideAgentModelId = 'moonshotai/kimi-k3'; export const NODESLIDE_DEFAULT_OPENROUTER_AGENT_MODEL: NodeSlideAgentModelId = 'moonshotai/kimi-k3'; export const NODESLIDE_NEBIUS_AGENT_MODEL: NodeSlideAgentModelId = 'nebius/zai-org/GLM-5.2'; +/** Default route shown in the bring-your-own-key UI (session BYOK store and Connections dialog). */ +export const NODESLIDE_BYOK_DEFAULT_MODEL: NodeSlideAgentModelId = 'z-ai/glm-5.2'; export const NODESLIDE_REASONING_EFFORTS = [ { id: 'low', label: 'Light', description: 'Faster responses for straightforward work.' }, @@ -236,6 +327,35 @@ export const NODESLIDE_REASONING_EFFORTS = [ export type NodeSlideReasoningEffort = (typeof NODESLIDE_REASONING_EFFORTS)[number]['id']; export const NODESLIDE_DEFAULT_REASONING_EFFORT: NodeSlideReasoningEffort = 'high'; +/** + * The effort a request gets when the caller names none: the row's own `defaultEffort` when it + * declares one (Opus 5.5 = medium), otherwise NODESLIDE_DEFAULT_REASONING_EFFORT. An explicit + * caller effort is never routed through here. + */ +export function nodeSlideDefaultReasoningEffort( + modelId: NodeSlideAgentModelId, +): NodeSlideReasoningEffort { + const route = nodeSlideAgentModel(modelId); + return 'defaultEffort' in route ? route.defaultEffort : NODESLIDE_DEFAULT_REASONING_EFFORT; +} + +/** + * The effort a picker shows and sends for a model: the person's own choice when the row supports it, + * otherwise the row's default (Opus 5.5 = medium, the rest high). `chosen` is `null` until the person + * touches the effort picker (or a saved effort is restored), which is how an untouched effort follows + * the model while an explicit one, even one equal to the previous row's default, is kept. Anything + * that is not a real effort (a stale localStorage value) counts as no choice. + */ +export function nodeSlideEffortForModel( + modelId: NodeSlideAgentModelId, + chosen: unknown, +): NodeSlideReasoningEffort { + return isNodeSlideReasoningEffort(chosen) && + nodeSlideModelSupportsReasoningEffort(modelId, chosen) + ? chosen + : nodeSlideDefaultReasoningEffort(modelId); +} + export function isNodeSlideReasoningEffort(value: unknown): value is NodeSlideReasoningEffort { return NODESLIDE_REASONING_EFFORTS.some((effort) => effort.id === value); } @@ -247,6 +367,20 @@ export function nodeSlideReasoningEffort(effortId: NodeSlideReasoningEffort) { ); } +/** + * Catalog flag for the edit-patch transport. A row that sets `structuredOutputMode: 'json_object'` + * sends the `nodeslide_edit_patch` schema in the prompt and asks the provider only for strict JSON, + * because that route rejects the planner's large scoped union before generating a token. Every other + * schema, and every row without the flag, keeps native `json_schema`. The result is validated + * locally against the same schema either way. + */ +export function nodeSlideEditPatchStructuredOutputMode( + modelId: NodeSlideAgentModelId, +): 'json_object' | undefined { + const route = nodeSlideAgentModel(modelId); + return 'structuredOutputMode' in route ? route.structuredOutputMode : undefined; +} + export function isNodeSlideAgentModelId(value: unknown): value is NodeSlideAgentModelId { return NODESLIDE_AGENT_MODELS.some((model) => model.id === value); } @@ -255,8 +389,64 @@ export function isNodeSlideOfferedAgentModelId(value: unknown): value is NodeSli return NODESLIDE_OFFERED_AGENT_MODELS.some((model) => model.id === value); } +/** The verified free constant a free-looking unknown id resolves to (Part A rule 10). */ +const NODESLIDE_FREE_FALLBACK_MODEL_ID = 'openrouter/free' as const; + +/** + * The `:free` ids SPEC section 1.2 verified live on OpenRouter (2026-10-10). They are known ids: one the + * catalog does not serve is refused, never rerouted to the free router (SPEC D1). + */ +const NODESLIDE_VERIFIED_FREE_MODEL_IDS: ReadonlySet = new Set([ + 'apodex/apodex-1.1-mini:free', + 'dots-studio/dots-3-note-preview:free', + 'liquid/lfm-2.5-2.6b:free', + 'nvidia/nemotron-3.5-lightning:free', + 'thinkingmachines/inkling-small:free', + 'poolside/laguna-s-2.1:free', + 'thinkingmachines/inkling:free', + 'poolside/laguna-xs-2.1:free', + 'cohere/north-mini-code:free', + 'nvidia/nemotron-3.5-content-safety:free', + 'nvidia/nemotron-3-ultra-550b-a55b:free', + 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free', + 'google/gemma-4-26b-a4b-it:free', + 'google/gemma-4-31b-it:free', + 'nvidia/nemotron-3-super-120b-a12b:free', + // OpenRouter recheck 2026-10-31 (SPEC 1.2 supersession): listed on the public list (live-unverified), and + // pi-ai has no row for it, so a caller-supplied id must refuse rather than fall to the free router. + 'recursive/flint-v1.0:free', +]); + +export function isNodeSlideVerifiedFreeModelId(value: unknown): boolean { + return typeof value === 'string' && NODESLIDE_VERIFIED_FREE_MODEL_IDS.has(value); +} + +/** + * Resolves a catalog id to its route. Cost class is preserved and an unknown id fails closed: an id + * the catalog does not carry never becomes a paid default (it used to resolve to the first row, the + * paid Nebius GLM route). A SPEC 1.2 verified free id the catalog does not serve throws (a known id is + * never rerouted). A free-looking id in neither the catalog nor SPEC 1.2 (`:free` or `-free` suffix) + * resolves to the free router row; every other unknown throws. The public Convex validators and + * `isNodeSlideAgentModelId` reject such ids at the API boundary first. + */ export function nodeSlideAgentModel(modelId: NodeSlideAgentModelId) { - return NODESLIDE_AGENT_MODELS.find((model) => model.id === modelId) ?? NODESLIDE_AGENT_MODELS[0]; + const route = NODESLIDE_AGENT_MODELS.find((model) => model.id === modelId); + if (route) return route; + if (isNodeSlideVerifiedFreeModelId(modelId)) { + throw new Error( + `NodeSlide model "${String(modelId)}" is a verified free id but is not in the catalog; it is not rerouted.`, + ); + } + if ( + typeof modelId === 'string' && + ((modelId as string).endsWith(':free') || (modelId as string).endsWith('-free')) + ) { + const free = NODESLIDE_AGENT_MODELS.find( + (model) => model.id === NODESLIDE_FREE_FALLBACK_MODEL_ID, + ); + if (free) return free; + } + throw new Error(`Unknown NodeSlide model "${String(modelId)}": it is not in the catalog.`); } export function nodeSlideModelSupportsReasoningEffort( diff --git a/shared/nodeslideRunBudget.ts b/shared/nodeslideRunBudget.ts index 54bb7712..c235eae0 100644 --- a/shared/nodeslideRunBudget.ts +++ b/shared/nodeslideRunBudget.ts @@ -25,6 +25,9 @@ import type { NodeSlideAgentModelId } from './nodeslide'; export const NODESLIDE_RUN_BUDGET_VERSION = 'nodeslide.run-budget/v1' as const; export const NODESLIDE_RUN_BUDGET_STATE_VERSION = 'nodeslide.run-budget-state/v1' as const; export const NODESLIDE_RUN_BUDGET_RECEIPT_VERSION = 'nodeslide.run-budget-receipt/v1' as const; +/** Run-level read model of one budget ledger row (`nodeslideBudgets.receiptForRun`). */ +export const NODESLIDE_RUN_BUDGET_LEDGER_RECEIPT_VERSION = + 'nodeslide.run-budget-ledger-receipt/v1' as const; export const NODESLIDE_MODEL_PRICING_VERSION = 'nodeslide.model-pricing/v1' as const; export const NODESLIDE_PRIVATE_DETERMINISTIC_MODEL = 'nodeslide/private-deterministic' as const; export const NODESLIDE_MICRO_USD_PER_USD = 1_000_000 as const; @@ -261,8 +264,10 @@ export interface NodeSlidePricedModelMetadata { readonly providerContextWindowTokens: number; readonly providerMaxOutputTokens: number; readonly source: 'openrouter_model_catalog_api'; - readonly sourceUrl: typeof NODESLIDE_MODEL_PRICING_SOURCE_URL; - readonly verifiedAt: typeof NODESLIDE_MODEL_PRICING_VERIFIED_AT; + /** Where this row's price was read: the /models listing, or a held row's endpoints evidence. */ + readonly sourceUrl: string; + /** When the price in this row was verified; a held row carries its own date, not the listing's. */ + readonly verifiedAt: string; } export interface NodeSlideZeroCostModelMetadata { @@ -475,7 +480,20 @@ export type NodeSlideRunBudgetPostflightResult = * SOURCE: https://openrouter.ai/api/v1/models — the provider's own machine * catalog, not a docs page, not a pricing page, not a paste from a * conversation. Every row below was read out of one response body. - * FETCHED: 2026-07-28T00:00:00Z (see NODESLIDE_MODEL_PRICING_VERIFIED_AT). + * FETCHED: 2026-10-14T16:03:00Z (see NODESLIDE_MODEL_PRICING_VERIFIED_AT). The four rows + * added by the model refresh, and gpt-5.6-terra, were read from that one response. + * moonshotai/kimi-k3, z-ai/glm-5.2 and openai/gpt-5.6-sol were re-read and + * deliberately NOT moved off the values they had on main (see their rows). Those + * three rows are not what that response published, so they carry their own + * `verifiedAt` (NODESLIDE_HELD_PRICE_VERIFIED_AT, 2026-10-15T23:08Z) and the + * per-route endpoints URL that verified them, not the listing's date and URL. + * The price below is ALSO the `max_price` routing ceiling sent to OpenRouter + * (`nodeslideBudgetedProvider.ts`), so it bounds both the reservation and the + * bill. The /models listing price is the cheapest endpoint's, so a row copied + * from it can sit below most live endpoints and leave a route with one to three + * providers, or none: each row is therefore checked against + * GET /api/v1/models/{id}/endpoints, and the endpoint count at or below the + * ceiling is part of the evidence for changing one. * UNIT: `pricing.prompt` / `pricing.completion` are USD per single token. * This table stores integer micro-USD per MILLION tokens, so every * value is the catalog string multiplied by 1e12. Integers only: the @@ -483,10 +501,10 @@ export type NodeSlideRunBudgetPostflightResult = * reservation, which is the one place rounding down is a loan. * WINDOWS: `providerContextWindowTokens` is `context_length`; * `providerMaxOutputTokens` is `top_provider.max_completion_tokens`. - * Where the catalog reports `null` for the completion cap — currently - * `moonshotai/kimi-k3` only — the context window is the binding - * provider limit and is recorded as such. That is read from the same - * response, not assumed. + * Where the catalog reports `null` for the completion cap (no row does + * in the 2026-10-14 response; `moonshotai/kimi-k3` did on 2026-07-28) the + * context window is the binding provider limit and is recorded as such. + * That is read from the same response, not assumed. * * TO RE-VERIFY: fetch the URL, and for each row assert * `pricing.prompt * 1e12 === inputMicroUsdPerMillionTokens` and the same for @@ -509,7 +527,24 @@ export type NodeSlideRunBudgetPostflightResult = * fallback rather than billing against an unchecked price. */ export const NODESLIDE_MODEL_PRICING_SOURCE_URL = 'https://openrouter.ai/api/v1/models' as const; -export const NODESLIDE_MODEL_PRICING_VERIFIED_AT = '2026-07-28T00:00:00Z' as const; +export const NODESLIDE_MODEL_PRICING_VERIFIED_AT = '2026-10-14T16:03:00Z' as const; +/** + * The three held rows (kimi-k3, glm-5.2, gpt-5.6-sol) keep main's 2026-07-28 values, which the + * 2026-10-14 listing did not publish. What verified them is the endpoint check below, so that is + * the date and the source their rows carry (SPEC D3, Homen 2026-10-16). + */ +export const NODESLIDE_HELD_PRICE_VERIFIED_AT = '2026-10-15T23:08:00Z' as const; +/** + * The executor row (deepseek/deepseek-v4.1-flash-1017, SPEC "Homen decisions" 2026-11-06) was added + * after the 2026-10-14 listing; it was read from https://openrouter.ai/api/v1/models at this instant + * and its ceiling checked against GET /api/v1/models/deepseek/deepseek-v4.1-flash-1017/endpoints in the + * same minute, so its row carries this date, not the 2026-10-14 one. + */ +export const NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT = '2026-11-06T10:39:31Z' as const; +const heldPriceEvidence = (modelId: string) => ({ + sourceUrl: `${NODESLIDE_MODEL_PRICING_SOURCE_URL}/${modelId}/endpoints`, + verifiedAt: NODESLIDE_HELD_PRICE_VERIFIED_AT, +}); type NodeSlideCatalogPricingMetadata = | NodeSlidePricedModelMetadata @@ -522,16 +557,19 @@ function pricedRoute(args: { outputMicroUsdPerMillionTokens: number; providerContextWindowTokens: number; providerMaxOutputTokens: number; + /** Set only on a row whose price is not the 2026-10-14 listing's (the held rows, the executor). */ + evidence?: { sourceUrl: string; verifiedAt: string }; }): NodeSlidePricedModelMetadata { + const { evidence, ...row } = args; return { version: NODESLIDE_MODEL_PRICING_VERSION, kind: 'priced', currency: 'USD', billingUnit: 'million_tokens', source: 'openrouter_model_catalog_api', - sourceUrl: NODESLIDE_MODEL_PRICING_SOURCE_URL, - verifiedAt: NODESLIDE_MODEL_PRICING_VERIFIED_AT, - ...args, + sourceUrl: evidence?.sourceUrl ?? NODESLIDE_MODEL_PRICING_SOURCE_URL, + verifiedAt: evidence?.verifiedAt ?? NODESLIDE_MODEL_PRICING_VERIFIED_AT, + ...row, }; } @@ -565,8 +603,15 @@ export const NODESLIDE_MODEL_PRICING = { reason: 'provider_pricing_not_pinned', source: 'nebius_private_catalog', }, + // Held at main's ceiling, not the /models listing (0.7 / 15 on 2026-10-14; 0.45 / 16.5 on + // 2026-10-15; the spec's 0.64 / 13.5). This is the production default, and the listing is the + // cheapest endpoint's price: as `max_price` 0.7 / 15 admitted 3 of 25 endpoints on 2026-10-15 + // (2 with structured_outputs, which `require_parameters` demands), 0.64 / 13.5 admitted 0, and + // main's 3 / 15 admits 21 of 25 (18 with structured_outputs; GET /api/v1/models/moonshotai/kimi-k3/endpoints, + // 2026-10-15 23:08 UTC). Window and output cap are main's too. 'moonshotai/kimi-k3': pricedRoute({ modelId: 'moonshotai/kimi-k3', + evidence: heldPriceEvidence('moonshotai/kimi-k3'), inputMicroUsdPerMillionTokens: 3_000_000, outputMicroUsdPerMillionTokens: 15_000_000, providerContextWindowTokens: 1_048_576, @@ -574,8 +619,16 @@ export const NODESLIDE_MODEL_PRICING = { // route, so the context window is the provider's binding output limit. providerMaxOutputTokens: 1_048_576, }), + // Held at main's ceiling, not the /models listing (0.05 / 7 on 2026-10-14, 0.65 / 10 on + // 2026-10-15). Used as `max_price`, 0.05 / 7 admitted 0 of 33 endpoints at about 18:30 and 18:49 UTC + // on 2026-10-15 and 2 of 33 (1 with structured_outputs, Wafer) at 22:35 and 23:00 UTC, so the + // route flaps between unroutable and one provider. Main's 0.7686 / 2.4156 admits 6 of 33 (4 with + // structured_outputs: DeepInfra, StreamLake, Baidu, DigitalOcean; GET /api/v1/models/z-ai/glm-5.2/endpoints, + // 2026-10-15 23:08 UTC). Window and output cap are main's too: those endpoints cap completions at + // 128,000-262,144, not the listing's 943,718. 'z-ai/glm-5.2': pricedRoute({ modelId: 'z-ai/glm-5.2', + evidence: heldPriceEvidence('z-ai/glm-5.2'), inputMicroUsdPerMillionTokens: 768_600, outputMicroUsdPerMillionTokens: 2_415_600, providerContextWindowTokens: 1_048_576, @@ -595,6 +648,20 @@ export const NODESLIDE_MODEL_PRICING = { providerContextWindowTokens: 1_000_000, providerMaxOutputTokens: 128_000, }), + 'anthropic/claude-sonnet-5.5': pricedRoute({ + modelId: 'anthropic/claude-sonnet-5.5', + inputMicroUsdPerMillionTokens: 2_000_000, + outputMicroUsdPerMillionTokens: 10_000_000, + providerContextWindowTokens: 1_000_000, + providerMaxOutputTokens: 128_000, + }), + 'anthropic/claude-opus-5.5': pricedRoute({ + modelId: 'anthropic/claude-opus-5.5', + inputMicroUsdPerMillionTokens: 4_000_000, + outputMicroUsdPerMillionTokens: 20_000_000, + providerContextWindowTokens: 1_000_000, + providerMaxOutputTokens: 128_000, + }), 'google/gemini-3.5-flash': pricedRoute({ modelId: 'google/gemini-3.5-flash', inputMicroUsdPerMillionTokens: 1_500_000, @@ -602,6 +669,18 @@ export const NODESLIDE_MODEL_PRICING = { providerContextWindowTokens: 1_048_576, providerMaxOutputTokens: 65_536, }), + // Introductory price (SPEC 1.3): Google doubles it to 1.50 / 7.50 on 2027-01-01. This row is both the + // reservation quote and the OpenRouter max_price ceiling, so once the doubled price is listed this + // ceiling admits 0 endpoints and the executor and the 3.8 picker row fail closed (no overspend, but the + // split is unavailable). Follow-up on 2027-01-01: re-read /api/v1/models/google/gemini-3.8-flash/endpoints, + // raise this row and its pricing test together, and re-check the 0.55 USD probe cap. + 'google/gemini-3.8-flash': pricedRoute({ + modelId: 'google/gemini-3.8-flash', + inputMicroUsdPerMillionTokens: 750_000, + outputMicroUsdPerMillionTokens: 3_750_000, + providerContextWindowTokens: 1_048_576, + providerMaxOutputTokens: 65_536, + }), 'google/gemini-3.1-pro-preview': pricedRoute({ modelId: 'google/gemini-3.1-pro-preview', inputMicroUsdPerMillionTokens: 2_000_000, @@ -609,8 +688,12 @@ export const NODESLIDE_MODEL_PRICING = { providerContextWindowTokens: 1_048_576, providerMaxOutputTokens: 65_536, }), + // Held at main's ceiling. OpenRouter's listed price moved from 2 / 10 to 4 / 20 on 2026-10-15, so + // 2 / 10 admitted 1 of 7 endpoints (OpenAI) where main's 5 / 30 admits 6 of 7 (all 6 with + // structured_outputs; GET /api/v1/models/openai/gpt-5.6-sol/endpoints, 2026-10-15 23:08 UTC). 'openai/gpt-5.6-sol': pricedRoute({ modelId: 'openai/gpt-5.6-sol', + evidence: heldPriceEvidence('openai/gpt-5.6-sol'), inputMicroUsdPerMillionTokens: 5_000_000, outputMicroUsdPerMillionTokens: 30_000_000, providerContextWindowTokens: 1_050_000, @@ -618,8 +701,36 @@ export const NODESLIDE_MODEL_PRICING = { }), 'openai/gpt-5.6-terra': pricedRoute({ modelId: 'openai/gpt-5.6-terra', - inputMicroUsdPerMillionTokens: 1_250_000, - outputMicroUsdPerMillionTokens: 7_500_000, + inputMicroUsdPerMillionTokens: 2_000_000, + outputMicroUsdPerMillionTokens: 12_000_000, + providerContextWindowTokens: 1_050_000, + providerMaxOutputTokens: 128_000, + }), + // The routed copy executor (SPEC "Homen decisions", 2026-11-06). Source: https://openrouter.ai/api/v1/models + // fetched 2026-11-06T10:39:31Z: pricing.prompt 0.00000015, pricing.completion 0.0000006 ($0.15 in / + // $0.60 out per M), context_length 1,048,576, top_provider.max_completion_tokens 393,216. The listing + // also carries weekday time-of-day overrides (DeepSeek's own endpoint doubles to 0.30 / 1.20 at + // 01:00-04:00 and 06:00-10:00 UTC). This row is the base price and, as for every row, the OpenRouter + // max_price ceiling: OpenRouter never bills above it, and at peak only DeepSeek's own endpoint drops + // out (as a ceiling it admitted 17 of 50 endpoints at every hour, 16 with structured_outputs; + // GET /api/v1/models/deepseek/deepseek-v4.1-flash-1017/endpoints, same minute). + 'deepseek/deepseek-v4.1-flash-1017': pricedRoute({ + modelId: 'deepseek/deepseek-v4.1-flash-1017', + evidence: { + sourceUrl: NODESLIDE_MODEL_PRICING_SOURCE_URL, + verifiedAt: NODESLIDE_EXECUTOR_PRICE_VERIFIED_AT, + }, + inputMicroUsdPerMillionTokens: 150_000, + outputMicroUsdPerMillionTokens: 600_000, + providerContextWindowTokens: 1_048_576, + providerMaxOutputTokens: 393_216, + }), + // Priced at the flat tier. OpenRouter lists a higher tier above 272K prompt tokens + // (2x input); a NodeSlide prompt is bounded far below that by the read-context limit. + 'openai/gpt-6.1-sol': pricedRoute({ + modelId: 'openai/gpt-6.1-sol', + inputMicroUsdPerMillionTokens: 2_000_000, + outputMicroUsdPerMillionTokens: 10_000_000, providerContextWindowTokens: 1_050_000, providerMaxOutputTokens: 128_000, }), @@ -679,6 +790,36 @@ export function nodeSlideModelPricing(model: string): NodeSlideModelPricingMetad }; } +/** + * Re-prices a provider catalog row (USD per million tokens, the shape pi-ai uses) at the ledger's + * rate. The ledger is the repo's price of record and the reservation quote is computed from it, so + * every dispatcher that turns a response into dollars must agree with it or a valid response can + * settle above the quote it was reserved at. + * + * Input and output take the ledger's rate. The cached-read rate is capped at the ledger's input + * rate, because the quote prices every input token at that rate and a cached token is never worth + * more than an uncached one (on 2026-10-14 pi-ai's glm-5.2 row carried cacheRead 0.162 against a + * ledger input of 0.05, 3.24x; the ledger input is 0.7686 now, so no row binds today and the cap is + * the guard for the day a ledger row falls below its cached rate). The cache-write + * rate is left alone: Claude and GPT rows bill writes at 1.25x input, which the quote covers because + * its input estimate is at least MAX_PROVIDER_ATTEMPTS (2x) the bytes actually sent (asserted in + * convex/nodeslideModelPricing.test.ts). Rows the ledger does not price (free, dynamic, unknown) are + * returned untouched. + */ +export function nodeSlideLedgerPricedCost< + Cost extends { input: number; output: number; cacheRead: number }, +>(model: string, cost: Cost): Cost { + const pricing = nodeSlideModelPricing(model); + if (pricing.kind !== 'priced') return cost; + const input = pricing.inputMicroUsdPerMillionTokens / 1_000_000; + return { + ...cost, + input, + output: pricing.outputMicroUsdPerMillionTokens / 1_000_000, + cacheRead: Math.min(cost.cacheRead, input), + }; +} + /** True only for pricing a reservation can actually be computed from. */ export function isNodeSlideScoredPricing( pricing: NodeSlideModelPricingMetadata, diff --git a/src/domains/nodeslide/components/NodeSlideConnectionsDialog.tsx b/src/domains/nodeslide/components/NodeSlideConnectionsDialog.tsx index 93f70d62..bacf3646 100644 --- a/src/domains/nodeslide/components/NodeSlideConnectionsDialog.tsx +++ b/src/domains/nodeslide/components/NodeSlideConnectionsDialog.tsx @@ -17,6 +17,7 @@ import { } from 'lucide-react'; import { useEffect, useRef, useState } from 'react'; import { api } from '../../../../convex/_generated/api'; +import { NODESLIDE_BYOK_DEFAULT_MODEL } from '../../../../shared/nodeslide'; import { SESSION_BYOK_KEYS, clearSessionByok, @@ -88,7 +89,10 @@ function NodeSlideConnectionsDialogContent({ initialFocusRef: firstInputRef, }); const [keys, setKeys] = useState>({}); - const [routing, setRouting] = useState({ model: 'z-ai/glm-5.2', baseUrl: '' }); + const [routing, setRouting] = useState<{ model: string; baseUrl: string }>({ + model: NODESLIDE_BYOK_DEFAULT_MODEL, + baseUrl: '', + }); const [client, setClient] = useState('claude'); const [notice, setNotice] = useState(null); const [googleBusy, setGoogleBusy] = useState<'connect' | 'disconnect' | null>(null); @@ -144,7 +148,7 @@ function NodeSlideConnectionsDialogContent({ const revoke = () => { clearSessionByok(); setKeys({}); - setRouting({ model: 'z-ai/glm-5.2', baseUrl: '' }); + setRouting({ model: NODESLIDE_BYOK_DEFAULT_MODEL, baseUrl: '' }); setNotice('Local connection values revoked from this tab.'); }; @@ -222,7 +226,7 @@ function NodeSlideConnectionsDialogContent({ ...env, PARITY_CONVEX_URL: NODESLIDE_CONVEX_URL, PARITY_DASHBOARD: 'disabled', - NODESLIDE_BYOK_MODEL: routing.model.trim() || 'z-ai/glm-5.2', + NODESLIDE_BYOK_MODEL: routing.model.trim() || NODESLIDE_BYOK_DEFAULT_MODEL, ...(routing.baseUrl.trim() ? { NODESLIDE_BYOK_BASE_URL: routing.baseUrl.trim() } : {}), ...(ownerAccessKey ? { NODESLIDE_OWNER_ACCESS_KEY: ownerAccessKey } : {}), }; @@ -584,7 +588,7 @@ function NodeSlideConnectionsDialogContent({ onChange={(event) => setRouting((current) => ({ ...current, model: event.target.value })) } - placeholder="z-ai/glm-5.2" + placeholder={NODESLIDE_BYOK_DEFAULT_MODEL} />