diff --git a/.github/workflows/test-drift.yml b/.github/workflows/test-drift.yml index fff11bec..afd3f9c6 100644 --- a/.github/workflows/test-drift.yml +++ b/.github/workflows/test-drift.yml @@ -19,7 +19,7 @@ on: # guards": check the unit lane first — that is where the value pin lives. paths: - "src/agui-types.ts" - - "src/__tests__/drift/agui-schema.drift.ts" + - "src/__tests__/drift/agui-*.drift.ts" # PR-scoped live drift leg (drift-live-pr job): trigger when the drift # scripts, any drift test, or a drift workflow itself changes. - "scripts/drift-*.ts" @@ -47,8 +47,22 @@ jobs: - name: Clone ag-ui repo run: git clone --depth 1 https://github.com/ag-ui-protocol/ag-ui.git ../ag-ui - - name: Run AG-UI schema drift test - run: npx vitest run src/__tests__/drift/agui-schema.drift.ts --config vitest.config.drift.ts + # The positional argument is a vitest FILENAME FILTER (substring match on + # the test file path), NOT a single file — so this runs EVERY AG-UI drift + # file, and a future `agui-*.drift.ts` guard is picked up automatically + # instead of silently never running. `vitest.config.drift.ts` already + # scopes `include` to `src/__tests__/drift/**/*.drift.ts`, so the filter + # cannot pull in `*.test.ts` helpers from the same directory. + # + # NAMING CONTRACT: an AG-UI drift guard MUST be named + # `src/__tests__/drift/agui-.drift.ts` to land in this lane. + # + # This lane needs NO provider API keys — the AG-UI drift files compare + # `src/agui-types.ts` against the cloned canonical ag-ui repo only. Do not + # widen the filter to the whole drift config: that is `runDriftTests()`'s + # job in the credit-burning `drift` leg below, which does need keys. + - name: Run AG-UI schema drift tests + run: npx vitest run src/__tests__/drift/agui- --config vitest.config.drift.ts drift: if: github.event_name != 'pull_request' diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e915dd4..e675887e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,21 @@ ## [Unreleased] +### Added + +- **AG-UI subagent lifecycle events, and `subagentRunId` attribution mirrored where canonical declares it.** Upstream `@ag-ui/core` added `SUBAGENT_STARTED` / `SUBAGENT_FINISHED` / `SUBAGENT_ERROR` and threaded an optional `subagentRunId` through the events a subagent can emit; aimock's AG-UI types carried none of it. The three literals now join `AGUIEventType` and the `AGUIEvent` union, backed by `AGUISubagentStartedEvent` (required `subagentRunId` and `name`, optional `description` / `parentSubagentRunId`, plus `parentToolCallId` / `parentMessageId` so an agents-as-tools subagent can be correlated to the call that spawned it without inspecting `rawEvent.metadata`), `AGUISubagentFinishedEvent` (optional `result`, plus an `AGUISubagentFinishedOutcome` of `{ type: "success" }` or `{ type: "suspended"; interruptIds?: string[] }` — `AGUIRunFinishedOutcome` one level down, where absent still means success, `interruptIds` names only the run-level interrupts that subagent directly owns, and unlike `RUN_FINISHED.outcome` the field postdates the valueless-field cleanup so it never tolerates `null`), and `AGUISubagentErrorEvent` (`message`, optional `code`). `subagentRunId` itself is declared **per event, not on a shared base type**, because that is how canonical declares it: optional on 24 event interfaces, required on the three subagent events, and deliberately absent from `RUN_STARTED` / `RUN_FINISHED` / `RUN_ERROR`, `MESSAGES_SNAPSHOT` and the deprecated `THINKING_*` family. Putting it once on `AGUIBaseEvent` would have cleared the drift report while granting the field to events canonical does not give it. The same optional field is mirrored onto `AGUIMessage` and `AGUIInterrupt`. Canonical `types.ts` declares it INDEPENDENTLY on `BaseMessageSchema`, `ToolMessageSchema`, `ActivityMessageSchema` and `ReasoningMessageSchema` — the latter three are standalone `z.object`s that do NOT extend the base, so there is no inheritance carrying the field to them — and on `InterruptSchema`; aimock deliberately flattens the canonical message union into one `role`-discriminated `AGUIMessage`, which is why two edits cover all four message declarations. So a replayed message or approval request keeps the attribution that lets a client group it under the subagent that produced it instead of reading as root-raised. All four new names — the three event interfaces and `AGUISubagentFinishedOutcome` — are exported from both the package root and the `agui-stub` entrypoint, guarded by a public-surface test that fails whenever any `agui-types.ts` type is missing from either barrel. The `AGUIMessage` / `AGUIInterrupt` mirroring is NOT guarded: the existing drift suite walks `*EventSchema` declarations only and cannot see the non-event schemas, so nothing fails if that field is later dropped — closing that gap is deferred to the drift-harness rewrite rather than bolted on here. **Scope: this is a type surface only.** Unlike 1.39.0's `AGUITokenUsage`, which was reachable through `AGUIBuildOpts`, no RUNTIME code CONSUMES these types — they are exported and guarded, but `agui-handler.ts` gained no builder and no build option, so aimock can TYPE a subagent event but cannot yet EMIT one. Every added field is optional or sits on a new type, so existing fixtures and callers are byte-identical (#391) + ### Changed +- **The AG-UI drift CI lane runs every `agui-*.drift.ts` guard, not one hardcoded file.** The `agui-schema-drift` job in `.github/workflows/test-drift.yml` and `runAgUiDriftTests` in `scripts/drift-report-collector.ts` both invoked `npx vitest run src/__tests__/drift/agui-schema.drift.ts`. That positional argument is a vitest FILENAME FILTER (substring match on the test file path), not a single file, so both now pass the path prefix `src/__tests__/drift/agui-` and every AG-UI drift file runs — one today, and any future guard automatically — under a documented naming contract: an AG-UI drift guard MUST be named `src/__tests__/drift/agui-.drift.ts` to land in this lane. The workflow's `paths:` trigger widens to `src/__tests__/drift/agui-*.drift.ts` to match. `vitest.config.drift.ts` already scopes `include` to `src/__tests__/drift/**/*.drift.ts`, so the prefix cannot pull in `*.test.ts` helpers from the same directory, and the lane still needs no provider API keys — these files read `src/agui-types.ts` and the cloned canonical `../ag-ui` checkout only, unlike the credit-burning `drift` leg. The collector retains the single filename as report metadata (the file a human opens when drift is reported), no longer as a run target. - `aimock-pytest` 0.5.3 now defaults to `@copilotkit/aimock` 1.39.0. +### Fixed + +- **The AG-UI drift collector no longer reports "clean" for a failure it could not read.** `collectAgUiDriftEntries` recognizes three failure-message shapes; any FAILED assertion matching none of them was dropped outright — no entry, no counter, no warning — and a FAILED assertion carrying no message at all was skipped before it was even looked at. Both paths produced zero entries, exit 0 and `conclusion: "clean"`, so a genuinely failing `agui-schema.drift.ts` assertion (`should parse aimock event types` fails with a bare `expect` message that matches no shape) certified AG-UI as drift-free. Every such failure now takes the collector's EXISTING quarantine lane — held for review at exit 5, the same "never silently swallowed" contract the HTTP leg already used — per-assertion and unconditional, so an unreadable failure survives a mixed run in which other failures DID parse. Separately, a ZERO-exit AG-UI run whose stdout is not vitest JSON now THROWS instead of returning an empty (`"no failures"`) result, matching what the HTTP twin `runDriftTests()` has always done on the same condition: the two legs no longer disagree about whether garbage output is clean. Drift-harness tooling, not runtime behavior — no published surface changes (#391) + +- **The AG-UI drift suite's canonical-schema parser no longer drops the field declared after a trailing comment.** `extractExtendFields` stripped whole-line comments only (`/^\s*\/\/.*$/gm`). Upstream's `STATE_DELTA` declares `delta: z.array(z.any()), // JSON Patch (RFC 6902)`, and after the top-level comma split that trailing comment heads the NEXT entry, so the field-name match failed and the entry was discarded silently — which is why the drift report read canonical as declaring `subagentRunId` on 23 events rather than 24, and flagged `STATE_DELTA.subagentRunId` as aimock-only. Comments are now stripped wherever they appear; no canonical schema literal contains `//`, so the unconditional strip is safe. This is drift-harness tooling, not runtime behavior — no published surface changes (#391) + ## [1.39.0] - 2026-08-18 ### Added diff --git a/scripts/drift-report-collector.ts b/scripts/drift-report-collector.ts index 1d6ae80f..9a9318c1 100644 --- a/scripts/drift-report-collector.ts +++ b/scripts/drift-report-collector.ts @@ -10,7 +10,10 @@ * Exit codes: * 0 — no critical diffs found (or no drift at all) * 2 — at least one critical diff exists - * 5 — at least one failure was quarantined (unparseable/untrusted — needs review) + * 5 — at least one failure was quarantined (unparseable/untrusted — needs review). + * Covers BOTH legs: an HTTP failure that could not be mapped to a + * provider, and an AG-UI failure the collector could not structurally + * interpret. An uninterpretable failure is NEVER silently dropped. * 6 — at least one live leg timed out having observed ZERO messages: the * surface went silent, so nothing was graded there. Not drift, not a * collector fault, and NOT a clean baseline. @@ -102,6 +105,27 @@ const PROVIDER_LABEL_MAP: Record = { // --------------------------------------------------------------------------- const AGUI_TYPES_FILE = "src/agui-types.ts"; + +/** + * Vitest FILENAME FILTER (substring match on the test file path) selecting the + * whole AG-UI drift surface, not one hardcoded file. Keep this in lockstep with + * the `agui-schema-drift` job in `.github/workflows/test-drift.yml`, which runs + * the same filter. + * + * NAMING CONTRACT: an AG-UI drift guard MUST be named + * `src/__tests__/drift/agui-.drift.ts` so both consumers pick it up + * automatically; a differently-named file would silently never run. + * `vitest.config.drift.ts` scopes `include` to the drift-suffixed files, so the + * filter cannot pull in plain `.test.ts` helpers from the same directory. No + * provider API keys are required — these files compare `src/agui-types.ts` against the + * cloned canonical ag-ui repo only. + */ +const AGUI_DRIFT_TEST_FILTER = "src/__tests__/drift/agui-"; + +/** + * Report metadata only: the file a human should open when AG-UI drift is + * reported. Not a run target — see `AGUI_DRIFT_TEST_FILTER` for that. + */ const AGUI_DRIFT_TEST = "src/__tests__/drift/agui-schema.drift.ts"; // --------------------------------------------------------------------------- @@ -1476,52 +1500,130 @@ export function collectDriftEntries(results: VitestJsonResult): CollectResult { * Returns drift entries in the same DriftEntry format as HTTP API drift, * or an empty array if the canonical repo is unavailable or tests pass. */ -function ensureAgUiRepo(): boolean { - const agUiPath = resolve("..", "ag-ui"); +/** + * The one file the AG-UI drift tests actually read out of the canonical + * checkout. A directory merely NAMED `ag-ui` proves nothing: if this file is + * absent the drift suites' `describe.skipIf` gates fire and the whole AG-UI leg + * silently reports NOTHING — which the collector would otherwise certify as a + * clean baseline. Presence of this file is the checkout's usability test. + */ +export const AGUI_CANONICAL_TYPES_RELPATH = "sdks/typescript/packages/core/src/types.ts"; + +/** + * What a candidate `../ag-ui` directory actually is. + * + * - `ok` — a usable canonical checkout (the canonical types file is there). + * - `absent` — no such directory; cloning is the correct next step. + * - `incomplete` — a directory named `ag-ui` EXISTS but does not contain the + * canonical sources. This is a stale/wrong/partial checkout, + * NOT a git or network failure, and must be reported as such: + * misreporting it sends the reader hunting a network problem + * that isn't there while the drift leg grades nothing. + */ +export type AgUiCheckoutStatus = + | { kind: "ok" } + | { kind: "absent" } + | { kind: "incomplete"; reason: string }; + +/** + * Classify a candidate canonical AG-UI checkout. Pure w.r.t. the filesystem it + * is handed (no cloning, no mutation) so it is unit-testable against a temp dir. + */ +export function classifyAgUiCheckout(agUiPath: string): AgUiCheckoutStatus { + let isDir = false; try { - if (existsSync(agUiPath) && statSync(agUiPath).isDirectory()) { - return true; - } + isDir = existsSync(agUiPath) && statSync(agUiPath).isDirectory(); } catch (statErr: unknown) { const msg = statErr instanceof Error ? statErr.message : String(statErr); - console.warn(`Could not stat AG-UI repo path: ${msg}`); + return { + kind: "incomplete", + reason: `could not stat AG-UI repo path ${agUiPath}: ${msg}`, + }; } - { - // Not present — try to clone - console.log("AG-UI canonical repo not found. Cloning..."); - try { - execSync("git clone --depth 1 https://github.com/ag-ui-protocol/ag-ui.git ../ag-ui", { - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - timeout: 60_000, - }); - console.log("AG-UI repo cloned successfully."); - return true; - } catch (cloneErr: unknown) { - const msg = cloneErr instanceof Error ? cloneErr.message : String(cloneErr); - console.warn(`Could not clone AG-UI repo: ${msg}`); - console.warn("AG-UI schema drift detection will be skipped."); - return false; - } + if (!isDir) return { kind: "absent" }; + if (!existsSync(resolve(agUiPath, AGUI_CANONICAL_TYPES_RELPATH))) { + return { + kind: "incomplete", + reason: + `${agUiPath} exists but ${AGUI_CANONICAL_TYPES_RELPATH} is missing — the canonical ` + + `AG-UI checkout is STALE or INCOMPLETE. This is not a git/network failure: remove the ` + + `directory and re-clone (git clone --depth 1 https://github.com/ag-ui-protocol/ag-ui.git).`, + }; } + return { kind: "ok" }; } -function runAgUiDriftTests(): VitestJsonResult | null { - if (!ensureAgUiRepo()) return null; +function ensureAgUiRepo(): boolean { + const agUiPath = resolve("..", "ag-ui"); + const status = classifyAgUiCheckout(agUiPath); + if (status.kind === "ok") return true; + if (status.kind === "incomplete") { + // N5: do NOT proceed. Running the drift suites against an unusable checkout + // makes every AG-UI assertion skip, and a leg that graded nothing must never + // be able to certify AG-UI as drift-free. + console.warn(`AG-UI canonical checkout unusable: ${status.reason}`); + console.warn("AG-UI schema drift detection will be skipped."); + return false; + } + // Not present — try to clone + console.log("AG-UI canonical repo not found. Cloning..."); try { - const stdout = execSync( - `npx vitest run ${AGUI_DRIFT_TEST} --config vitest.config.drift.ts --reporter=json`, - { - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - maxBuffer: 50 * 1024 * 1024, - }, + execSync("git clone --depth 1 https://github.com/ag-ui-protocol/ag-ui.git ../ag-ui", { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + timeout: 60_000, + }); + } catch (cloneErr: unknown) { + const msg = cloneErr instanceof Error ? cloneErr.message : String(cloneErr); + console.warn(`Could not clone AG-UI repo: ${msg}`); + console.warn("AG-UI schema drift detection will be skipped."); + return false; + } + // A clone that "succeeded" but still lacks the canonical sources is the same + // unusable checkout as above — re-verify rather than assume. + const afterClone = classifyAgUiCheckout(agUiPath); + if (afterClone.kind !== "ok") { + console.warn( + `AG-UI repo cloned but the checkout is still unusable: ` + + `${afterClone.kind === "incomplete" ? afterClone.reason : `${agUiPath} is absent`}`, + ); + console.warn("AG-UI schema drift detection will be skipped."); + return false; + } + console.log("AG-UI repo cloned successfully."); + return true; +} + +/** How the AG-UI leg shells out. Injectable so the parse contract is testable. */ +export type VitestExec = (command: string) => string; + +const defaultAgUiExec: VitestExec = (command) => + execSync(command, { + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + maxBuffer: 50 * 1024 * 1024, + }); + +/** + * Run the AG-UI drift lane and return its vitest JSON. + * + * `null` means the leg could not run at all (infra) — the caller maps that to + * the collector's exit-1 "skipped" lane. + * + * FAIL-CLOSED (twin symmetry): a ZERO-exit run whose stdout cannot be parsed as + * vitest JSON THROWS, exactly as the HTTP twin `runDriftTests()` does. It used + * to `return { testResults: [] }` — an empty result the collector reads as "no + * failures", i.e. exit 0 / `conclusion: "clean"` — so a lane that produced + * garbage instead of a report certified AG-UI as drift-free. The two legs face + * the same condition and must not disagree about whether it is clean. + */ +export function runAgUiVitest(exec: VitestExec = defaultAgUiExec): VitestJsonResult | null { + let stdout: string; + try { + stdout = exec( + `npx vitest run ${AGUI_DRIFT_TEST_FILTER} --config vitest.config.drift.ts --reporter=json`, ); - const result = parseVitestOutput(stdout, "AG-UI drift JSON parse of successful run failed"); - if (result) return result; - // Tests passed, no failures — return empty result - return { testResults: [] }; } catch (err: unknown) { if (hasStdout(err)) { const result = parseVitestOutput(err.stdout, "AG-UI drift JSON parse of failed run"); @@ -1531,6 +1633,14 @@ function runAgUiDriftTests(): VitestJsonResult | null { console.warn(`AG-UI schema drift tests failed to run: ${msg}`); return null; } + const result = parseVitestOutput(stdout, "AG-UI drift JSON parse of successful run failed"); + if (result) return result; + throw new Error("AG-UI drift tests passed but produced unparseable output"); +} + +function runAgUiDriftTests(): VitestJsonResult | null { + if (!ensureAgUiRepo()) return null; + return runAgUiVitest(); } /** @@ -1543,9 +1653,26 @@ function runAgUiDriftTests(): VitestJsonResult | null { * * These are converted to DriftEntry objects that point at `src/agui-types.ts` * as the builder file (the file that needs fixing). + * + * FAIL-CLOSED INVARIANT (W5/N1): a FAILED AG-UI assertion this function cannot + * structurally interpret MUST NOT vanish. Previously any failure that matched + * none of the recognizers above was dropped — no entry, no counter, no warning — + * so a genuinely failing assertion in `agui-schema.drift.ts` (e.g. `should parse + * aimock event types`, whose bare `expect` message matches none of the three + * shapes) produced zero entries, exit 0 and `conclusion: "clean"`. The same went + * for a FAILED assertion carrying no message at all. Every such failure is now returned + * as a `QuarantineEntry`, reusing the collector's EXISTING quarantine/exit-5 + * lane — the same "held for review, never silently swallowed" contract the HTTP + * leg already uses. Note this is per-assertion and UNCONDITIONAL: unlike the + * HTTP leg's `entries.length === 0`-gated rescue, an unrecognized AG-UI failure + * survives a mixed run in which other failures DID parse. */ -function collectAgUiDriftEntries(results: VitestJsonResult): DriftEntry[] { +export function collectAgUiDriftEntries(results: VitestJsonResult): { + entries: DriftEntry[]; + quarantine: QuarantineEntry[]; +} { const entries: DriftEntry[] = []; + const quarantine: QuarantineEntry[] = []; // Accumulate all diffs across assertions into a single entry per scenario const missingTypesDiffs: ParsedDiff[] = []; @@ -1554,7 +1681,23 @@ function collectAgUiDriftEntries(results: VitestJsonResult): DriftEntry[] { for (const file of results.testResults) { for (const assertion of file.assertionResults) { if (assertion.status !== "failed") continue; - if (assertion.failureMessages.length === 0) continue; + + const testNameForQuarantine = + `${assertion.ancestorTitles.join(" ")} > ${assertion.title}`.trim(); + + if (assertion.failureMessages.length === 0) { + // A FAILED assertion carrying no message is the least interpretable + // failure there is — the collector cannot even see what broke. Skipping + // it read as exit 0 / "clean", which is the same fail-open the + // quarantine lane below exists to close, so it takes the same lane. + quarantine.push({ + provider: "AG-UI", + testName: testNameForQuarantine, + rawLocation: "", + message: "AG-UI drift assertion failed with no failure message reported by vitest.", + }); + continue; + } const fullMessage = assertion.failureMessages.join("\n"); const testName = assertion.title || assertion.ancestorTitles.join(" > "); @@ -1600,11 +1743,11 @@ function collectAgUiDriftEntries(results: VitestJsonResult): DriftEntry[] { // If THIS assertion did not extract any structured data, try a generic fallback const thisAssertionExtracted = missingTypesDiffs.length > missingTypesBefore || fieldDriftDiffs.length > fieldDriftBefore; - if ( + const genericCritical = !thisAssertionExtracted && (fullMessage.includes("Missing event types") || - fullMessage.includes("Critical field drift")) - ) { + fullMessage.includes("Critical field drift")); + if (genericCritical) { // Generic critical failure from the ag-ui schema drift test missingTypesDiffs.push({ severity: "critical", @@ -1615,6 +1758,20 @@ function collectAgUiDriftEntries(results: VitestJsonResult): DriftEntry[] { mock: "(see test output)", }); } + + if (!thisAssertionExtracted && !genericCritical) { + // The fail-closed lane. This assertion FAILED and none of the shapes + // above claimed it, so the collector cannot say what drifted — but it + // absolutely must not say "clean". Held for review (exit 5), with the + // raw pre-strip frame so a human can find the assertion, exactly as the + // HTTP leg quarantines its unmappable failures. + quarantine.push({ + provider: "AG-UI", + testName: testNameForQuarantine, + rawLocation: extractRawLocation(fullMessage), + message: fullMessage, + }); + } } } @@ -1642,7 +1799,16 @@ function collectAgUiDriftEntries(results: VitestJsonResult): DriftEntry[] { }); } - return entries; + if (quarantine.length > 0) { + console.warn( + `WARNING: ${quarantine.length} AG-UI drift failure(s) could not be interpreted by the ` + + `collector — quarantined for review (exit 5), NOT reported as clean:`, + ); + for (const q of quarantine) + console.warn(` - ${q.testName} @ ${q.rawLocation || ""}`); + } + + return { entries, quarantine }; } // --------------------------------------------------------------------------- @@ -1732,15 +1898,18 @@ function main(): void { const agUiResults = runAgUiDriftTests(); const agUiSkipped = agUiResults === null; let agUiEntries: DriftEntry[] = []; + let agUiQuarantine: QuarantineEntry[] = []; if (agUiResults) { console.log("Collecting AG-UI schema drift entries..."); - agUiEntries = collectAgUiDriftEntries(agUiResults); + const agUiResult = collectAgUiDriftEntries(agUiResults); + agUiEntries = agUiResult.entries; + agUiQuarantine = agUiResult.quarantine; } else { console.warn("WARNING: AG-UI schema drift tests could not run — results will be incomplete."); } const entries = [...httpEntries, ...agUiEntries]; - const quarantine = httpResult.quarantine; + const quarantine = [...httpResult.quarantine, ...agUiQuarantine]; const timeouts = httpResult.timeouts; const criticalCount = entries.reduce( @@ -1779,6 +1948,7 @@ function main(): void { console.log(` AG-UI schema entries: SKIPPED (could not run tests)`); } else { console.log(` AG-UI schema entries: ${agUiEntries.length}`); + console.log(` AG-UI uninterpretable failures (quarantined): ${agUiQuarantine.length}`); } console.log(` Total entries: ${entries.length}`); console.log(` Critical diffs: ${criticalCount}`); diff --git a/src/__tests__/agui-barrel-exports.test.ts b/src/__tests__/agui-barrel-exports.test.ts new file mode 100644 index 00000000..9b54100d --- /dev/null +++ b/src/__tests__/agui-barrel-exports.test.ts @@ -0,0 +1,138 @@ +import { describe, it, expect } from "vitest"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import ts from "typescript"; + +// --------------------------------------------------------------------------- +// Public-surface guard: every type declared in src/agui-types.ts must be +// re-exported from both barrels that front it — the package root (src/index.ts) +// and the "./agui" subpath entry (src/agui-stub.ts). A type that exists but is +// unreachable from an entry point cannot be named by a consumer, and the +// omission is invisible to the compiler, so it needs an explicit test. +// +// The property under test is *reachability under the declared name*, so the +// files are read with the TypeScript parser rather than with regexes. A regex +// scan of TypeScript fails open in exactly the ways this guard must not: a +// comma inside a comment corrupts a naively split export block, and `X as Y` +// looks like an export of `X` while actually making `X` unreachable. The +// parser sees comments as trivia and models a rename as a distinct +// `propertyName`/`name` pair, so both cases are handled by construction. +// +// A runtime import cannot be used here: these are type-only exports, erased +// before any module is evaluated, so there is nothing to inspect at runtime. +// Parsing the module graph is the closest sound check available at this cost. +// --------------------------------------------------------------------------- + +const TYPES_MODULE = "./agui-types.js"; + +const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8"); + +const parse = (fileName: string, source: string) => + ts.createSourceFile(fileName, source, ts.ScriptTarget.ES2022, true, ts.ScriptKind.TS); + +const isExported = (node: ts.Node) => + ts.canHaveModifiers(node) && + (ts.getModifiers(node) ?? []).some((m) => m.kind === ts.SyntaxKind.ExportKeyword); + +/** Names of the exported `type` / `interface` declarations in a source file. */ +function declaredTypeNames(fileName: string, source: string): string[] { + const names: string[] = []; + for (const statement of parse(fileName, source).statements) { + if (!ts.isTypeAliasDeclaration(statement) && !ts.isInterfaceDeclaration(statement)) continue; + if (!isExported(statement)) continue; + names.push(statement.name.text); + } + return names; +} + +/** + * Names of `./agui-types.js` that a barrel makes reachable *under their own + * name*. A renamed re-export (`export type { X as Y }`) publishes `Y` and + * leaves `X` unreachable, so it contributes nothing to this set: neither `X` + * (not reachable) nor `Y` (not a name declared in agui-types.ts). + * A star re-export makes every name reachable, so it short-circuits to `true`. + */ +function reExportedFromTypes(fileName: string, source: string): Set | true { + const names = new Set(); + for (const statement of parse(fileName, source).statements) { + if (!ts.isExportDeclaration(statement)) continue; + const specifier = statement.moduleSpecifier; + if (!specifier || !ts.isStringLiteral(specifier) || specifier.text !== TYPES_MODULE) continue; + // `export * from "./agui-types.js"` re-exports everything under its own name. + if (!statement.exportClause) return true; + if (!ts.isNamedExports(statement.exportClause)) continue; + for (const element of statement.exportClause.elements) { + const exportedAs = element.name.text; + const local = element.propertyName?.text ?? exportedAs; + if (local === exportedAs) names.add(exportedAs); + } + } + return names; +} + +const typeNames = declaredTypeNames("agui-types.ts", read("../agui-types.ts")); + +describe("AG-UI type barrel exports", () => { + it("declares the subagent types it is meant to publish", () => { + expect(typeNames).toEqual( + expect.arrayContaining([ + "AGUISubagentStartedEvent", + "AGUISubagentFinishedEvent", + "AGUISubagentErrorEvent", + "AGUISubagentFinishedOutcome", + ]), + ); + }); + + it.each([ + ["src/index.ts", "../index.ts"], + ["src/agui-stub.ts", "../agui-stub.ts"], + ])("re-exports every agui-types.ts type from %s", (label, rel) => { + const exported = reExportedFromTypes(label, read(rel)); + if (exported === true) return; + // Positive control: a total parse failure would yield an empty set and let + // every assertion below pass vacuously. + expect(exported.size).toBeGreaterThan(0); + const missing = typeNames.filter((name) => !exported.has(name)); + expect(missing).toEqual([]); + }); +}); + +// The guard is only as good as its reader, so the reader is tested directly on +// the two shapes that defeat a regex-based implementation. +describe("barrel export reader", () => { + it("ignores commas inside comments in an export block", () => { + const source = [ + "export type {", + " AGUIAlpha,", + " // a comment, with a comma, in it", + " AGUIBeta,", + '} from "./agui-types.js";', + ].join("\n"); + expect(reExportedFromTypes("barrel.ts", source)).toEqual(new Set(["AGUIAlpha", "AGUIBeta"])); + }); + + it("does not treat a renamed re-export as reachability of the original name", () => { + const source = 'export type { AGUIAlpha as AGUIRenamed, AGUIBeta } from "./agui-types.js";'; + expect(reExportedFromTypes("barrel.ts", source)).toEqual(new Set(["AGUIBeta"])); + }); + + it("ignores re-exports from other modules", () => { + const source = 'export type { AGUIAlpha } from "./somewhere-else.js";'; + expect(reExportedFromTypes("barrel.ts", source)).toEqual(new Set()); + }); + + it("treats a star re-export as publishing every name", () => { + expect(reExportedFromTypes("barrel.ts", 'export * from "./agui-types.js";')).toBe(true); + }); + + it("reads exported type and interface declarations, and skips unexported ones", () => { + const source = [ + "export type AGUIAlpha = string;", + "export interface AGUIBeta { a: number }", + "interface AGUIPrivate { b: number }", + "type AGUIAlsoPrivate = number;", + ].join("\n"); + expect(declaredTypeNames("types.ts", source)).toEqual(["AGUIAlpha", "AGUIBeta"]); + }); +}); diff --git a/src/__tests__/drift-collector.test.ts b/src/__tests__/drift-collector.test.ts index d68f935f..dca7ec2f 100644 --- a/src/__tests__/drift-collector.test.ts +++ b/src/__tests__/drift-collector.test.ts @@ -16,7 +16,7 @@ * report, and the stack-frame layout are exactly what vitest emits. */ -import { describe, it, expect } from "vitest"; +import { describe, it, expect, beforeEach, afterEach } from "vitest"; import { formatDriftReport } from "./drift/schema.js"; import type { ShapeDiff } from "./drift/schema.js"; import { @@ -26,6 +26,10 @@ import { extractScenario, parseKnownModelsCanary, collectDriftEntries, + collectAgUiDriftEntries, + runAgUiVitest, + classifyAgUiCheckout, + AGUI_CANONICAL_TYPES_RELPATH, computeExitCode, conclusionForExitCode, classifyUnparseableAsInfra, @@ -45,8 +49,17 @@ import type { ParsedDiff, } from "../../scripts/drift-types.js"; import { SURFACE_REGISTRY, KNOWN_SURFACE_SLUGS, isKnownSurface } from "./drift/surface-registry.js"; -import { existsSync, readFileSync, readdirSync } from "node:fs"; -import { resolve } from "node:path"; +import { + existsSync, + readFileSync, + readdirSync, + mkdtempSync, + mkdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { resolve, join } from "node:path"; +import { tmpdir } from "node:os"; import { isBaseReportReusable, computeDelta } from "../../scripts/drift-delta.js"; import type { DriftReport } from "../../scripts/drift-types.js"; @@ -3253,3 +3266,211 @@ describe("WS-5 — SURFACE_REGISTRY coverage & integrity", () => { expect(new Set(labels).size).toBe(labels.length); }); }); + +// --------------------------------------------------------------------------- +// AG-UI leg: the collector must never report "clean" when it cannot see +// --------------------------------------------------------------------------- +// +// The AG-UI leg used to DROP any failed assertion whose message matched none of +// its three recognizers — no entry, no counter, no warning — so a genuinely +// failing guard produced zero entries, exit 0 and `conclusion: "clean"`. That is +// a PRE-EXISTING hole in the EXISTING `agui-schema.drift.ts`: two of its +// assertions (`should parse aimock event types`, and any bare `expect` outside +// the three recognized report shapes) fail with messages no recognizer claims. +// The fixtures below are REAL vitest `--reporter=json` failure messages captured +// by mutating `src/agui-types.ts` (renaming `TEXT_MESSAGE_START` in +// `AGUIEventType`) and running +// `vitest run src/__tests__/drift/agui- --config vitest.config.drift.ts +// --reporter=json`. They are not hand-authored: the single-glyph `…(N)` ellipsis, +// the `AssertionError:` prefix and the frame layout are exactly what vitest emits. + +/** Real failure of an EXISTING agui-schema.drift.ts assertion — matches NO recognizer. */ +const AGUI_UNPARSEABLE_SCHEMA_FAILURE = [ + "AssertionError: expected [ Array(36) ] to include 'TEXT_MESSAGE_START'", + " at Proxy. (file:///repo/node_modules/.pnpm/@vitest+expect@3.2.4/node_modules/@vitest/expect/dist/index.js:1191:15)", + " at /repo/src/__tests__/drift/agui-schema.drift.ts:404:25", +].join("\n"); + +/** Real failure that IS recognized (the missing-event-type shape). */ +const AGUI_MISSING_TYPE_FAILURE = [ + "AssertionError: Missing event types:", + `[CRITICAL] Event type "TEXT_MESSAGE_START" exists in canonical @ag-ui/core but is missing from aimock AGUIEventType: expected [ { severity: 'CRITICAL', …(1) } ] to deeply equal []`, + " at /repo/src/__tests__/drift/agui-schema.drift.ts:422:58", +].join("\n"); + +describe("collectAgUiDriftEntries — fail-closed on uninterpretable failures", () => { + it("quarantines a failed AG-UI assertion it cannot interpret instead of reporting clean", () => { + const result = collectAgUiDriftEntries( + makeResult([ + makeAssertion({ + ancestorTitles: ["AG-UI schema drift"], + title: "should parse aimock event types", + failureMessages: [AGUI_UNPARSEABLE_SCHEMA_FAILURE], + }), + ]), + ); + + expect(result.entries).toEqual([]); + expect(result.quarantine).toHaveLength(1); + expect(result.quarantine[0].provider).toBe("AG-UI"); + expect(result.quarantine[0].testName).toContain("should parse aimock event types"); + expect(result.quarantine[0].rawLocation).toBe( + "/repo/src/__tests__/drift/agui-schema.drift.ts:404:25", + ); + expect(result.quarantine[0].message).toBe(AGUI_UNPARSEABLE_SCHEMA_FAILURE); + + // The invariant, stated as the collector's terminal signal: a run that + // could not interpret a real failure must NOT be a reusable clean baseline. + const exitCode = computeExitCode(0, result.quarantine.length, false, 0); + expect(exitCode).toBe(5); + expect(conclusionForExitCode(exitCode)).toBe("quarantine"); + }); + + it("surfaces an uninterpretable failure even on a MIXED run that also produced entries", () => { + // Regression for the HTTP leg's `entries.length === 0` gating being copied + // here: an unrecognized AG-UI failure must survive alongside a parsed one. + const result = collectAgUiDriftEntries( + makeResult([ + makeAssertion({ + ancestorTitles: ["AG-UI schema drift"], + title: "should parse aimock event types", + failureMessages: [AGUI_UNPARSEABLE_SCHEMA_FAILURE], + }), + makeAssertion({ + ancestorTitles: ["AG-UI schema drift"], + title: "all canonical event types are present in aimock", + failureMessages: [AGUI_MISSING_TYPE_FAILURE], + }), + ]), + ); + + expect(result.entries).toHaveLength(1); + expect(result.entries[0].provider).toBe("AG-UI"); + expect(result.quarantine).toHaveLength(1); + expect(result.quarantine[0].testName).toContain("should parse aimock event types"); + expect(result.quarantine[0].rawLocation).toBe( + "/repo/src/__tests__/drift/agui-schema.drift.ts:404:25", + ); + }); + + it("does not quarantine a failure it DID interpret", () => { + const result = collectAgUiDriftEntries( + makeResult([ + makeAssertion({ + ancestorTitles: ["AG-UI schema drift"], + title: "all canonical event types are present in aimock", + failureMessages: [AGUI_MISSING_TYPE_FAILURE], + }), + ]), + ); + expect(result.quarantine).toEqual([]); + expect(result.entries).toHaveLength(1); + expect(result.entries[0].diffs[0].path).toBe("AGUIEventType.TEXT_MESSAGE_START"); + }); + + it("stays silent on passing assertions", () => { + const result = collectAgUiDriftEntries( + makeResult([makeAssertion({ status: "passed", failureMessages: [] })]), + ); + expect(result.entries).toEqual([]); + expect(result.quarantine).toEqual([]); + expect(computeExitCode(0, 0, false, 0)).toBe(0); + }); + + it("quarantines a FAILED assertion that carries no failure message at all", () => { + // A failed assertion with an empty `failureMessages` array is the LEAST + // interpretable failure there is, so it belongs in the same fail-closed lane + // as an unrecognized message — not skipped as if the run were clean. The + // collector used to `continue` past it, which read as exit 0 / "clean" and + // re-opened the exact hole the quarantine lane exists to close. + const result = collectAgUiDriftEntries( + makeResult([ + makeAssertion({ + status: "failed", + ancestorTitles: ["AG-UI schema drift"], + title: "event field shapes match canonical schemas", + failureMessages: [], + }), + ]), + ); + expect(result.entries).toEqual([]); + expect(result.quarantine).toHaveLength(1); + expect(result.quarantine[0].provider).toBe("AG-UI"); + expect(result.quarantine[0].testName).toContain("event field shapes match canonical schemas"); + expect(result.quarantine[0].rawLocation).toBe(""); + expect(result.quarantine[0].message).toMatch(/no failure message/i); + + const exitCode = computeExitCode(0, result.quarantine.length, false, 0); + expect(exitCode).toBe(5); + expect(conclusionForExitCode(exitCode)).toBe("quarantine"); + }); +}); + +describe("runAgUiVitest — a zero-exit run with unparseable stdout is never clean", () => { + // TWIN SYMMETRY: the HTTP leg's `runDriftTests()` throws + // "Drift tests passed but produced unparseable output" on exactly this + // condition. The AG-UI leg used to return `{ testResults: [] }`, which the + // collector reads as "no failures" — exit 0, `conclusion: "clean"` — so a lane + // that emitted garbage instead of a report certified AG-UI as drift-free. + + it("throws on a zero-exit run whose stdout is not vitest JSON", () => { + expect(() => runAgUiVitest(() => "vitest crashed before writing a report")).toThrow( + /unparseable output/i, + ); + }); + + it("returns the parsed result when the zero-exit stdout IS vitest JSON", () => { + expect(runAgUiVitest(() => JSON.stringify({ testResults: [] }))).toEqual({ testResults: [] }); + }); + + it("still returns null (infra skip, exit 1) when the lane could not run at all", () => { + expect( + runAgUiVitest(() => { + throw new Error("spawn npx ENOENT"); + }), + ).toBeNull(); + }); +}); + +describe("classifyAgUiCheckout — a directory named ag-ui is not a canonical checkout", () => { + let tmpRoot: string; + + beforeEach(() => { + tmpRoot = mkdtempSync(join(tmpdir(), "agui-checkout-")); + }); + afterEach(() => { + rmSync(tmpRoot, { recursive: true, force: true }); + }); + + it('reports a missing directory as "absent" (cloning is the right next step)', () => { + expect(classifyAgUiCheckout(join(tmpRoot, "ag-ui"))).toEqual({ kind: "absent" }); + }); + + it('reports a stale/incomplete checkout as "incomplete", not a git/network failure', () => { + const agUi = join(tmpRoot, "ag-ui"); + mkdirSync(join(agUi, "sdks", "typescript", "packages", "core"), { recursive: true }); + const status = classifyAgUiCheckout(agUi); + expect(status.kind).toBe("incomplete"); + // The message must name the real problem, not send the reader after git. + const reason = status.kind === "incomplete" ? status.reason : ""; + expect(reason).toContain(AGUI_CANONICAL_TYPES_RELPATH); + expect(reason).toMatch(/STALE or INCOMPLETE/); + expect(reason).toMatch(/not a git\/network failure/); + }); + + it("accepts a checkout that actually carries the canonical types file", () => { + const agUi = join(tmpRoot, "ag-ui"); + const canonicalDir = join(agUi, "sdks", "typescript", "packages", "core", "src"); + mkdirSync(canonicalDir, { recursive: true }); + writeFileSync(join(canonicalDir, "types.ts"), "export type Placeholder = never;\n"); + expect(classifyAgUiCheckout(agUi)).toEqual({ kind: "ok" }); + }); + + it("an unusable checkout lands on the AG-UI-skipped lane, never on clean", () => { + // ensureAgUiRepo returns false for an incomplete checkout, which main() maps + // to agUiSkipped=true → exit 1 / "skipped". The point is that it is NOT 0. + const exitCode = computeExitCode(0, 0, true, 0); + expect(exitCode).toBe(1); + expect(conclusionForExitCode(exitCode)).toBe("skipped"); + }); +}); diff --git a/src/agui-stub.ts b/src/agui-stub.ts index 6dd0ab01..bd9ca03a 100644 --- a/src/agui-stub.ts +++ b/src/agui-stub.ts @@ -28,6 +28,9 @@ export type { AGUIReasoningMessageChunkEvent, AGUIReasoningEndEvent, AGUIReasoningEncryptedValueEvent, + AGUISubagentStartedEvent, + AGUISubagentFinishedEvent, + AGUISubagentErrorEvent, AGUIRawEvent, AGUICustomEvent, AGUIThinkingStartEvent, @@ -47,6 +50,7 @@ export type { AGUIInterrupt, AGUIResumeEntry, AGUIRunFinishedOutcome, + AGUISubagentFinishedOutcome, AGUITokenUsage, AGUIFixtureMatch, AGUIFixture, diff --git a/src/agui-types.ts b/src/agui-types.ts index eada59bb..e2274b14 100644 --- a/src/agui-types.ts +++ b/src/agui-types.ts @@ -397,6 +397,11 @@ export interface AGUIInterrupt { responseSchema?: Record; expiresAt?: string; metadata?: Record; + // The subagent whose work raised this interrupt; absent when the root raised + // it. Attribution sits on each interrupt rather than on the run because one + // run can carry interrupts from several subagents, so a consumer can render + // the request inside its own subagent's group. + subagentRunId?: string; } export interface AGUIResumeEntry { @@ -473,6 +478,7 @@ export interface AGUIMessage { error?: string; toolCallId?: string; toolCalls?: AGUIToolCall[]; + subagentRunId?: string; } export interface AGUIToolDefinition { diff --git a/src/index.ts b/src/index.ts index 3479d32c..38bfb1d5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -281,6 +281,10 @@ export type { AGUIReasoningEndEvent, AGUIReasoningEncryptedValueEvent, AGUIReasoningEncryptedValueSubtype, + // Subagent events + AGUISubagentStartedEvent, + AGUISubagentFinishedEvent, + AGUISubagentErrorEvent, // Special events AGUIRawEvent, AGUICustomEvent, @@ -294,6 +298,7 @@ export type { AGUIInterrupt, AGUIResumeEntry, AGUIRunFinishedOutcome, + AGUISubagentFinishedOutcome, AGUITokenUsage, } from "./agui-types.js"; export type { AGUIBuildOpts } from "./agui-handler.js";