diff --git a/.changeset/routing-run-observation.md b/.changeset/routing-run-observation.md new file mode 100644 index 00000000000..3230e0b631a --- /dev/null +++ b/.changeset/routing-run-observation.md @@ -0,0 +1,5 @@ +--- +"gh-aw": minor +--- + +Record whether a routed run's result can teach a router anything. For each run that AWF routed and whose agent made requests, the conclusion job's unified session now records a `routing.observation` verdict: `success` or `failure` when the result counts as evidence about the model and effort AWF selected, or `skip` with the reason it does not (`cancelled`, `infrastructure`, `rate_limited`, `pair_mismatch`, or `unknown_evidence`). The verdict uses only AWF's request records, the job results and the validated safe outputs, so it works for every engine. The selected pair and its cost stay in the AWF records the session already holds. `gh aw audit` and `gh aw logs --json` show the verdict. diff --git a/actions/setup/js/collect_ndjson_output.cjs b/actions/setup/js/collect_ndjson_output.cjs index 4e6bb55de07..1e98e23032e 100644 --- a/actions/setup/js/collect_ndjson_output.cjs +++ b/actions/setup/js/collect_ndjson_output.cjs @@ -198,6 +198,7 @@ async function main() { core.info(`[INGESTION] Output file path: ${outputFile}`); const collectionErrors = []; + let collectorInfrastructureCause; if (!outputFile || !fs.existsSync(outputFile)) { core.info(outputFile ? `Output file does not exist: ${outputFile}` : "GH_AW_SAFE_OUTPUTS not set, no output to collect"); const runnerTemp = process.env.RUNNER_TEMP || "/home/runner/work/_temp"; @@ -208,6 +209,7 @@ async function main() { `This is a gateway infrastructure failure, not a normal no-op. ` + `Check the MCP gateway startup logs for ECONNRESET errors or delayed backend registration and re-run the workflow.`; collectionErrors.push(reason); + collectorInfrastructureCause = "safeoutputs_gateway_empty"; // eslint-disable-next-line gh-aw-custom/require-return-after-core-setfailed core.setFailed(reason); } @@ -432,6 +434,7 @@ async function main() { ...(collectorDriverExitCode !== undefined ? { collectorDriverExitCode } : {}), ...(collectorRetryCount !== undefined ? { collectorRetryCount } : {}), ...(collectorEngineErrorType ? { collectorEngineErrorType } : {}), + ...(collectorInfrastructureCause ? { collectorInfrastructureCause } : {}), }; const path = require("path"); const agentOutputFile = path.join(TMP_GH_AW_PATH, AGENT_OUTPUT_FILENAME); diff --git a/actions/setup/js/collect_ndjson_output.test.cjs b/actions/setup/js/collect_ndjson_output.test.cjs index c86ac5efef0..92934cb294f 100644 --- a/actions/setup/js/collect_ndjson_output.test.cjs +++ b/actions/setup/js/collect_ndjson_output.test.cjs @@ -262,6 +262,7 @@ describe("collect_ndjson_output.cjs", () => { const output = JSON.parse(mockCore.setOutput.mock.calls.find(call => call[0] === "output")[1]); expect(output.items[0].type).toBe("report_incomplete"); expect(output.items[0].details).toContain("Safe-output tools: unavailable (gateway registered zero tools)"); + expect(output.collectorInfrastructureCause).toBe("safeoutputs_gateway_empty"); expect(fs.existsSync(path.join(TMP_GH_AW_PATH, AGENT_OUTPUT_FILENAME))).toBe(true); } finally { if (originalRunnerTemp === undefined) { diff --git a/actions/setup/js/fixtures/routing-analytics/run-39147795806/agent_output.json b/actions/setup/js/fixtures/routing-analytics/run-39147795806/agent_output.json new file mode 100644 index 00000000000..c87b62d0e7c --- /dev/null +++ b/actions/setup/js/fixtures/routing-analytics/run-39147795806/agent_output.json @@ -0,0 +1 @@ +{ "items": [{ "type": "create_issue" }], "errors": [] } diff --git a/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/model-routing.jsonl b/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/model-routing.jsonl new file mode 100644 index 00000000000..dd5674c8a00 --- /dev/null +++ b/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/model-routing.jsonl @@ -0,0 +1,6 @@ +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:05:38.963Z","event":"model_routing","stage":"classification","purpose":"routing_classification","attempt":1,"classifier_model":"github-copilot/gpt-5.6-luna","classifier_effort":"high"} +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:05:45.104Z","event":"model_routing","stage":"selection","objective":{"goal":"cost","mode":"economy"},"provider":"copilot","selected_provider":"copilot","wire_model":"gpt-5.6-luna","endpoint":"/responses","labels":{"task_type":"chore","scope":"cross_system","task_complexity":"trivial"},"mode":"economy","classifier_model":"github-copilot/gpt-5.6-luna","classifier_effort":"high","router":{"name":"gh-aw-router","version":"0.1.3"},"ranked_choices":[{"model":"github-copilot/gpt-5.6-luna","effort":"max"},{"model":"github-copilot/gpt-5.6-luna","effort":"xhigh"},{"model":"github-copilot/gpt-5.6-luna","effort":"high"},{"model":"github-copilot/gpt-5.6-luna","effort":"medium"},{"model":"github-copilot/gpt-5.4-mini","effort":"xhigh"},{"model":"github-copilot/gpt-5.4-mini","effort":"high"},{"model":"github-copilot/gpt-5.4-mini","effort":"medium"},{"model":"github-copilot/gpt-5.6-luna","effort":"low"},{"model":"github-copilot/gpt-5.4-mini","effort":"low"},{"model":"github-copilot/claude-haiku-4.5","effort":null},{"model":"github-copilot/gpt-5.6-luna","effort":"none"},{"model":"github-copilot/gpt-5.4-mini","effort":"none"}],"conversation_sha256":"7af299df550a5bfe2ae9f80ccae3e5cb3a68c7d60b5b0c159f727ef364241498","selected_id":"choice-0009","selected_model":"github-copilot/gpt-5.6-luna","selected_effort":"max","degraded_classification":false,"degraded_reason":null,"classifier_attempts":1,"eligible_choices":12,"catalogue_overlap":12,"latency_ms":6156,"interaction_id":"39147795806-1","github_repository":"github/gh-aw","github_workflow_ref":"github/gh-aw/.github/workflows/smoke-copilot-routed.lock.yml@refs/heads/main"} +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:05:56.986Z","event":"model_routing","stage":"request","routed":"as_selected","deviations":[],"unavailable":[],"method":"POST","pathname":"/responses","provider":"copilot","requested_model":"gpt-5.6-luna","requested_effort":"max","selected_provider":"copilot","selected_model":"gpt-5.6-luna","selected_effort":"max","selected_endpoint":"/responses","requested_endpoint":"/responses","upstream_endpoint":"/responses","request_id":"350154af-d6ed-4d8c-b176-b93da7144bdd","outcome":"completed","status":200} +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:05:58.589Z","event":"model_routing","stage":"request","routed":"as_selected","deviations":[],"unavailable":[],"method":"POST","pathname":"/responses","provider":"copilot","requested_model":"gpt-5.6-luna","requested_effort":"max","selected_provider":"copilot","selected_model":"gpt-5.6-luna","selected_effort":"max","selected_endpoint":"/responses","requested_endpoint":"/responses","upstream_endpoint":"/responses","request_id":"79b45ef3-a365-4e5e-9e39-89c48698f37e","outcome":"completed","status":200} +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:06:01.270Z","event":"model_routing","stage":"request","routed":"as_selected","deviations":[],"unavailable":[],"method":"POST","pathname":"/responses","provider":"copilot","requested_model":"gpt-5.6-luna","requested_effort":"max","selected_provider":"copilot","selected_model":"gpt-5.6-luna","selected_effort":"max","selected_endpoint":"/responses","requested_endpoint":"/responses","upstream_endpoint":"/responses","request_id":"c2453852-d56d-4964-b514-3536a525afda","outcome":"completed","status":200} +{"_schema":"model-routing/v0.28.62","timestamp":"2026-10-18T17:06:05.354Z","event":"model_routing","stage":"request","routed":"as_selected","deviations":[],"unavailable":[],"method":"POST","pathname":"/responses","provider":"copilot","requested_model":"gpt-5.6-luna","requested_effort":"max","selected_provider":"copilot","selected_model":"gpt-5.6-luna","selected_effort":"max","selected_endpoint":"/responses","requested_endpoint":"/responses","upstream_endpoint":"/responses","request_id":"8fcd367d-53d6-48ac-b56f-620c1a1a6a80","outcome":"completed","status":200} diff --git a/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl b/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl new file mode 100644 index 00000000000..4f7166c6bb2 --- /dev/null +++ b/actions/setup/js/fixtures/routing-analytics/run-39147795806/sandbox/firewall/logs/api-proxy-logs/token-usage.jsonl @@ -0,0 +1,5 @@ +{"_schema":"token-usage/v0.28.62","timestamp":"2026-10-18T17:05:45.096Z","event":"token_usage","request_id":"78a3c387-fe05-4ad8-9e8a-ccd5806dc19c","provider":"copilot","model":"gpt-5.6-luna","path":"/responses","status":200,"streaming":false,"input_tokens":941,"output_tokens":549,"cache_read_tokens":0,"cache_write_tokens":0,"duration_ms":6129,"response_bytes":20133,"purpose":"routing_classification","x_initiator":"agent","ai_credits_this_response":0.0847,"ai_credits_total":0.0847,"ai_credits_pricing_source":"provider","ai_credits_pricing_tier":"default","ai_credits_accounting_policy":"concrete_model","ai_credits_fallback_pricing_used":false,"ai_credits_pricing_observed_at":"2026-10-18T17:05:38.926Z","ai_credits_pricing_api_version":"2026-07-01"} +{"_schema":"token-usage/v0.28.62","timestamp":"2026-10-18T17:05:56.985Z","event":"token_usage","request_id":"350154af-d6ed-4d8c-b176-b93da7144bdd","provider":"copilot","model":"gpt-5.6-luna","path":"/responses","status":200,"streaming":true,"input_tokens":23197,"output_tokens":400,"cache_read_tokens":0,"cache_write_tokens":0,"duration_ms":6725,"response_bytes":237349,"x_initiator":"user","ai_credits_this_response":0.51194,"ai_credits_total":0.59664,"ai_credits_pricing_source":"provider","ai_credits_pricing_tier":"default","ai_credits_accounting_policy":"concrete_model","ai_credits_fallback_pricing_used":false,"ai_credits_pricing_observed_at":"2026-10-18T17:05:38.926Z","ai_credits_pricing_api_version":"2026-07-01"} +{"_schema":"token-usage/v0.28.62","timestamp":"2026-10-18T17:05:58.589Z","event":"token_usage","request_id":"79b45ef3-a365-4e5e-9e39-89c48698f37e","provider":"copilot","model":"gpt-5.6-luna","path":"/responses","status":200,"streaming":true,"input_tokens":23799,"output_tokens":45,"cache_read_tokens":23194,"cache_write_tokens":0,"duration_ms":1536,"response_bytes":225482,"x_initiator":"agent","ai_credits_this_response":0.063888,"ai_credits_total":0.660528,"ai_credits_pricing_source":"provider","ai_credits_pricing_tier":"default","ai_credits_accounting_policy":"concrete_model","ai_credits_fallback_pricing_used":false,"ai_credits_pricing_observed_at":"2026-10-18T17:05:38.926Z","ai_credits_pricing_api_version":"2026-07-01"} +{"_schema":"token-usage/v0.28.62","timestamp":"2026-10-18T17:06:01.270Z","event":"token_usage","request_id":"c2453852-d56d-4964-b514-3536a525afda","provider":"copilot","model":"gpt-5.6-luna","path":"/responses","status":200,"streaming":true,"input_tokens":23870,"output_tokens":196,"cache_read_tokens":23796,"cache_write_tokens":0,"duration_ms":2614,"response_bytes":261689,"x_initiator":"agent","ai_credits_this_response":0.072592,"ai_credits_total":0.73312,"ai_credits_pricing_source":"provider","ai_credits_pricing_tier":"default","ai_credits_accounting_policy":"concrete_model","ai_credits_fallback_pricing_used":false,"ai_credits_pricing_observed_at":"2026-10-18T17:05:38.926Z","ai_credits_pricing_api_version":"2026-07-01"} +{"_schema":"token-usage/v0.28.62","timestamp":"2026-10-18T17:06:05.354Z","event":"token_usage","request_id":"8fcd367d-53d6-48ac-b56f-620c1a1a6a80","provider":"copilot","model":"gpt-5.6-luna","path":"/responses","status":200,"streaming":true,"input_tokens":24084,"output_tokens":109,"cache_read_tokens":23867,"cache_write_tokens":0,"duration_ms":3844,"response_bytes":298553,"x_initiator":"agent","ai_credits_this_response":0.065154,"ai_credits_total":0.798274,"ai_credits_pricing_source":"provider","ai_credits_pricing_tier":"default","ai_credits_accounting_policy":"concrete_model","ai_credits_fallback_pricing_used":false,"ai_credits_pricing_observed_at":"2026-10-18T17:05:38.926Z","ai_credits_pricing_api_version":"2026-07-01"} diff --git a/actions/setup/js/fixtures/routing_analytics_runs.cjs b/actions/setup/js/fixtures/routing_analytics_runs.cjs index 06c40772bac..4fdb70235b1 100644 --- a/actions/setup/js/fixtures/routing_analytics_runs.cjs +++ b/actions/setup/js/fixtures/routing_analytics_runs.cjs @@ -28,6 +28,11 @@ * https://github.com/github/gh-aw/actions/runs/39499464895 (usage 12300520074, * agent 12298393979). Selected claude-haiku-4.5, then failed closed: * `mini-whoami` requested unavailable gpt-5.4-mini. + * - run-39147795806: Smoke Copilot Routed, AWF v0.28.62, + * https://github.com/github/gh-aw/actions/runs/39147795806/attempts/1. Selected + * gpt-5.6-luna at max; four main requests and one classifier request. It keeps + * only the api-proxy logs and `agent_output.json`, reduced to its item types: + * the agent created its required report, but a later check failed its job. * * `routing-analytics/awf-10211/` holds records produced by the gh-aw-firewall * writers at b5c683e116470e0aa579ec9bf30a675fcdb66f76 (github/gh-aw-firewall#10211) diff --git a/actions/setup/js/routing_analytics.cjs b/actions/setup/js/routing_analytics.cjs index f0fed89d671..e2f99cb438f 100644 --- a/actions/setup/js/routing_analytics.cjs +++ b/actions/setup/js/routing_analytics.cjs @@ -249,6 +249,40 @@ function matchesDeclaredSubAgent(requested, provider, declarations) { }); } +/** + * AWF's per-request routing records by request ID. Conflicting records for one + * request are ambiguous and map to null. + * @param {unknown[]} routing firewall.model_routing records + * @returns {Map | null>} + */ +function routedRequests(routing) { + /** @type {Map | null>} */ + const requests = new Map(); + for (const record of routing) { + if (!isObject(record) || record.stage !== "request" || typeof record.request_id !== "string" || !record.request_id) continue; + const previous = requests.get(record.request_id); + requests.set(record.request_id, previous === undefined || (previous && previous.routed === record.routed && previous.requested_model === record.requested_model) ? record : null); + } + return requests; +} + +/** + * Attribute one proxy request from AWF's record of it and the runner-declared + * sub-agents: `main` ran as selected, `subagent` is a declared sub-agent's model + * that AWF recorded as deviated, `deviated` ran another model or effort, and + * anything else, including a missing or conflicting record, is `unattributed`. + * @param {Record | null | undefined} route + * @param {unknown} provider + * @param {unknown} subAgentModels aw_info.sub_agent_models + * @returns {"main" | "subagent" | "deviated" | "unattributed"} + */ +function attributeRequest(route, provider, subAgentModels) { + const requested = route?.requested_model; + const declared = typeof requested === "string" && matchesDeclaredSubAgent(requested, route?.provider ?? provider, subAgentModels); + if (route?.routed === "deviated") return declared ? "subagent" : "deviated"; + return route?.routed === "as_selected" && !declared ? "main" : "unattributed"; +} + /** @param {unknown} value @returns {number | undefined} */ const tokenCount = value => (value === undefined || value === null ? 0 : typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined); @@ -270,14 +304,7 @@ const tokenCount = value => (value === undefined || value === null ? 0 : typeof function estimateBaseline({ config, subAgentModels, tokenUsage, routing }) { if (config?.routing?.enabled !== true) return undefined; const baseline = config.baselineModel; - /** @type {Map | null>} */ - const requests = new Map(); - for (const record of routing) { - if (!isObject(record) || record.stage !== "request" || typeof record.request_id !== "string" || !record.request_id) continue; - // Conflicting proxy records for one request are ambiguous. - const previous = requests.get(record.request_id); - requests.set(record.request_id, previous === undefined || (previous && previous.routed === record.routed && previous.requested_model === record.requested_model) ? record : null); - } + const requests = routedRequests(routing); const seen = new Set(); let mainRequests = 0; let pricedRequests = 0; @@ -295,11 +322,9 @@ function estimateBaseline({ config, subAgentModels, tokenUsage, routing }) { if (seen.has(id)) continue; seen.add(id); if (record.purpose === "routing_classification") continue; - const route = requests.get(id); - const requested = route?.requested_model; - const declared = typeof requested === "string" && matchesDeclaredSubAgent(requested, route?.provider ?? record.provider, subAgentModels); - if (route?.routed === "deviated" && declared) continue; - if (route?.routed !== "as_selected" || declared) { + const role = attributeRequest(requests.get(id), record.provider, subAgentModels); + if (role === "subagent") continue; + if (role !== "main") { unattributedRequests++; continue; } @@ -353,5 +378,7 @@ module.exports = { persistModelConfigBaseline, projectModelConfig, matchesDeclaredSubAgent, + routedRequests, + attributeRequest, estimateBaseline, }; diff --git a/actions/setup/js/routing_observation.cjs b/actions/setup/js/routing_observation.cjs new file mode 100644 index 00000000000..402db6f9bbd --- /dev/null +++ b/actions/setup/js/routing_observation.cjs @@ -0,0 +1,232 @@ +// @ts-check +"use strict"; + +/** + * The verdict on a routed run: whether its result counts as evidence about the + * pair AWF selected, and if not, why. The unified session already holds AWF's + * selection, its record of every request and each request's priced usage; the + * verdict is the one fact it lacks, because it needs the conclusion job's final + * job results and validated safe outputs. + */ + +const { attributeRequest, routedRequests } = require("./routing_analytics.cjs"); + +/** @typedef {import("./types/unified_session").RoutingObservationData} RoutingObservationData */ +/** @typedef {import("./types/unified_session").RoutingSkipReason} RoutingSkipReason */ +/** @typedef {{terminal: string[], errors: number, agentIncomplete: boolean, infrastructure: boolean, failureCause?: string}} AgentOutputSummary */ + +/** + * @typedef {object} RunEvidence + * @property {"match" | "mismatch" | "unknown"} pair whether the agent's requests ran the selected pair + * @property {string | undefined} agentResult + * @property {{outcome?: string, failureClasses: string[]} | undefined} harness the final harness attempt + * @property {boolean} startupFailed + * @property {{categories: string[], errorCodes: Array}} execution + * @property {number[]} proxyStatuses HTTP statuses AWF recorded for the agent's failed requests + * @property {boolean} refused the main conversation recorded a refusal or content filter + * @property {AgentOutputSummary | undefined} output + * @property {"clean" | "threat" | "inconclusive"} detection + */ + +const CLASSIFIER_PURPOSE = "routing_classification"; +const NON_TERMINAL_OUTPUTS = new Set(["report_missing_tool", "report_missing_data", "report_incomplete", "request_continuation"]); +const THREAT_FLAGS = ["prompt_injection", "promptInjection", "secret_leak", "secretLeak", "malicious_patch", "maliciousPatch"]; +const INCONCLUSIVE_DETECTION_REASONS = new Set(["agent_failure", "parse_error", "github_api_quota_exhausted"]); + +// Platform causes. Each set names evidence about the platform, never about the +// model's answer; a run that succeeded is not re-examined for them. The +// collector's driver_crash cause also covers unclassified nonzero exits, so a +// crash counts only through its own evidence: a crash signal or an interrupted attempt. +const INFRASTRUCTURE_FAILURE_CAUSES = new Set(["agent_startup_failure", "secret_redaction_failure", "engine_outage"]); +// Generic labels a guard's budget rejection can arrive wrapped in; beside a confirmed limit they are the model's. +const GUARD_WRAPPERS = new Set(["authentication_failed", "api_proxy_guard_rejected"]); +const INFRASTRUCTURE_CATEGORIES = new Set([ + "agentic_engine_timeout", + "authentication_failed", + "awf_api_proxy_blocking_requests", + "capi_server_error", + "goal_already_active", + "inference_access_error", + "mcp_policy_error", + "missing_model_pricing_error", + "model_not_supported_error", + "sandbox_runtime_crash", +]); +const INFRASTRUCTURE_CLASSES = new Set([ + "api_proxy_guard_rejected", + "authentication_failed", + "capi_server_error", + "connection_refused", + "invalid_model", + "mcp_gateway_shutdown", + "mcp_policy_blocked", + "missing_api_key", + "model_endpoint_mismatch", + "model_not_supported", + "model_routing_failed", + "no_auth_info", + "overloaded_error", + "sandbox_runtime_crash", + "sdk_session_idle_timeout", + "server_error", + "startup_error", + "unsupported_model_tools", + "watchdog", +]); +const RATE_LIMIT_CATEGORIES = new Set(["ai_credits_rate_limit_error", "capi_quota_exceeded_error"]); +const RATE_LIMIT_CLASSES = new Set(["capi_quota_exceeded", "rate_limit_error", "rate_limit_wait_exceeded", "token_per_minute_rate_limit"]); +const CANCELLED_CLASSES = new Set(["cancelled", "cancelled_or_timed_out"]); +// Limits the selected pair reached on its own: steps, tokens, credits, tool denials or a content filter. +const BEHAVIOR_CATEGORIES = new Set(["effective_tokens_limit_exceeded", "invocation_cap_exceeded", "max_ai_credits_exceeded", "permission_denied_limit_exceeded"]); +const BEHAVIOR_CLASSES = new Set(["ai_credits_exhausted", "content_filter", "invocation_cap_exceeded", "max_turns"]); + +/** @param {unknown} value @returns {value is Record} */ +const isRecord = value => value !== null && typeof value === "object" && !Array.isArray(value); + +/** + * Whether AWF routed the run, whether its agent made requests, whether they + * ran the selected pair, and the HTTP statuses AWF recorded for the ones that + * failed. Requests are attributed exactly as routing analytics attributes them; + * the router's own classifier call is not the agent's. + * @param {{tokenUsage: unknown[], routing: unknown[], upstreamErrors?: unknown[], subAgentModels?: unknown}} records agent-phase AWF records + * @returns {{routed: boolean, started: boolean, pair: RunEvidence["pair"], statuses: number[]}} + */ +function routedRun({ tokenUsage, routing, upstreamErrors = [], subAgentModels }) { + const routes = routedRequests(routing); + const classifier = new Set(tokenUsage.flatMap(record => (isRecord(record) && record.purpose === CLASSIFIER_PURPOSE ? [record.request_id] : []))); + for (const [id, route] of routes) if (route?.purpose === CLASSIFIER_PURPOSE) classifier.add(id); + const counts = { main: 0, subagent: 0, deviated: 0, unattributed: 0 }; + const seen = new Set(); + for (const record of tokenUsage) { + if (!isRecord(record) || record.purpose === CLASSIFIER_PURPOSE) continue; + const id = record.request_id; + if (typeof id !== "string" || !id) { + counts.unattributed++; + continue; + } + if (seen.has(id)) continue; + seen.add(id); + counts[attributeRequest(routes.get(id), record.provider, subAgentModels)]++; + } + // Requests AWF routed but recorded no usage for, such as ones rejected upstream. + for (const [id, route] of routes) { + if (seen.has(id) || classifier.has(id)) continue; + seen.add(id); + counts[attributeRequest(route, route?.provider, subAgentModels)]++; + } + return { + routed: routing.some(record => isRecord(record) && record.stage === "selection"), + started: counts.main + counts.subagent + counts.deviated + counts.unattributed > 0, + pair: counts.deviated > 0 ? "mismatch" : counts.main > 0 && counts.unattributed === 0 ? "match" : "unknown", + // Only requests attributed to the agent; a failed classifier call may have no other record. + statuses: upstreamErrors.flatMap(record => (isRecord(record) && seen.has(record.request_id) && Number.isInteger(record.status) ? [record.status] : [])), + }; +} + +/** + * Summarize the validated safe outputs the agent job wrote (agent_output.json). + * @param {unknown} value + * @returns {AgentOutputSummary | undefined} + */ +function summarizeAgentOutput(value) { + if (!isRecord(value) || !Array.isArray(value.items) || !Array.isArray(value.errors)) return undefined; + const types = value.items.map(item => (isRecord(item) && typeof item.type === "string" ? item.type : "")); + // The collector adds one report_incomplete of its own when no terminal output was found. + const collectorCause = typeof value.collectorFailureCause === "string" ? value.collectorFailureCause : typeof value.collectorEmptyOutputCause === "string" ? "unknown" : undefined; + const reports = value.items.filter(item => isRecord(item) && item.type === "report_incomplete"); + // Runtimes file this reason for provider failures, budgets and long rate-limit waits, and + // the agent can file it too, so such a report is neither the agent's own nor platform evidence. + const claimedInfrastructure = reports.filter(item => item.reason === "infrastructure_error").length; + return { + terminal: types.filter(type => type && !NON_TERMINAL_OUTPUTS.has(type)), + errors: value.errors.length, + agentIncomplete: reports.length - claimedInfrastructure > (collectorCause === undefined ? 0 : 1), + infrastructure: typeof value.collectorInfrastructureCause === "string", + ...(collectorCause === undefined ? {} : { failureCause: collectorCause }), + }; +} + +/** + * Threat detection's verdict: a threat found, a result it could not reach, or + * clean. A run without detection results is clean. + * @param {unknown[]} results detection.result data + * @returns {RunEvidence["detection"]} + */ +function detectionVerdict(results) { + const records = results.filter(isRecord); + if (records.some(result => result.reason === "threat_detected" || THREAT_FLAGS.some(key => result[key] === true))) return "threat"; + const inconclusive = records.some(result => INCONCLUSIVE_DETECTION_REASONS.has(result.reason) || ["failure", "warning"].includes(result.conclusion) || ["failure", "cancelled"].includes(result.job_result ?? result.jobResult)); + return inconclusive ? "inconclusive" : "clean"; +} + +/** @param {RunEvidence} e */ +const statuses = e => [...e.execution.errorCodes.map(code => (typeof code === "number" ? code : /^\d{3}$/.test(code) ? Number(code) : NaN)).filter(Number.isInteger), ...e.proxyStatuses]; + +/** @param {RunEvidence} e */ +function limitReached(e) { + return e.execution.categories.some(value => BEHAVIOR_CATEGORIES.has(value)) || (e.harness?.failureClasses ?? []).some(value => BEHAVIOR_CLASSES.has(value)); +} + +/** @param {RunEvidence} e */ +function cancelled(e) { + return e.agentResult === "cancelled" || e.harness?.outcome === "cancelled" || (e.harness?.failureClasses ?? []).some(value => CANCELLED_CLASSES.has(value)); +} + +/** @param {RunEvidence} e */ +function infrastructure(e) { + const limit = limitReached(e); + /** @param {string} value */ + const platform = value => !(limit && GUARD_WRAPPERS.has(value)); + return ( + e.output?.infrastructure === true || + (e.output?.failureCause !== undefined && INFRASTRUCTURE_FAILURE_CAUSES.has(e.output.failureCause)) || + e.startupFailed || + // The harness marks an attempt interrupted when its runner itself failed. + e.harness?.outcome === "interrupted" || + e.execution.categories.some(value => INFRASTRUCTURE_CATEGORIES.has(value) && platform(value)) || + statuses(e).some(status => status >= 500 && status <= 599) || + (e.harness?.failureClasses ?? []).some(value => INFRASTRUCTURE_CLASSES.has(value) && platform(value)) + ); +} + +/** @param {RunEvidence} e */ +function rateLimited(e) { + return e.execution.categories.some(value => RATE_LIMIT_CATEGORIES.has(value)) || statuses(e).includes(429) || (e.harness?.failureClasses ?? []).some(value => RATE_LIMIT_CLASSES.has(value)); +} + +/** @param {RunEvidence} e */ +function behavioralFailure(e) { + // A refusal ends the task only when the run left no terminal output; one the agent recovered from is not its result. + const refusedTask = (e.refused || e.execution.errorCodes.includes("content_filter")) && !(e.output && e.output.terminal.length > 0); + return e.output?.agentIncomplete === true || e.output?.failureCause === "prompt_exhaustion" || refusedTask || limitReached(e); +} + +/** + * Apply the precedence rules: cancellation, then platform causes for a run that + * did not succeed, then whether the selected pair ran, and only then the result. + * @param {RunEvidence} e + * @returns {RoutingObservationData} + */ +function routingOutcome(e) { + /** @param {RoutingSkipReason} reason @returns {RoutingObservationData} */ + const skip = reason => ({ outcome: "skip", reason }); + const { output } = e; + const outputValid = output !== undefined && output.errors === 0 && !output.agentIncomplete && output.failureCause === undefined && output.terminal.length > 0; + const success = e.agentResult === "success" && outputValid && e.detection === "clean"; + if (cancelled(e)) return skip("cancelled"); + if (!success && infrastructure(e)) return skip("infrastructure"); + if (!success && rateLimited(e)) return skip("rate_limited"); + if (e.pair !== "match") return skip(e.pair === "mismatch" ? "pair_mismatch" : "unknown_evidence"); + // Output that threat detection flagged is not evidence about the model. + if (e.detection === "threat") return skip("unknown_evidence"); + if (success) return { outcome: "success" }; + if (behavioralFailure(e) || (output !== undefined && (output.errors > 0 || output.failureCause === "missing_terminal_safe_output"))) return { outcome: "failure" }; + return skip("unknown_evidence"); +} + +module.exports = { + routedRun, + summarizeAgentOutput, + detectionVerdict, + routingOutcome, +}; diff --git a/actions/setup/js/routing_observation.test.cjs b/actions/setup/js/routing_observation.test.cjs new file mode 100644 index 00000000000..fc55b2700c5 --- /dev/null +++ b/actions/setup/js/routing_observation.test.cjs @@ -0,0 +1,233 @@ +import { afterEach, describe, expect, it } from "vitest"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { collectUnifiedSession, writeUnifiedSession } from "./unified_session.cjs"; +import { validateSession } from "./scripts/validate_session.cjs"; + +const req = require; +const { routedRun, routingOutcome, summarizeAgentOutput, detectionVerdict } = req("./routing_observation.cjs"); +const fixtures = req("./fixtures/routing_analytics_runs.cjs"); +const { readJsonlFile } = req("./jsonl_helpers.cjs"); + +const PROXY_LOGS = "sandbox/firewall/logs/api-proxy-logs"; +// Routed run 39147795806 created its required report, but a later check failed its agent job. +const FAILED_CHECK_RUN = fixtures.runDir("39147795806"); +const { routed, unrouted, routedClaude } = fixtures.RUNS; + +/** @param {string} dir @param {string} name */ +const proxyRecords = (dir, name) => [...readJsonlFile(path.join(dir, PROXY_LOGS, name), { strict: true })]; +/** @param {string} reason */ +const skip = reason => ({ outcome: "skip", reason }); + +describe("routedRun", () => { + // Run 39508154330 routed gpt-5.6-luna; its declared haiku-whoami sub-agent ran claude-haiku-4.5. + const dir = fixtures.runDir(routed.id); + const tokenUsage = proxyRecords(dir, "token-usage.jsonl"); + const routing = proxyRecords(dir, "model-routing.jsonl"); + const subAgentModels = fixtures.awInfo(routed.id).sub_agent_models; + const mainRequest = tokenUsage.find(record => !record.purpose && record.model === "gpt-5.6-luna").request_id; + + it("matches when the main requests ran as selected beside a declared sub-agent", () => { + expect(routedRun({ tokenUsage, routing, subAgentModels })).toEqual({ routed: true, started: true, pair: "match", statuses: [] }); + }); + + it("reports the statuses AWF recorded for the agent's failed requests, not the classifier's", () => { + const classifierRequest = tokenUsage.find(record => record.purpose === "routing_classification").request_id; + const upstreamErrors = [ + { request_id: mainRequest, status: 429 }, + { request_id: classifierRequest, status: 503 }, + // A failed classifier call can leave no usage or routing record at all. + { request_id: "classifier-without-records", status: 503 }, + ]; + expect(routedRun({ tokenUsage, routing, upstreamErrors, subAgentModels }).statuses).toEqual([429]); + }); + + it("treats a model no declared sub-agent uses as a deviation from the selected pair", () => { + expect(routedRun({ tokenUsage, routing }).pair).toBe("mismatch"); + }); + + it("cannot attribute a request without AWF's routing record, or with conflicting ones", () => { + expect(routedRun({ tokenUsage, routing: routing.filter(record => record.request_id !== mainRequest), subAgentModels }).pair).toBe("unknown"); + const conflicting = { ...routing.find(record => record.request_id === mainRequest), routed: "deviated" }; + expect(routedRun({ tokenUsage, routing: [...routing, conflicting], subAgentModels }).pair).toBe("unknown"); + }); + + it("counts a request AWF routed but recorded no usage for", () => { + const rejected = { stage: "request", request_id: "rejected-1", routed: "deviated", requested_model: "gpt-6-luna" }; + expect(routedRun({ tokenUsage, routing: [...routing, rejected], subAgentModels }).pair).toBe("mismatch"); + }); + + it("needs AWF's selection to call a run routed, and an agent request to call it started", () => { + expect(routedRun({ tokenUsage, routing: routing.filter(record => record.stage !== "selection"), subAgentModels }).routed).toBe(false); + // Run 39499464895 recorded a selection and the router's classifier call, but no agent request. + const claude = fixtures.runDir(routedClaude.id); + expect(routedRun({ tokenUsage: proxyRecords(claude, "token-usage.jsonl"), routing: proxyRecords(claude, "model-routing.jsonl") })).toEqual({ routed: true, started: false, pair: "unknown", statuses: [] }); + }); +}); + +describe("routingOutcome", () => { + /** @param {string[]} types @param {Record} [extra] */ + const output = (types, extra = {}) => summarizeAgentOutput({ items: types.map(type => ({ type })), errors: [], ...extra }); + /** @param {Record} overrides */ + const evidence = overrides => ({ + pair: "match", + agentResult: "success", + harness: undefined, + startupFailed: false, + execution: { categories: [], errorCodes: [] }, + proxyStatuses: [], + refused: false, + output: output(["create_issue"]), + detection: "clean", + ...overrides, + }); + const turnLimit = { outcome: "failure", failureClasses: ["max_turns"] }; + + it.each([ + ["a successful agent with terminal output", {}, { outcome: "success" }], + ["a valid noop", { output: output(["noop"]) }, { outcome: "success" }], + ["a success that recovered from a rate limit", { execution: { categories: [], errorCodes: [429] }, proxyStatuses: [503] }, { outcome: "success" }], + ["only a continuation request", { output: output(["request_continuation"]) }, skip("unknown_evidence")], + ["a cancelled agent job, before the pair check", { agentResult: "cancelled", pair: "mismatch" }, skip("cancelled")], + ["a harness attempt cancelled or timed out", { agentResult: "failure", harness: { outcome: "failure", failureClasses: ["cancelled_or_timed_out"] } }, skip("cancelled")], + ["a startup failure before any harness attempt", { agentResult: "failure", startupFailed: true, output: undefined }, skip("infrastructure")], + ["an interrupted harness attempt", { agentResult: "failure", harness: { outcome: "interrupted", failureClasses: [] } }, skip("infrastructure")], + ["a provider 5xx", { agentResult: "failure", execution: { categories: [], errorCodes: ["503"] } }, skip("infrastructure")], + ["an authentication failure", { agentResult: "failure", execution: { categories: ["authentication_failed"], errorCodes: [] } }, skip("infrastructure")], + ["an incomplete report claiming an infrastructure error", { agentResult: "failure", output: summarizeAgentOutput({ items: [{ type: "report_incomplete", reason: "infrastructure_error" }], errors: [] }) }, skip("unknown_evidence")], + [ + "a safe-output gateway that registered no tools", + { agentResult: "failure", output: output(["report_incomplete"], { errors: ["gateway"], collectorFailureCause: "request_rejection", collectorInfrastructureCause: "safeoutputs_gateway_empty" }) }, + skip("infrastructure"), + ], + ["a 429 without terminal output", { agentResult: "failure", output: output([]), execution: { categories: [], errorCodes: [429] } }, skip("rate_limited")], + ["a 429 that only AWF recorded", { agentResult: "failure", output: output(["report_incomplete"]), proxyStatuses: [429] }, skip("rate_limited")], + ["requests that ran another model or effort", { pair: "mismatch" }, skip("pair_mismatch")], + ["requests that could not be attributed", { pair: "unknown" }, skip("unknown_evidence")], + ["an agent that reported it could not finish", { agentResult: "failure", output: output(["report_incomplete"]) }, { outcome: "failure" }], + ["a turn limit", { agentResult: "failure", output: output([]), harness: turnLimit }, { outcome: "failure" }], + ["a turn limit without agent output", { agentResult: "failure", output: undefined, harness: turnLimit }, { outcome: "failure" }], + ["a turn limit beside an unclassified nonzero exit", { agentResult: "failure", output: output(["report_incomplete"], { collectorFailureCause: "driver_crash" }), harness: turnLimit }, { outcome: "failure" }], + ["a credit limit wrapped as an authentication failure", { agentResult: "failure", output: output([]), execution: { categories: ["authentication_failed", "max_ai_credits_exceeded"], errorCodes: [] } }, { outcome: "failure" }], + ["a refusal that left no terminal output", { agentResult: "failure", output: output([]), refused: true }, { outcome: "failure" }], + ["a refusal the agent recovered from", { agentResult: "failure", refused: true }, skip("unknown_evidence")], + ["outputs the validator rejected", { agentResult: "failure", output: summarizeAgentOutput({ items: [], errors: ["invalid"] }) }, { outcome: "failure" }], + ["no terminal output", { agentResult: "failure", output: output(["report_incomplete"], { collectorFailureCause: "missing_terminal_safe_output" }) }, { outcome: "failure" }], + ["a failed agent job after valid terminal output", { agentResult: "failure" }, skip("unknown_evidence")], + ["a threat detection finding", { detection: "threat" }, skip("unknown_evidence")], + ["rejected output that threat detection flagged", { agentResult: "failure", detection: "threat", output: summarizeAgentOutput({ items: [], errors: ["invalid"] }) }, skip("unknown_evidence")], + ["detection that could not reach a result", { detection: "inconclusive" }, skip("unknown_evidence")], + ["missing agent output", { agentResult: "failure", output: undefined }, skip("unknown_evidence")], + ])("%s", (_name, overrides, expected) => { + expect(routingOutcome(evidence(overrides))).toEqual(expected); + }); +}); + +describe("detectionVerdict", () => { + it.each([ + ["no detection result", [], "clean"], + ["a clean conclusion result", [{ job_result: "success", conclusion: "success", prompt_injection: false }], "clean"], + ["skipped detection", [{ job_result: "skipped", conclusion: "skipped", reason: "detection_skipped" }], "clean"], + ["a threat flag", [{ secretLeak: true }], "threat"], + ["a threat reason without flags", [{ job_result: "failure", conclusion: "failure", reason: "threat_detected" }], "threat"], + ["a detector that failed", [{ job_result: "success", conclusion: "warning", reason: "agent_failure" }], "inconclusive"], + ["a warning without a verdict", [{ job_result: "success", conclusion: "warning" }], "inconclusive"], + ["a cancelled detection job", [{ job_result: "cancelled" }], "inconclusive"], + ])("%s", (_name, results, expected) => { + expect(detectionVerdict(results)).toBe(expected); + }); +}); + +describe("routing.observation in the unified session", () => { + const roots = []; + afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); + }); + + /** @param {string} source @param {unknown} [agentOutput] */ + function prepare(source, agentOutput = { items: [{ type: "create_issue" }], errors: [] }) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "routing-observation-")); + roots.push(root); + fs.cpSync(source, root, { recursive: true, filter: file => path.basename(file) !== "aw_session.jsonl" }); + fs.writeFileSync(path.join(root, "agent_output.json"), JSON.stringify(agentOutput)); + return root; + } + /** @param {string} agent */ + /** @param {string} agent @param {string} [detection] */ + const jobResults = (agent, detection) => JSON.stringify({ activation: { result: "success" }, agent: { result: agent }, ...(detection ? { detection: { result: detection } } : {}) }); + /** @param {string} root @param {{agent?: string, engine?: string, routingObservation?: boolean}} [options] */ + const collect = (root, { agent = "success", detection, engine, routingObservation = true } = {}) => + collectUnifiedSession({ rootDir: root, engine, warn: () => {}, dailyAIC: {}, admission: {}, jobResults: jobResults(agent, detection), routingObservation }).events; + /** @param {any[]} events */ + const verdicts = events => events.filter(event => event.type === "routing.observation"); + + it("writes one collector verdict for a routed run that validates against the session schema", () => { + const root = prepare(fixtures.runDir(routed.id)); + const outputPath = path.join(root, "usage/aw_session.jsonl"); + writeUnifiedSession({ rootDir: root, outputPath, warn: () => {}, dailyAIC: {}, admission: {}, jobDurations: {}, jobResults: jobResults("success"), routingObservation: true }); + const content = fs.readFileSync(outputPath, "utf8"); + const events = [...readJsonlFile(outputPath, { strict: true })]; + expect(validateSession(content)).toBe(events.length); + const [verdict, ...rest] = verdicts(events); + expect(rest).toEqual([]); + expect(verdict.data).toEqual({ outcome: "success" }); + expect(verdict.provenance).toMatchObject({ component: "collector", phase: "conclusion", path: "usage/aw_session.jsonl" }); + }); + + it("judges the same AWF evidence the same way for every engine", () => { + const root = prepare(fixtures.runDir(routed.id)); + for (const engine of ["copilot", "claude", "codex", "pi"]) { + expect(verdicts(collect(root, { engine })).map(event => event.data)).toEqual([{ outcome: "success" }]); + } + expect(verdicts(collect(root, { agent: "failure" })).map(event => event.data)).toEqual([skip("unknown_evidence")]); + }); + + it("does not count run 39147795806, whose report succeeded but whose agent job failed a later check", () => { + const root = prepare(FAILED_CHECK_RUN); + expect(verdicts(collect(root, { agent: "failure" })).map(event => event.data)).toEqual([skip("unknown_evidence")]); + expect(verdicts(collect(root)).map(event => event.data)).toEqual([{ outcome: "success" }]); + }); + + it("reads detection results, AWF's failed requests and content-filter refusals from the run", () => { + const empty = { items: [], errors: [] }; + const threat = prepare(fixtures.runDir(routed.id)); + fs.mkdirSync(path.join(threat, "usage/detection"), { recursive: true }); + fs.writeFileSync(path.join(threat, "usage/detection/detection_result.json"), JSON.stringify({ job_result: "failure", conclusion: "failure", reason: "threat_detected" })); + expect(verdicts(collect(threat)).map(event => event.data)).toEqual([skip("unknown_evidence")]); + // A detector that failed before writing any result leaves no clean verdict either. + const failedDetector = prepare(fixtures.runDir(routed.id)); + fs.rmSync(path.join(failedDetector, "usage/detection"), { recursive: true, force: true }); + expect(verdicts(collect(failedDetector, { detection: "failure" })).map(event => event.data)).toEqual([skip("unknown_evidence")]); + + // A failed agent that left no output is unknown evidence, unless AWF recorded a provider outage. + const outage = prepare(fixtures.runDir(routed.id), empty); + expect(verdicts(collect(outage, { agent: "failure" })).map(event => event.data)).toEqual([skip("unknown_evidence")]); + const mainRequest = proxyRecords(outage, "token-usage.jsonl").find(record => !record.purpose && record.model === "gpt-5.6-luna").request_id; + fs.writeFileSync(path.join(outage, PROXY_LOGS, "upstream-errors.jsonl"), JSON.stringify({ event: "UPSTREAM_ERROR_RESPONSE", request_id: mainRequest, status: 503 }) + "\n"); + expect(verdicts(collect(outage, { agent: "failure" })).map(event => event.data)).toEqual([skip("infrastructure")]); + + const filtered = prepare(fixtures.runDir(routed.id), empty); + fs.writeFileSync(path.join(filtered, "agent-session.jsonl"), JSON.stringify({ type: "assistant.refusal", data: { reason: "refusal" } }) + "\n"); + expect(verdicts(collect(filtered, { agent: "failure" })).map(event => event.data)).toEqual([{ outcome: "failure" }]); + + // A fallback detection file's reason is untrusted, as in the published session. + const fallback = prepare(fixtures.runDir(routed.id)); + fs.rmSync(path.join(fallback, "usage/detection"), { recursive: true, force: true }); + fs.mkdirSync(path.join(fallback, "threat-detection"), { recursive: true }); + fs.writeFileSync(path.join(fallback, "threat-detection/detection_result.json"), JSON.stringify({ prompt_injection: false, secret_leak: false, malicious_patch: false, reason: "agent_failure" })); + expect(verdicts(collect(fallback)).map(event => event.data)).toEqual([{ outcome: "success" }]); + }); + + it("has no verdict outside the conclusion job, for an unrouted run, or when the agent made no request", () => { + expect(verdicts(collect(prepare(fixtures.runDir(routed.id)), { routingObservation: false }))).toEqual([]); + expect(verdicts(collect(prepare(fixtures.runDir(unrouted.id))))).toEqual([]); + expect(verdicts(collect(prepare(fixtures.runDir(routedClaude.id))))).toEqual([]); + }); + + it("drops a verdict that any other source supplies", () => { + const root = prepare(fixtures.runDir(unrouted.id)); + fs.writeFileSync(path.join(root, "agent-session.jsonl"), JSON.stringify({ type: "routing.observation", data: { outcome: "success" } }) + "\n"); + expect(verdicts(collect(root))).toEqual([]); + }); +}); diff --git a/actions/setup/js/safe_output_redaction.cjs b/actions/setup/js/safe_output_redaction.cjs index 550184f0f84..85b19a24304 100644 --- a/actions/setup/js/safe_output_redaction.cjs +++ b/actions/setup/js/safe_output_redaction.cjs @@ -157,7 +157,7 @@ function redactSafeOutputContent(filePath, content, maskedValues, redactText) { if (!value || typeof value !== "object" || !Array.isArray(value.items)) { throw new Error(`${ERR_VALIDATION}: Invalid agent-output envelope during secret redaction`); } - const properties = Object.fromEntries(["errors", "collectorEmptyOutputCause", "collectorFailureCause", "collectorDriverExitCode", "collectorRetryCount", "collectorEngineErrorType"].map(key => [key, {}])); + const properties = Object.fromEntries(["errors", "collectorEmptyOutputCause", "collectorFailureCause", "collectorDriverExitCode", "collectorRetryCount", "collectorEngineErrorType", "collectorInfrastructureCause"].map(key => [key, {}])); return Object.fromEntries( Object.entries(value).map(([key, nested]) => key === "items" ? [key, nested.map(item => redactMessage(item, redactText))] : [Object.hasOwn(properties, key) ? key : redactText(key), redactBySchema(nested, properties[key], redactText)] diff --git a/actions/setup/js/types/unified_session.d.ts b/actions/setup/js/types/unified_session.d.ts index bde0d5d684c..60dd3d308b2 100644 --- a/actions/setup/js/types/unified_session.d.ts +++ b/actions/setup/js/types/unified_session.d.ts @@ -302,6 +302,23 @@ export interface ModelBaselineEstimateData { complete: boolean; } +/** Why a routed run's result does not count as evidence about the selected pair. */ +export type RoutingSkipReason = "cancelled" | "infrastructure" | "rate_limited" | "pair_mismatch" | "unknown_evidence"; + +/** A routed run whose result counts: the selected pair succeeded or failed on its own. */ +export interface RoutingCountedObservationData { + outcome: "success" | "failure"; +} + +/** A routed run whose result does not count, and why. */ +export interface RoutingSkippedObservationData { + outcome: "skip"; + reason: RoutingSkipReason; +} + +/** Collector-written verdict on a routed run (T-UAS-094). */ +export type RoutingObservationData = RoutingCountedObservationData | RoutingSkippedObservationData; + export interface ModelRoutingRankedChoice { rank: number; id?: string; @@ -846,6 +863,7 @@ export interface UnifiedSessionEventDataMap { "model.inventory": ModelInventoryData; "model.config": ModelConfigData; "model.baseline_estimate": ModelBaselineEstimateData; + "routing.observation": RoutingObservationData; "skill.inventory": SkillInventoryData; "skill.conflict": SkillConflictData; "skill.invoked": SkillInvokedData; diff --git a/actions/setup/js/unified_session.cjs b/actions/setup/js/unified_session.cjs index ddcede0ba45..350f1769030 100644 --- a/actions/setup/js/unified_session.cjs +++ b/actions/setup/js/unified_session.cjs @@ -3,7 +3,7 @@ const { iterateJsonlEvents } = require("./jsonl_helpers.cjs"); const fs = require("fs"); const path = require("path"); -const { isSessionEvent } = require("./agent_session.cjs"); +const { isSessionEvent, isNestedSessionEvent } = require("./agent_session.cjs"); const { hasCopilotConversation, deduplicateCopilotFallback, normalizeCopilotSession } = require("./copilot_session.cjs"); const { collectAddMaskedValues, serializeSessionArtifact, writeSessionArtifact, removeFailedSessionArtifacts } = require("./session_artifact.cjs"); const { getErrorMessage } = require("./error_helpers.cjs"); @@ -15,12 +15,15 @@ const { sessionTimestamp, orderSessionSources } = require("./unified_session_ord const { normalizeOtelEvents } = require("./unified_session_otel.cjs"); const { getApiProxyEventName } = require("./steering_helpers.cjs"); const { estimateBaseline, projectModelConfig } = require("./routing_analytics.cjs"); +const { routedRun, routingOutcome, summarizeAgentOutput, detectionVerdict } = require("./routing_observation.cjs"); const { normalizeHarnessRetryRecord } = require("./harness_retry_record.cjs"); const { parseHarnessAttempts, correlateHarnessAttempts } = require("./harness_retry_session.cjs"); const { isDurableSessionRecord } = require("./durable_session_record.cjs"); const { buildWorkflowCallId } = require("./aw_context.cjs"); const SESSION_FILE_FORMAT_VERSION = 1; +// The conclusion's sanitized detection result; only it carries a trusted conclusion reason. +const DETECTION_RESULT_PATH = "usage/detection/detection_result.json"; /** @param {any} data @returns {boolean} */ function isModelEndpointMismatchData(data) { @@ -107,7 +110,7 @@ function mergeSessionSources(sources, engine) { native.index >= 0 ? native.index : (source.indices?.[index] ?? index); - if (event.type === "detection.result" && source.path !== "usage/detection/detection_result.json") { + if (event.type === "detection.result" && source.path !== DETECTION_RESULT_PATH) { delete normalized.data.reason; } return { @@ -180,10 +183,55 @@ function parseEngineSession(content, engine, options = {}) { return [...events.filter(event => event.type !== "agent.execution"), ...(execution ? [execution] : [])]; } +/** + * The routing verdict for a run AWF routed and whose agent made requests + * (T-UAS-094). A run that was not routed, or whose agent never made a request, + * has none. + * @param {SessionSource[]} sources + * @param {unknown} subAgentModels aw_info.sub_agent_models + * @param {unknown} output agent_output.json + * @returns {import("./types/unified_session").RoutingObservationData | undefined} + */ +function observeRoutedRun(sources, subAgentModels, output) { + /** @param {string} component @param {string | undefined} phase @param {string} type */ + const eventsOf = (component, phase, type) => sources.filter(source => source.component === component && (phase === undefined || source.phase === phase)).flatMap(source => source.events.filter(event => event.type === type)); + /** @param {string} type */ + const proxyRecords = type => eventsOf("firewall", "agent", type).map(event => event.data); + const run = routedRun({ tokenUsage: proxyRecords("firewall.token_usage"), routing: proxyRecords("firewall.model_routing"), upstreamErrors: proxyRecords("firewall.upstream_error"), subAgentModels }); + if (!run.routed || !run.started) return undefined; + /** @type {any} */ + const harness = eventsOf("harness", "agent", "harness.retry")[0]?.data; + /** @type {any} */ + const execution = eventsOf("execution", "agent", "agent.execution")[0]?.data; + const attempt = harness?.attemptResults?.at(-1); + const startup = harness?.startupAttemptResults?.at(-1); + const jobResults = eventsOf("workflow", "conclusion", "workflow.job_result"); + const agentResult = jobResults.find(event => event.data?.jobId === "agent")?.data?.result; + const detectionJob = jobResults.find(event => event.data?.jobId === "detection")?.data?.result; + return routingOutcome({ + pair: run.pair, + agentResult: typeof agentResult === "string" ? agentResult : undefined, + harness: attempt ? { outcome: attempt.outcome, failureClasses: Array.isArray(attempt.failureClasses) ? attempt.failureClasses : [] } : undefined, + startupFailed: !attempt && startup?.outcome === "failure", + execution: { categories: Array.isArray(execution?.categories) ? execution.categories : [], errorCodes: Array.isArray(execution?.errorCodes) ? execution.errorCodes : [] }, + proxyStatuses: run.statuses, + refused: eventsOf("agent", "agent", "assistant.refusal").some(event => !isNestedSessionEvent(event)), + output: summarizeAgentOutput(output), + // As in the published session, only the conclusion's own detection result carries a reason. The + // detection job's result counts too, for a detector that failed before any result was written. + detection: detectionVerdict([ + ...sources + .filter(source => source.component === "detection") + .flatMap(source => source.events.filter(event => event.type === "detection.result").map(event => (source.path === DETECTION_RESULT_PATH ? event.data : { ...event.data, reason: undefined }))), + ...(typeof detectionJob === "string" ? [{ job_result: detectionJob }] : []), + ]), + }); +} + /** * Collect only known runtime directories; never follow artifact symlinks. * Replicated firewall files use logs > audit > legacy precedence, including empty files. - * @param {{rootDir?: string, engine?: string, render?: boolean, protectedSessionCapture?: boolean, warn?: (message: string) => void, dailyAIC?: NodeJS.ProcessEnv, executionIdentity?: {runId?: string, runAttempt: number}, admission?: NodeJS.ProcessEnv, jobResults?: string, safeJobNames?: string, safeJobResults?: string, memorySaveResults?: string, jobDurations?: Record}} [options] + * @param {{rootDir?: string, engine?: string, render?: boolean, protectedSessionCapture?: boolean, warn?: (message: string) => void, dailyAIC?: NodeJS.ProcessEnv, executionIdentity?: {runId?: string, runAttempt: number}, admission?: NodeJS.ProcessEnv, jobResults?: string, safeJobNames?: string, safeJobResults?: string, memorySaveResults?: string, jobDurations?: Record, routingObservation?: boolean}} [options] * @returns {{events: import("./types/unified_session").UnifiedSession, maskedValues: string[]}} */ function collectUnifiedSession({ @@ -200,6 +248,7 @@ function collectUnifiedSession({ safeJobResults = process.env.GH_AW_SAFE_JOB_RESULTS, memorySaveResults = process.env.GH_AW_MEMORY_SAVE_RESULTS, jobDurations = {}, + routingObservation = false, } = {}) { const liveIdentity = executionIdentity?.runId && Number.isSafeInteger(executionIdentity.runAttempt) && executionIdentity.runAttempt > 0 ? executionIdentity : undefined; let currentRunId = liveIdentity?.runId ?? dailyAIC.GITHUB_RUN_ID; @@ -955,6 +1004,19 @@ function collectUnifiedSession({ } } } + // Only the collector publishes routing verdicts; no source can supply its own. + for (const source of sources) { + if (!source.events.some(event => event.type === "routing.observation")) continue; + source.indices = source.events.flatMap((event, index) => (event.type === "routing.observation" ? [] : [source.indices?.[index] ?? index])); + source.events = source.events.filter(event => event.type !== "routing.observation"); + } + /** @type {SessionEvent[]} */ + const routingObservations = []; + if (routingObservation) { + const outputFile = choose(["agent_output.json"]); + const observation = observeRoutedRun(sources, runInfo?.sub_agent_models, outputFile ? records(outputFile)[0] : undefined); + if (observation) routingObservations.push({ type: "routing.observation", data: { ...observation } }); + } const persistedWarnings = sources.flatMap(source => source.events.filter(event => event.type === "session.collection_warning")); const memorySaves = require("./memory_save_results.cjs").readMemorySaveResults(memorySaveResults); if (memorySaves.length) { @@ -978,7 +1040,7 @@ function collectUnifiedSession({ }; /** @type {import("./types/agent_session").SessionFileFormatEvent} */ const format = { type: "session.format", data: { version: SESSION_FILE_FORMAT_VERSION } }; - sources.push({ component: "collector", phase: "conclusion", path: "usage/aw_session.jsonl", events: [format, ...warnings, ...routingEstimates, summary] }); + sources.push({ component: "collector", phase: "conclusion", path: "usage/aw_session.jsonl", events: [format, ...warnings, ...routingEstimates, ...routingObservations, summary] }); const events = correlateHarnessAttempts(mergeSessionSources(sources, engine ?? (canonicalCopilot ? "copilot" : undefined))); const formatIndex = events.findIndex(event => event.type === "session.format" && event.provenance.component === "collector" && event.provenance.index === 0); // File metadata leads the stream without inventing a timestamp for it. @@ -987,7 +1049,7 @@ function collectUnifiedSession({ } /** - * @param {{rootDir?: string, engine?: string, outputPath?: string, warn?: (message: string) => void, executionIdentity?: {runId?: string, runAttempt: number}, admission?: NodeJS.ProcessEnv, jobDurations?: Record, graders?: any[], customGraderIds?: string[]}} [options] + * @param {{rootDir?: string, engine?: string, outputPath?: string, warn?: (message: string) => void, executionIdentity?: {runId?: string, runAttempt: number}, admission?: NodeJS.ProcessEnv, jobDurations?: Record, graders?: any[], customGraderIds?: string[], routingObservation?: boolean}} [options] * @returns {import("./types/unified_session").UnifiedSession} */ function writeUnifiedSession(options = {}) { @@ -1021,7 +1083,8 @@ async function main(options = {}) { const { readGraderManifestEnvironment, publishGraderSummary } = require("./grader_artifacts.cjs"); const manifest = options.graders === undefined ? readGraderManifestEnvironment() : { graders: options.graders }; const executionIdentity = options.executionIdentity ?? { runId: process.env.GITHUB_RUN_ID, runAttempt: Number(process.env.GITHUB_RUN_ATTEMPT) }; - const events = writeUnifiedSession({ ...options, executionIdentity, jobDurations, graders: manifest.graders, customGraderIds: options.customGraderIds ?? manifest.customGraders }); + // Only the conclusion job has the final job results the routing verdict needs. + const events = writeUnifiedSession({ ...options, executionIdentity, jobDurations, graders: manifest.graders, customGraderIds: options.customGraderIds ?? manifest.customGraders, routingObservation: true }); const { publishUnifiedSessionSummary } = require("./unified_session_render.cjs"); await publishUnifiedSessionSummary(options.outputPath ?? path.join(options.rootDir ?? "/tmp/gh-aw", "usage/aw_session.jsonl")); await publishGraderSummary(events); diff --git a/actions/setup/js/unified_session_render.cjs b/actions/setup/js/unified_session_render.cjs index ab3e505ab7b..cbf610f5bbb 100644 --- a/actions/setup/js/unified_session_render.cjs +++ b/actions/setup/js/unified_session_render.cjs @@ -217,6 +217,8 @@ function eventDetail(event) { return fields(data, ["stage", "routed", "outcome", "selectedModel", "selectedEffort", "router"]); case "model_routing.outcome": return fields(data, ["status", "wireModel", "effectiveEndpoint", "selectedEndpoint", "effort", "appliedEffort", "failureCode"]); + case "routing.observation": + return fields(data, ["outcome", "reason"]); case "model.inventory": return fields(data, ["endpoints", "modelsFetchComplete"]); case "model_endpoint.mismatch": diff --git a/actions/setup/session_parsers.go b/actions/setup/session_parsers.go index 4f678353d17..79268507088 100644 --- a/actions/setup/session_parsers.go +++ b/actions/setup/session_parsers.go @@ -80,7 +80,7 @@ import "embed" //go:embed js/agent_execution.cjs js/agent_error_patterns.cjs js/harness_error_patterns.cjs js/harness_crash_signals.cjs js/harness_retry_record.cjs //go:embed js/harness_retry_session.cjs //go:embed js/engine_log_parser.cjs -//go:embed js/routing_analytics.cjs js/resolve_model_alias.cjs +//go:embed js/routing_analytics.cjs js/routing_observation.cjs js/resolve_model_alias.cjs //go:embed js/parse_kiro_log.cjs //go:embed js/parse_deepseek_log.cjs //go:embed js/parse_pydantic_log.cjs diff --git a/docs/adr/80468-record-routing-observation-verdict.md b/docs/adr/80468-record-routing-observation-verdict.md new file mode 100644 index 00000000000..a4d5756d6a6 --- /dev/null +++ b/docs/adr/80468-record-routing-observation-verdict.md @@ -0,0 +1,63 @@ +# ADR-80468: Record a Routing Observation Verdict for Routed Runs + +**Date**: 2026-11-23 +**Status**: Accepted +**Deciders**: rabeckett (PR author and author of [#79103](https://github.com/github/gh-aw/issues/79103)) + +## Context + +When AWF routes a run, it selects a model and effort for it. Three existing signals answer different questions: the routing selection, the harness outcome, and the safe-output result. None of them says whether the run's result is evidence about the pair AWF actually selected. Issue [#79103](https://github.com/github/gh-aw/issues/79103) names two failure modes. A setup timeout or a 429 counted as a model failure teaches a router the wrong lesson. So does a result credited to a model or effort the harness did not use. + +Forces: + +- The unified session already holds, for every routed run, the selected pair, whether each request ran as selected (`routed`), and each request's priced cost. +- Job results and validated safe outputs are known only in the conclusion job, after the other jobs finish. +- The verdict must mean the same thing for Copilot, Claude, Codex, and Pi, so it cannot depend on engine-specific logs. +- Cost must come from the firewall's priced requests, not a second accounting path. Missing cost is not zero. + +## Decision + +For each routed run whose agent made requests, the conclusion job adds one `routing.observation` event to the unified session. The event is either: + +- `success` or `failure`, when the result counts as evidence about the selected model and effort; or +- `skip`, with one reason: `cancelled`, `infrastructure`, `rate_limited`, `pair_mismatch`, or `unknown_evidence`. + +The verdict uses only: + +- AWF's request records (`model_routing`, `token_usage`), attributed by the rule routing analytics already applies (`attributeRequest` in `routing_analytics.cjs`), and the statuses AWF recorded for the agent's failed requests; +- the job results, including the detection job's; +- the harness and execution records, and refusals in the main conversation; +- the validated safe outputs in `agent_output.json`; and +- threat detection's result. + +The rules apply in this order: cancellation; platform causes, for runs that did not succeed; rate limits; whether the selected pair ran; then the result. A run that succeeded is not re-examined for platform errors it recovered from. A success needs a successful agent job, a terminal safe output (a valid `noop` counts), and a clean threat detection result. Output that threat detection flagged is skipped as `unknown_evidence`. + +Only the conclusion job computes the verdict, because only it has the final job results. The collector's entry point enables it, so the compiler does not change and no lock file is recompiled. The collector drops `routing.observation` events from any other source. It also records `collectorInfrastructureCause: "safeoutputs_gateway_empty"` in `agent_output.json`, so a gateway that registered no tools is not mistaken for the agent's invalid outputs. + +The verdict appears in `gh aw audit` and as `model_routing.observation` in `audit --json` and `logs --json`. Its vocabulary is defined in version 2.14.0 of the unified agent session specification (T-UAS-094) and in the audit reference. Whether a run may update a routing history is left to the history writer, not the verdict. + +## Alternatives Considered + +1. **Use the agent job's or the conclusion job's success as the verdict.** Rejected. A setup timeout or a 429 would count as a model failure, and a run that used a model other than the one selected would be credited to the selection. +2. **Parse each engine's logs for outcome evidence.** Rejected. Issue #79103 requires evidence that every engine produces, so the meaning is the same for Copilot, Claude, Codex, and Pi. +3. **Compute the verdict in the agent job.** Rejected. The agent job does not have the final job results that the platform-cause and output rules depend on. +4. **Compute cost in a separate accounting path.** Rejected. The firewall's priced requests are the single source of cost, and a second path could disagree with them. + +## Consequences + +**Positive** + +- Platform causes (outages, timeouts, 429s, cancellations) no longer count as model failures. +- A result counts only when the selected pair actually ran, so the verdict is attributable. +- The verdict means the same thing across engines and needs no compiler or lock-file change. +- Sessions without the event stay readable: the CLI reports no observation for them, as the unchanged model-routing golden sessions and the provenance test show. + +**Negative** + +- The precedence and classification tables are large (platform, rate-limit, and behavioral sets, plus the wrapper and guard exceptions). They must be kept in step with gh-aw's harness and execution category names. +- An incomplete report whose reason claims an infrastructure error counts neither way, because the agent can file that reason. An infrastructure failure known only from such a report is skipped as `unknown_evidence` rather than `infrastructure`. +- Many routed runs will produce `skip` verdicts, which give no learning signal for routing history. +- The vocabulary is closed. A new reason or outcome requires coordinated changes to the session schema, the specification, and the audit output. +- Consumers must read two separate decisions: the verdict, and the history writer's choice about whether to record it. + +*ADR drafted by the Design Decision Gate and reviewed by the PR author.* diff --git a/docs/public/schemas/unified-session.schema.json b/docs/public/schemas/unified-session.schema.json index a190c90c266..a20cd168a17 100644 --- a/docs/public/schemas/unified-session.schema.json +++ b/docs/public/schemas/unified-session.schema.json @@ -140,6 +140,7 @@ { "if": { "properties": { "type": { "const": "plugin.installation" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/PluginInstallationData" } } } }, { "if": { "properties": { "type": { "const": "prompt.system" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/Pick%3CMessageData%2C%22content%22%3E" } } } }, { "if": { "properties": { "type": { "const": "prompt.user" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/Pick%3CMessageData%2C%22content%22%3E" } } } }, + { "if": { "properties": { "type": { "const": "routing.observation" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/RoutingObservationData" } } } }, { "if": { "properties": { "type": { "const": "safe_output.error" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/SafeOutputErrorData" } } } }, { "if": { "properties": { "type": { "const": "safe_output.execution" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/SafeOutputData" } } } }, { "if": { "properties": { "type": { "const": "safe_output.request" } }, "required": ["type"] }, "then": { "properties": { "data": { "$ref": "#/definitions/SafeOutputData" } } } }, @@ -1282,6 +1283,22 @@ "additionalProperties": false }, "Record": { "type": "object", "additionalProperties": { "$ref": "#/definitions/JsonValue" } }, + "RoutingCountedObservationData": { + "type": "object", + "properties": { "outcome": { "type": "string", "enum": ["success", "failure"] } }, + "required": ["outcome"], + "additionalProperties": false, + "description": "A routed run whose result counts: the selected pair succeeded or failed on its own." + }, + "RoutingObservationData": { "anyOf": [{ "$ref": "#/definitions/RoutingCountedObservationData" }, { "$ref": "#/definitions/RoutingSkippedObservationData" }], "description": "Collector-written verdict on a routed run (T-UAS-094)." }, + "RoutingSkipReason": { "type": "string", "enum": ["cancelled", "infrastructure", "rate_limited", "pair_mismatch", "unknown_evidence"], "description": "Why a routed run's result does not count as evidence about the selected pair." }, + "RoutingSkippedObservationData": { + "type": "object", + "properties": { "outcome": { "type": "string", "const": "skip" }, "reason": { "$ref": "#/definitions/RoutingSkipReason" } }, + "required": ["outcome", "reason"], + "additionalProperties": false, + "description": "A routed run whose result does not count, and why." + }, "RuntimeObservationData": { "type": "object", "properties": { diff --git a/docs/src/content/docs/reference/audit.md b/docs/src/content/docs/reference/audit.md index 1f4dad66a9d..a7b1e2d7d14 100644 --- a/docs/src/content/docs/reference/audit.md +++ b/docs/src/content/docs/reference/audit.md @@ -366,6 +366,8 @@ gh aw json-schema logs-jsonl > logs-jsonl.schema.json When routing records are available, single-run `audit --json` includes `model_routing` with status, objective, labels, classifier and selected model details, ranked choices, router metadata, effective and selected endpoints, request outcome/deviation counts, failure details, and classifier/selected/deviated cost buckets. Logs JSON includes `model_routing.routes` entries keyed by labels, mode, model, effort, router version, and endpoint attribution, with `run_count`, `total_aic`, and `average_aic`, plus classifier AIC and deviation totals. +For a routed run whose agent made requests, `model_routing` in `audit --json` and in each run of `logs --json` also includes `observation`: whether the run's result counts as evidence about the model and effort AWF selected (`outcome` is `success` or `failure`), or why it does not (`skip` with a `reason`: `cancelled`, `infrastructure`, `rate_limited`, `pair_mismatch`, or `unknown_evidence`). The console report prints it as an `observation` line in the model routing details. Older sessions and unrouted runs have no observation. The [Unified Agent Session Specification](/gh-aw/specs/unified-agent-session-specification/#routing-analytics) defines the rules. + ## `gh aw logs --format ` Generates a cross-run security and performance audit report across recent runs, built into `gh aw logs`. diff --git a/docs/src/content/docs/specs/unified-agent-session-specification.md b/docs/src/content/docs/specs/unified-agent-session-specification.md index 1fe0782660a..bf57a90496a 100644 --- a/docs/src/content/docs/specs/unified-agent-session-specification.md +++ b/docs/src/content/docs/specs/unified-agent-session-specification.md @@ -4,7 +4,7 @@ spec: true description: Draft contract for canonical traces, full unified artifacts, and bounded compact unified sessions. sidebar: order: 1365 -version: "2.13.0" +version: "2.14.0" status: Draft publication_date: "2026-11-23" editors: @@ -14,7 +14,7 @@ editors: # Unified Agent Session Specification -**Version**: 2.13.0
+**Version**: 2.14.0
**Status**: Draft
**Publication Date**: 2026-11-23
**Editors**: GitHub Agentic Workflows Team (GitHub)
@@ -31,7 +31,7 @@ This specification defines the session traces used by GitHub Agentic Workflows: This is a **GitHub Agentic Workflows project specification**, written using W3C-inspired document conventions. It is **not an official W3C standard**, W3C publication, or W3C-endorsed recommendation. -Version 2.13.0 is a draft governed by the project's normal review process. It may be updated, replaced, or superseded. The accompanying implementation and regression suites exercise this contract, including the sampled CI sessions identified in Section 9.4. This is not a blanket declaration of conformance for every engine version or source format. Section 10 records historical pre-implementation gaps, not current defects. Approval and ongoing compliance testing remain project responsibilities. +Version 2.14.0 is a draft governed by the project's normal review process. It may be updated, replaced, or superseded. The accompanying implementation and regression suites exercise this contract, including the sampled CI sessions identified in Section 9.4. This is not a blanket declaration of conformance for every engine version or source format. Section 10 records historical pre-implementation gaps, not current defects. Approval and ongoing compliance testing remain project responsibilities. The specification version belongs to this document. The unified file's leading `session.format` record carries an independent numeric serialization-format @@ -849,6 +849,7 @@ source for opaque fields. | `firewall.http_access` | AWF network audit observations, including operational entries without a host. | | `firewall.token_usage`, `firewall.model_routing`, `firewall.upstream_error`, `firewall.steering`, `firewall.event` | API proxy accounting, essential AWF model-routing selection/request records, identifier-only upstream error responses (T-UAS-082), token/time steering, tracker and other firewall messages. | | `model.config`, `model.baseline_estimate` | Runner-written configured routing/model policy, budget, and baseline model (T-UAS-080), and the collector's counterfactual baseline repricing for routed runs (T-UAS-081). | +| `routing.observation` | The collector's verdict on a routed run: whether its result counts as evidence about the pair AWF selected, or why not (T-UAS-094). | | `safe_output.request`, `safe_output.result`, `safe_output.error` | Requested operation identities, executed item identities, and structured error codes. Requests are not execution results. Bodies, titles, raw errors, messages, and arbitrary metadata are excluded. | | `safe_output.execution` | Handler application outcomes from `safe-output-executions.jsonl`, transported in `safe-outputs-items`: operation `type`, zero-based `messageIndex`, `status`, and `staged`. Status is `success`, `failed`, `skipped`, `warning`, `cancelled`, `deferred`, `delegated`, or `staged`. This is the handler's run-time snapshot, not later human adoption, object survival, or longitudinal repository Value. Buffered reviews remain deferred until final submission; submission failures and skips replace provisional success. Delegation to a standalone step, custom action, or custom job is not evidence of application. Exporting a custom action payload records delegation, not application; available `workflow.job_result` observations preserve actual job success or failure separately. An optional canonical HTTPS GitHub resource `url` preserves numeric resource IDs, commit hashes, and recognized comment/review anchors, without credentials, query parameters, or free-form fragments. GitHub Enterprise uses the configured server origin; unrecognized URLs are omitted. Claim-scoped outcome files retain their source path in provenance. | | `lifecycle.adoption` | A post-run supplement from `gh aw logs --adoption --adoption-dir`, written as `adoption-session-.jsonl`. The supplement carries distinct delivery, adoption, and survival fields plus source run correlation. It is a separate observation stream: consumers MAY join it to the original session by `sourceRunId`, but MUST NOT append it to or rewrite the original run's immutable `usage/aw_session.jsonl`. | @@ -1164,6 +1165,71 @@ model is indistinguishable from the main agent in this evidence. | `unattributedRequests` | Agent-phase requests that could not be attributed. | | `complete` | `true` only when `baselineModel` is known, at least one main request was observed, and no request is unpriced or unattributed. A priced subtotal with unpriced or unattributed requests is incomplete. | +**T-UAS-094 — Routing observation.** The conclusion job's collector emits one +`routing.observation` event, with `collector` provenance and phase `conclusion`, +for a run in which AWF recorded a selection (`firewall.model_routing` with +`stage: selection`) and the agent made at least one agent-phase proxy request +other than the classifier's. A run that was not routed, or whose agent made no +request, has no observation, and neither does a session collected outside the +conclusion job, which lacks the final job results. Readers MUST treat a missing +observation as no verdict, never as a failure. Events of this type from any other +source are dropped. + +The event records only the verdict: whether the run's result counts as evidence +about the selected pair, and if not, why. The selected pair, the requests that ran +it, and their priced usage stay in the run's `firewall.model_routing` and +`firewall.token_usage` events, which readers attribute with the rules of T-UAS-081. +Under those rules, the selected pair ran when at least one main request was +observed and no request is unattributed. A request AWF recorded as +`routed: deviated` that matches no declared sub-agent ran another model or effort. +Requests AWF recorded without usage count as well. + +| Field | Meaning | +| --- | --- | +| `outcome` | `success`, `failure`, or `skip`. | +| `reason` | Present only with `skip`: `cancelled`, `infrastructure`, `rate_limited`, `pair_mismatch`, or `unknown_evidence`. | + +A run succeeded when the agent job succeeded, its validated safe outputs include at +least one terminal output (a valid `noop` counts; a continuation request does not) +with no validation errors and no incomplete report, and threat detection, if it +ran, reached a clean result. Rules apply in order: + +1. `skip` with `cancelled` when the agent job or its final harness attempt was + cancelled, including an attempt classed as cancelled or timed out. +2. For a run that did not succeed, `skip` with `infrastructure` for platform + failures: startup failures, interrupted harness attempts, crash signals, engine + outages and timeouts, a safe-output gateway that registered no tools, + authentication and policy rejections, provider 5xx responses that the engine or + AWF recorded for an agent request, and harness infrastructure failure classes. + Then `skip` with `rate_limited` for such 429 responses and quota or rate-limit + categories and classes. A generic authentication or proxy-guard rejection beside + a confirmed limit belongs to the limit, not the platform. An incomplete report + whose reason claims an infrastructure error is neither the agent's own report nor + platform evidence, because runtimes use that reason for budgets and rate-limit + waits too and the agent can file it. A run that succeeded is not re-examined for + transient errors it recovered from. +3. `skip` with `pair_mismatch` when an agent request ran another model or effort, + and `skip` with `unknown_evidence` when the requests cannot be attributed. +4. `skip` with `unknown_evidence` when threat detection flagged the output. +5. `success` for a run that succeeded. +6. `failure` when the agent reported that it could not finish or exhausted its + prompt, the main conversation recorded a refusal or content filter and the run + left no terminal output, the selected pair reached a step, token, credit, or + tool-denial limit (with or without output), or the validator rejected its + outputs or found no terminal output. +7. Otherwise `skip` with `unknown_evidence`, including an agent job that failed + after valid terminal output, and a run whose threat detection could not reach a + result: a warning or failure conclusion, a detector failure, or a failed or + cancelled detection job. As in the published `detection.result`, only the + conclusion's own result supplies a reason. + +The verdict is evidence of validated terminal completion, not of answer quality. +It uses only engine-neutral evidence (AWF's records, the job results, harness and +execution records, normalized refusal events, validated safe outputs, and threat +detection), so the same evidence gives the same verdict for every engine. It does +not decide whether a run may update routing history: re-runs, pull request runs, +and experiment workflows are excluded by the consumer that keeps that history. + #### Upstream errors **T-UAS-082 — Identifier-only proxy errors.** The collector maps AWF @@ -2799,6 +2865,11 @@ Native IDs can collide, timestamps can be out of order, and a trace can contain ## 13. Change Log (Informative) +### Version 2.14.0 - Draft (2026-11-23) + +- Added `routing.observation`, the conclusion collector's verdict on a routed run: `success`, `failure`, or `skip` with a reason, decided from AWF's request records, the job results, and the validated safe outputs (T-UAS-094). +- Retained serialization-format version 1. + ### Version 2.13.0 - Draft (2026-11-23) - Added the LangGraph native-session mapping for `messages_to_dict` trajectories, including human, AI, system, tool, invalid-tool-call, unknown-message, usage, and exit-status observations (T-UAS-093). diff --git a/pkg/cli/audit_report_render.go b/pkg/cli/audit_report_render.go index bae34367f6a..844406e32a0 100644 --- a/pkg/cli/audit_report_render.go +++ b/pkg/cli/audit_report_render.go @@ -268,6 +268,13 @@ func renderConsoleModelRouting(routing *ModelRoutingSummary) { fmt.Fprintf(os.Stderr, " failure: code=%s detail=%s\n", safeModelRoutingText(routing.Failure.Code), safeModelRoutingText(routing.Failure.Detail)) } + if observation := routing.Observation; observation != nil { + line := " observation: outcome=" + observation.Outcome + if observation.Reason != "" { + line += " reason=" + observation.Reason + } + fmt.Fprintln(os.Stderr, safeModelRoutingText(line)) + } fmt.Fprintf(os.Stderr, " cost_aic: classifier=%.3f selected_model=%.3f deviated=%.3f\n", routing.ClassifierCost.AIC, routing.SelectedModelCost.AIC, routing.DeviatedTrafficCost.AIC) if routing.MainAgentCost.Requests > 0 || routing.MainAgentCost.AIC > 0 { diff --git a/pkg/cli/model_routing.go b/pkg/cli/model_routing.go index e3155240313..13917c250ef 100644 --- a/pkg/cli/model_routing.go +++ b/pkg/cli/model_routing.go @@ -96,9 +96,17 @@ type ModelRoutingSummary struct { DeviatedTrafficCost ModelRoutingCost `json:"deviated_traffic_cost"` MainAgentCost ModelRoutingCost `json:"main_agent_cost,omitzero"` SubagentCosts []ModelRoutingAgentCost `json:"subagent_costs,omitempty"` + Observation *RoutingObservation `json:"observation,omitempty"` EndpointOnlyDeviationNormalized bool `json:"endpoint_only_deviation_normalized,omitempty"` } +// RoutingObservation is the unified session's verdict on a routed run (T-UAS-094): +// whether its result counts as evidence about the selected pair, and if not, why. +type RoutingObservation struct { + Outcome string `json:"outcome"` + Reason string `json:"reason,omitempty"` +} + type effectiveModelAttribution struct { Model string RequestedModel string @@ -267,8 +275,8 @@ func findModelRoutingFile(runDir string) string { return legacy } var found string - _ = filepath.WalkDir(runDir, func(path string, entry os.DirEntry, err error) error { - if err != nil || entry.IsDir() { + if err := filepath.WalkDir(runDir, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil || entry.IsDir() { return nil } if entry.Name() == "model-routing.jsonl" { @@ -276,7 +284,9 @@ func findModelRoutingFile(runDir string) string { return filepath.SkipAll } return nil - }) + }); err != nil { + tokenUsageSubagentLog.Printf("failed to search for model routing records: %v", err) + } return found } @@ -348,6 +358,7 @@ func applySessionModelRouting(summary *ModelRoutingSummary, session *sessionMode if summary == nil || session == nil { return } + summary.Observation = session.Observation routing := session.modelRouting() if routing == nil { return @@ -435,7 +446,11 @@ func parseModelRoutingFile(path string, usageEntries []TokenUsageEntry) *ModelRo if err != nil { return &ModelRoutingSummary{Status: "unavailable"} } - defer file.Close() + defer func() { + if closeErr := file.Close(); closeErr != nil { + tokenUsageSubagentLog.Printf("failed to close model routing records: %v", closeErr) + } + }() summary := &ModelRoutingSummary{ Status: "not_routed", diff --git a/pkg/cli/model_routing_session.go b/pkg/cli/model_routing_session.go index 612795aa71a..b5dbd9ec8a2 100644 --- a/pkg/cli/model_routing_session.go +++ b/pkg/cli/model_routing_session.go @@ -91,6 +91,7 @@ type sessionModelRoutingAttribution struct { Mismatches []ModelEndpointMismatch UnavailableSubagentModels []sessionSubagentModelUnavailable RetryEvents []sessionModelRoutingEvent + Observation *RoutingObservation } // ModelEndpointMismatch describes a model/API incompatibility reported by the unified session. @@ -247,10 +248,33 @@ func decodeSessionModelRoutingEvent(line []byte, lineNumber int, attribution *se unavailable.AgentName != "" && unavailable.DeclaredModel != "" && unavailable.Model != "" { attribution.UnavailableSubagentModels = append(attribution.UnavailableSubagentModels, unavailable) } + case event.Type == "routing.observation" && event.Provenance.Component == "collector" && event.Provenance.Phase == "conclusion": + attribution.Observation = parseRoutingObservation(event.Data, lineNumber) } return nil } +// parseRoutingObservation returns the verdict when it uses T-UAS-094's +// vocabulary: a known reason, and only with skip. +func parseRoutingObservation(data json.RawMessage, lineNumber int) *RoutingObservation { + var observation RoutingObservation + if json.Unmarshal(data, &observation) == nil { + switch observation.Outcome { + case "success", "failure": + if observation.Reason == "" { + return &observation + } + case "skip": + switch observation.Reason { + case "cancelled", "infrastructure", "rate_limited", "pair_mismatch", "unknown_evidence": + return &observation + } + } + } + auditReportLog.Printf("Ignoring invalid routing.observation on line %d", lineNumber) + return nil +} + func validModelEndpointMismatchData(data json.RawMessage) bool { var fields map[string]json.RawMessage if json.Unmarshal(data, &fields) != nil || fields == nil { diff --git a/pkg/cli/routing_observation_test.go b/pkg/cli/routing_observation_test.go new file mode 100644 index 00000000000..36b2242416f --- /dev/null +++ b/pkg/cli/routing_observation_test.go @@ -0,0 +1,49 @@ +//go:build !integration + +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +const routingObservationSkip = `{"outcome":"skip","reason":"unknown_evidence"}` + +func TestModelRoutingReadsRoutingObservation(t *testing.T) { + // The unified session collector's header and verdict for routed run + // 39508154330 when its agent job failed after valid output. + golden, err := os.ReadFile(filepath.Join("testdata", "routing-observation", "aw_session.jsonl")) + require.NoError(t, err) + header, verdict, _ := strings.Cut(strings.TrimSpace(string(golden)), "\n") + require.Contains(t, verdict, routingObservationSkip) + workflowInfo := `{"type":"workflow.info","data":{"engineId":"copilot","modelRouting":{"status":"selected","wireModel":"gpt-5.6-luna"}},"provenance":{"component":"workflow","phase":"activation","path":"aw_info.json","index":0}}` + + for name, tc := range map[string]struct { + verdict string + expected *RoutingObservation + }{ + "collector verdict": {verdict, &RoutingObservation{Outcome: "skip", Reason: "unknown_evidence"}}, + "counted verdict": {strings.Replace(verdict, routingObservationSkip, `{"outcome":"success"}`, 1), &RoutingObservation{Outcome: "success"}}, + "agent provenance": {strings.Replace(verdict, `"component":"collector"`, `"component":"agent"`, 1), nil}, + "unknown reason": {strings.Replace(verdict, `"unknown_evidence"`, `"experiment"`, 1), nil}, + "skip without a reason": {strings.Replace(verdict, routingObservationSkip, `{"outcome":"skip"}`, 1), nil}, + "success with a reason": {strings.Replace(verdict, `"outcome":"skip"`, `"outcome":"success"`, 1), nil}, + } { + t.Run(name, func(t *testing.T) { + runDir := t.TempDir() + writeSessionTestFile(t, runDir, "usage/aw_session.jsonl", header+"\n"+workflowInfo+"\n"+tc.verdict+"\n") + summary := analyzeModelRouting(runDir) + require.NotNil(t, summary) + require.Equal(t, tc.expected, summary.Observation) + }) + } + + console := captureStderrForGuardPolicyReportTest(func() { + renderConsoleModelRouting(&ModelRoutingSummary{Status: "selected", Observation: &RoutingObservation{Outcome: "skip", Reason: "unknown_evidence"}}) + }) + require.Contains(t, console, " observation: outcome=skip reason=unknown_evidence\n") +} diff --git a/pkg/cli/testdata/routing-observation/aw_session.jsonl b/pkg/cli/testdata/routing-observation/aw_session.jsonl new file mode 100644 index 00000000000..c0841875a87 --- /dev/null +++ b/pkg/cli/testdata/routing-observation/aw_session.jsonl @@ -0,0 +1,2 @@ +{"type":"session.format","data":{"version":1},"provenance":{"component":"collector","phase":"conclusion","path":"usage/aw_session.jsonl","index":0}} +{"type":"routing.observation","data":{"outcome":"skip","reason":"unknown_evidence"},"provenance":{"component":"collector","phase":"conclusion","path":"usage/aw_session.jsonl","index":1}} diff --git a/schemas/audit.schema.json b/schemas/audit.schema.json index ff566edf7bd..9cc2c5a9d23 100644 --- a/schemas/audit.schema.json +++ b/schemas/audit.schema.json @@ -3051,6 +3051,24 @@ "additionalProperties": false } }, + "observation": { + "type": [ + "null", + "object" + ], + "properties": { + "outcome": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "outcome" + ], + "additionalProperties": false + }, "endpoint_only_deviation_normalized": { "type": "boolean" } diff --git a/schemas/logs-jsonl.schema.json b/schemas/logs-jsonl.schema.json index 64d0a22d54f..88b7321e89e 100644 --- a/schemas/logs-jsonl.schema.json +++ b/schemas/logs-jsonl.schema.json @@ -3849,6 +3849,24 @@ "additionalProperties": false } }, + "observation": { + "type": [ + "null", + "object" + ], + "properties": { + "outcome": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "outcome" + ], + "additionalProperties": false + }, "endpoint_only_deviation_normalized": { "type": "boolean" } @@ -7272,6 +7290,24 @@ "additionalProperties": false } }, + "observation": { + "type": [ + "null", + "object" + ], + "properties": { + "outcome": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "outcome" + ], + "additionalProperties": false + }, "endpoint_only_deviation_normalized": { "type": "boolean" } diff --git a/schemas/logs.schema.json b/schemas/logs.schema.json index 15117c1af3e..4c9e0a35d26 100644 --- a/schemas/logs.schema.json +++ b/schemas/logs.schema.json @@ -4735,6 +4735,24 @@ "additionalProperties": false } }, + "observation": { + "type": [ + "null", + "object" + ], + "properties": { + "outcome": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "outcome" + ], + "additionalProperties": false + }, "endpoint_only_deviation_normalized": { "type": "boolean" }