From 5228b2a6e2e03ad1e2de128495cdd867ab32153b Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 13:51:41 -0700 Subject: [PATCH 01/10] fix(agui): export the subagent event types from the public barrels The subagent lifecycle types added alongside SUBAGENT_STARTED / SUBAGENT_FINISHED / SUBAGENT_ERROR were declared in src/agui-types.ts but never re-exported, so no consumer of the package root or of the "./agui" subpath could name them. Export AGUISubagentStartedEvent, AGUISubagentFinishedEvent, AGUISubagentErrorEvent and AGUISubagentFinishedOutcome from both barrels, and add a public-surface test that fails whenever any agui-types.ts type is missing from either. --- src/__tests__/agui-barrel-exports.test.ts | 59 +++++++++++++++++++++++ src/agui-stub.ts | 4 ++ src/index.ts | 5 ++ 3 files changed, 68 insertions(+) create mode 100644 src/__tests__/agui-barrel-exports.test.ts diff --git a/src/__tests__/agui-barrel-exports.test.ts b/src/__tests__/agui-barrel-exports.test.ts new file mode 100644 index 00000000..d9e9938e --- /dev/null +++ b/src/__tests__/agui-barrel-exports.test.ts @@ -0,0 +1,59 @@ +import { describe, it, expect } from "vitest"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// 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. +// --------------------------------------------------------------------------- + +const read = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), "utf8"); + +/** Names of the `export type` / `export interface` declarations in a source file. */ +function declaredTypeNames(source: string): string[] { + return [...source.matchAll(/^export (?:type|interface) ([A-Za-z0-9_]+)/gm)].map((m) => m[1]); +} + +/** Names re-exported from "./agui-types.js" by a barrel file. */ +function reExportedFromTypes(source: string): Set { + const names = new Set(); + for (const block of source.matchAll(/export type \{([^}]*)\} from "\.\/agui-types\.js";/g)) { + for (const raw of block[1].split(",")) { + const name = raw + .replace(/\/\/[^\n]*/g, "") + .trim() + .split(/\s+as\s+/)[0] + .trim(); + if (name) names.add(name); + } + } + return names; +} + +const typeNames = declaredTypeNames(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(read(rel)); + expect(exported.size).toBeGreaterThan(0); + const missing = typeNames.filter((name) => !exported.has(name)); + expect(missing).toEqual([]); + }); +}); 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/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"; From e5f8da69d2f1a3c50c44f6dd51a697ca055e9f1f Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 13:53:19 -0700 Subject: [PATCH 02/10] fix(agui): mirror canonical subagentRunId onto messages and interrupts `AGUIMessage` and `AGUIInterrupt` dropped the optional `subagentRunId` that `@ag-ui/core` declares on `BaseMessageSchema`, the three standalone message schemas, and `InterruptSchema`. A replayed message or approval request lost the attribution that lets a client group it under the subagent that produced it, and read as root-raised instead. The existing AG-UI drift suite only walks `*EventSchema` against `AGUI*Event` interfaces, so it could not see this. Adds `agui-nonevent-schema.drift.ts`, which compares the canonical non-event schemas that carry `subagentRunId` against the aimock interfaces that mirror them, plus a type-level guard. Scoped to `subagentRunId`; broader non-event field drift is tracked separately. Note: tsconfig.json excludes src/__tests__, so the type-level guard is not covered by `pnpm build` and must be typechecked explicitly. --- .../drift/agui-nonevent-schema.drift.ts | 152 ++++++++++++++++++ src/agui-types.ts | 6 + 2 files changed, 158 insertions(+) create mode 100644 src/__tests__/drift/agui-nonevent-schema.drift.ts diff --git a/src/__tests__/drift/agui-nonevent-schema.drift.ts b/src/__tests__/drift/agui-nonevent-schema.drift.ts new file mode 100644 index 00000000..4f269cac --- /dev/null +++ b/src/__tests__/drift/agui-nonevent-schema.drift.ts @@ -0,0 +1,152 @@ +/** + * AG-UI non-event schema drift test. + * + * The sibling `agui-schema.drift.ts` only walks `*EventSchema` against + * `AGUI*Event` interfaces, so drift in the non-event types — messages, + * interrupts, tool calls — is invisible to it. This file closes that gap for + * subagent attribution specifically: canonical `subagentRunId` is what lets a + * client group replayed content under the subagent that produced it, and a + * fixture whose message or interrupt silently drops the field replays as + * root-attributed work. + * + * Scoped to `subagentRunId` on purpose. A general field-by-field comparison of + * the non-event types is a larger surface (aimock deliberately flattens the + * seven canonical message schemas into one `AGUIMessage`) and is tracked + * separately. + */ + +import { describe, it, expect } from "vitest"; +import fs from "node:fs"; +import path from "node:path"; +import type { AGUIInterrupt, AGUIMessage } from "../../agui-types.js"; + +const CANONICAL_TYPES_PATH = path.resolve( + import.meta.dirname, + "../../../../ag-ui/sdks/typescript/packages/core/src/types.ts", +); +const AIMOCK_TYPES_PATH = path.resolve(import.meta.dirname, "../../agui-types.ts"); + +/** + * Read the brace-balanced body that follows the first match of `header`. + * + * Balancing rather than a non-greedy `\{([\s\S]*?)\}`: both sides nest braces + * — canonical wraps schemas in `z.object({...})` chains, and aimock's + * `AGUIToolCall` declares an inline `function: { ... }` object type — so a + * lazy match stops at the first inner close brace. + */ +function readBlock(source: string, header: RegExp): string | null { + const match = source.match(header); + if (!match || match.index === undefined) return null; + const open = source.indexOf("{", match.index + match[0].length - 1); + if (open === -1) return null; + let depth = 0; + for (let i = open; i < source.length; i++) { + if (source[i] === "{") depth++; + else if (source[i] === "}" && --depth === 0) return source.slice(open + 1, i); + } + return null; +} + +function canonicalSchemaBody(source: string, schemaName: string): string | null { + return readBlock( + source, + new RegExp(`export const ${schemaName}\\s*=\\s*z\\s*\\.\\s*object\\(\\{`), + ); +} + +function aimockInterfaceBody(source: string, interfaceName: string): string | null { + return readBlock(source, new RegExp(`export interface ${interfaceName}\\s*\\{`)); +} + +/** + * Canonical schema -> the aimock interface that mirrors it. + * + * Aimock flattens the canonical message union into a single `AGUIMessage` + * discriminated by `role`, so all four canonical message schemas that carry + * `subagentRunId` map onto that one interface. + */ +const MIRRORS: Array<{ canonical: string; aimock: string }> = [ + { canonical: "BaseMessageSchema", aimock: "AGUIMessage" }, + { canonical: "ToolMessageSchema", aimock: "AGUIMessage" }, + { canonical: "ActivityMessageSchema", aimock: "AGUIMessage" }, + { canonical: "ReasoningMessageSchema", aimock: "AGUIMessage" }, + { canonical: "InterruptSchema", aimock: "AGUIInterrupt" }, +]; + +const canonicalExists = fs.existsSync(CANONICAL_TYPES_PATH); +const aimockExists = fs.existsSync(AIMOCK_TYPES_PATH); + +describe.skipIf(!canonicalExists || !aimockExists)("AG-UI non-event schema drift", () => { + const canonicalSource = canonicalExists ? fs.readFileSync(CANONICAL_TYPES_PATH, "utf-8") : ""; + const aimockSource = aimockExists ? fs.readFileSync(AIMOCK_TYPES_PATH, "utf-8") : ""; + + it("has both sources available", () => { + expect(canonicalExists).toBe(true); + expect(aimockExists).toBe(true); + }); + + it("parses the canonical non-event schemas it compares", () => { + // Positive control: a mirror silently going unparsed would make the drift + // assertion below vacuously green. + for (const { canonical } of MIRRORS) { + expect(canonicalSchemaBody(canonicalSource, canonical), `${canonical} body`).toBeTruthy(); + } + for (const { aimock } of new Map(MIRRORS.map((m) => [m.aimock, m])).values()) { + expect(aimockInterfaceBody(aimockSource, aimock), `${aimock} body`).toBeTruthy(); + } + // The canonical field must actually be declared where we expect to read it, + // so an upstream rename fails loudly here instead of reading as "no drift". + expect(canonicalSchemaBody(canonicalSource, "InterruptSchema")).toContain("subagentRunId"); + }); + + it("mirrors canonical subagentRunId onto the non-event interfaces", () => { + const drifts: string[] = []; + + for (const { canonical, aimock } of MIRRORS) { + const canonicalBody = canonicalSchemaBody(canonicalSource, canonical); + const aimockBody = aimockInterfaceBody(aimockSource, aimock); + if (canonicalBody === null || aimockBody === null) continue; // reported above + if (!/^\s*subagentRunId\s*:/m.test(canonicalBody)) continue; + + if (!/^\s*subagentRunId\?\s*:\s*string;/m.test(aimockBody)) { + drifts.push( + `${canonical} declares optional "subagentRunId" but aimock's ${aimock} does not mirror it`, + ); + } + } + + expect(drifts, `Non-event subagent attribution drift:\n ${drifts.join("\n ")}`).toEqual([]); + }); +}); + +// --------------------------------------------------------------------------- +// Type-level guard. The structural check above reads source text; this one +// fails the typecheck instead, so removing the field breaks consumers loudly +// even if the ag-ui checkout is absent and the suite above skips. +// +// NOTE: tsconfig.json excludes src/__tests__, so `pnpm build` does NOT cover +// this. Typecheck it explicitly: +// npx tsc --noEmit --strict --module NodeNext --moduleResolution NodeNext \ +// --target ES2022 src/__tests__/drift/agui-nonevent-schema.drift.ts +// --------------------------------------------------------------------------- + +describe("non-event subagent attribution is expressible in the type system", () => { + it("accepts subagentRunId on a message and on an interrupt", () => { + // Object literals, so excess-property checking rejects these at compile + // time if the field is not declared. + const message: AGUIMessage = { + id: "msg_1", + role: "assistant", + content: "hi", + subagentRunId: "sub_1", + }; + const interrupt: AGUIInterrupt = { + id: "int_1", + reason: "approval", + subagentRunId: "sub_1", + }; + + expect(message.subagentRunId).toBe("sub_1"); + expect(interrupt.subagentRunId).toBe("sub_1"); + }); +}); 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 { From 5a33cbc9157a647026a993d9f847f55c6304c05d Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 14:20:29 -0700 Subject: [PATCH 03/10] test: parse barrel re-exports with the TypeScript parser, not regexes The barrel guard split export blocks on commas before stripping comments, so a comma inside a comment dropped a real exported name and injected a bogus one; and it recorded `X as Y` under `X`, so renaming a re-export defeated the reachability check the guard exists to perform. Read src/index.ts, src/agui-stub.ts and src/agui-types.ts with the TypeScript parser instead. Comments are trivia and a rename is a distinct propertyName/name pair, so both failure modes are handled by construction. A name is counted as reachable only when its local and exported names match. Star re-exports are recognised as publishing everything. The reader itself is now unit-tested on the shapes that defeat a regex, and the non-empty positive control against a total parse failure is retained. --- src/__tests__/agui-barrel-exports.test.ts | 111 ++++++++++++++++++---- 1 file changed, 95 insertions(+), 16 deletions(-) diff --git a/src/__tests__/agui-barrel-exports.test.ts b/src/__tests__/agui-barrel-exports.test.ts index d9e9938e..9b54100d 100644 --- a/src/__tests__/agui-barrel-exports.test.ts +++ b/src/__tests__/agui-barrel-exports.test.ts @@ -1,6 +1,7 @@ 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 @@ -8,32 +9,68 @@ import { fileURLToPath } from "node:url"; // 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"); -/** Names of the `export type` / `export interface` declarations in a source file. */ -function declaredTypeNames(source: string): string[] { - return [...source.matchAll(/^export (?:type|interface) ([A-Za-z0-9_]+)/gm)].map((m) => m[1]); +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 re-exported from "./agui-types.js" by a barrel file. */ -function reExportedFromTypes(source: string): Set { +/** + * 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 block of source.matchAll(/export type \{([^}]*)\} from "\.\/agui-types\.js";/g)) { - for (const raw of block[1].split(",")) { - const name = raw - .replace(/\/\/[^\n]*/g, "") - .trim() - .split(/\s+as\s+/)[0] - .trim(); - if (name) names.add(name); + 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(read("../agui-types.ts")); +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", () => { @@ -50,10 +87,52 @@ describe("AG-UI type barrel exports", () => { 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(read(rel)); + ])("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"]); + }); +}); From 47ea0f0d83b80da35c21adb05d9a497678abce74 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 14:20:56 -0700 Subject: [PATCH 04/10] docs(changelog): record the AG-UI subagent event and subagentRunId mirroring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The branch adds four public type exports and mirrors canonical's optional subagentRunId onto 24 events, AGUIMessage and AGUIInterrupt, with no [Unreleased] entry — against the repo's own convention. Adds one Added bullet matching the depth of the 1.39.0 AGUITokenUsage entry (the same kind of change), and one Fixed bullet for the drift parser's trailing- comment bug that made the report undercount. States plainly that the new types are declarative only: agui-handler.ts gained no builder, so aimock can type a subagent event but not emit one. --- CHANGELOG.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e915dd4..89490caa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,10 +2,18 @@ ## [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` (canonical `BaseMessageSchema`) and `AGUIInterrupt` (canonical `InterruptSchema`), 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, and by a new non-event drift suite covering the canonical schemas the existing `*EventSchema` walk could never see. **Scope: this is a type surface only.** Unlike 1.39.0's `AGUITokenUsage`, which was reachable through `AGUIBuildOpts`, nothing outside `agui-types.ts` references these types — `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 - `aimock-pytest` 0.5.3 now defaults to `@copilotkit/aimock` 1.39.0. +### Fixed + +- **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 From 7ddef26ef8583eefc94966b30c4ad85e402a00e8 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 14:34:58 -0700 Subject: [PATCH 05/10] ci: run the whole AG-UI drift surface, not one hardcoded file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `agui-schema-drift` job and `runAgUiDriftTests()` in the drift report collector both ran a single hardcoded path, `src/__tests__/drift/agui-schema.drift.ts`. The default vitest config only includes `*.test.ts`, so `pnpm test` never picks up `*.drift.ts` either — meaning `agui-nonevent-schema.drift.ts` was executed by no CI job at all: a guard that could never fail server-side. Both consumers now pass the vitest filename filter `src/__tests__/drift/agui-` instead, so every current and future `agui-*.drift.ts` guard runs. `vitest.config.drift.ts` already scopes `include` to the drift-suffixed files, so the filter cannot pull in plain `.test.ts` helpers from the same directory. The lane still needs no provider API keys — the AG-UI drift files compare `src/agui-types.ts` against the cloned canonical ag-ui repo only. The `paths:` trigger entry is generalised to `agui-*.drift.ts` to match. --- .github/workflows/test-drift.yml | 20 +++++++++++++++++--- scripts/drift-report-collector.ts | 23 ++++++++++++++++++++++- 2 files changed, 39 insertions(+), 4 deletions(-) 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/scripts/drift-report-collector.ts b/scripts/drift-report-collector.ts index 1d6ae80f..8b5c8215 100644 --- a/scripts/drift-report-collector.ts +++ b/scripts/drift-report-collector.ts @@ -102,6 +102,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"; // --------------------------------------------------------------------------- @@ -1511,7 +1532,7 @@ function runAgUiDriftTests(): VitestJsonResult | null { try { const stdout = execSync( - `npx vitest run ${AGUI_DRIFT_TEST} --config vitest.config.drift.ts --reporter=json`, + `npx vitest run ${AGUI_DRIFT_TEST_FILTER} --config vitest.config.drift.ts --reporter=json`, { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"], From 6dd17f30b9f5e8624f750c3d823047998d1c2ee0 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 14:36:59 -0700 Subject: [PATCH 06/10] fix(drift): make the non-event drift guard fail loudly instead of skipping The availability check lived inside the `describe.skipIf` it was meant to guard, so a missing ag-ui checkout skipped the assertion that would have reported it and the file exited 0 while comparing nothing. The gate now lives outside the skipped block: an absent or unreadable canonical checkout fails, and the local escape hatch (AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1) is inert whenever CI is set, so no automated lane can reach a silent pass. The mirror loop also `continue`d past any canonical schema that did not declare `subagentRunId`, so an upstream rename -- the drift this file exists to catch -- reported clean for the four message mirrors. The canonical side is now asserted and a missing declaration is reported as drift. Drop the type-level companion block: it asserted nothing at runtime and the `tsc` command its comment documented was wired into no script and no CI lane. Run the file in test-drift.yml's AG-UI job, which previously named only the older agui-schema.drift.ts and so never executed this one. --- .github/workflows/test-drift.yml | 2 +- .../drift/agui-nonevent-schema.drift.ts | 185 +++++++++++------- 2 files changed, 117 insertions(+), 70 deletions(-) diff --git a/.github/workflows/test-drift.yml b/.github/workflows/test-drift.yml index fff11bec..c83be393 100644 --- a/.github/workflows/test-drift.yml +++ b/.github/workflows/test-drift.yml @@ -48,7 +48,7 @@ jobs: 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 + run: npx vitest run src/__tests__/drift/agui-schema.drift.ts src/__tests__/drift/agui-nonevent-schema.drift.ts --config vitest.config.drift.ts drift: if: github.event_name != 'pull_request' diff --git a/src/__tests__/drift/agui-nonevent-schema.drift.ts b/src/__tests__/drift/agui-nonevent-schema.drift.ts index 4f269cac..7082d1e4 100644 --- a/src/__tests__/drift/agui-nonevent-schema.drift.ts +++ b/src/__tests__/drift/agui-nonevent-schema.drift.ts @@ -18,7 +18,6 @@ import { describe, it, expect } from "vitest"; import fs from "node:fs"; import path from "node:path"; -import type { AGUIInterrupt, AGUIMessage } from "../../agui-types.js"; const CANONICAL_TYPES_PATH = path.resolve( import.meta.dirname, @@ -73,80 +72,128 @@ const MIRRORS: Array<{ canonical: string; aimock: string }> = [ { canonical: "InterruptSchema", aimock: "AGUIInterrupt" }, ]; -const canonicalExists = fs.existsSync(CANONICAL_TYPES_PATH); -const aimockExists = fs.existsSync(AIMOCK_TYPES_PATH); +/** + * Read a source file, returning the error rather than throwing, so the + * availability gate below can report *which* side is missing. + */ +function readSource(file: string): { source: string; error: string | null } { + try { + const source = fs.readFileSync(file, "utf-8"); + if (source.trim() === "") return { source: "", error: `${file} is empty` }; + return { source, error: null }; + } catch (err: unknown) { + return { source: "", error: err instanceof Error ? err.message : String(err) }; + } +} -describe.skipIf(!canonicalExists || !aimockExists)("AG-UI non-event schema drift", () => { - const canonicalSource = canonicalExists ? fs.readFileSync(CANONICAL_TYPES_PATH, "utf-8") : ""; - const aimockSource = aimockExists ? fs.readFileSync(AIMOCK_TYPES_PATH, "utf-8") : ""; +const canonical = readSource(CANONICAL_TYPES_PATH); +const aimock = readSource(AIMOCK_TYPES_PATH); - it("has both sources available", () => { - expect(canonicalExists).toBe(true); - expect(aimockExists).toBe(true); - }); +/** + * Escape hatch for a developer running `pnpm test:drift` with no sibling ag-ui + * checkout. Deliberately inert under CI: `CI` is set by every GitHub Actions + * runner, so the opt-out cannot be inherited by an automated lane, and a CI run + * without the canonical checkout fails instead of reporting a clean drift check. + */ +const localOptOut = + process.env.AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT === "1" && process.env.CI !== "true"; - it("parses the canonical non-event schemas it compares", () => { - // Positive control: a mirror silently going unparsed would make the drift - // assertion below vacuously green. - for (const { canonical } of MIRRORS) { - expect(canonicalSchemaBody(canonicalSource, canonical), `${canonical} body`).toBeTruthy(); - } - for (const { aimock } of new Map(MIRRORS.map((m) => [m.aimock, m])).values()) { - expect(aimockInterfaceBody(aimockSource, aimock), `${aimock} body`).toBeTruthy(); +/** + * Availability gate. This block is deliberately NOT skipped by the same + * condition it checks: putting the "are the sources there?" assertion inside a + * `describe.skipIf(!sourcesThere)` — as this file originally did — makes a + * missing canonical checkout skip the assertion that was supposed to catch it, + * so the whole file exits 0 while comparing nothing. + */ +describe("AG-UI non-event schema sources", () => { + it("has both schema sources available", () => { + // aimock's own types ship in this repo; unreadable is always a hard failure. + expect(aimock.error, `aimock types unreadable at ${AIMOCK_TYPES_PATH}: ${aimock.error}`).toBe( + null, + ); + + if (canonical.error !== null && localOptOut) { + console.warn( + `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1: skipping AG-UI non-event drift comparison (${canonical.error}).`, + ); + // Pin the opt-out's own precondition so it can never apply inside CI. + expect(process.env.CI, "the missing-checkout opt-out must never apply in CI").not.toBe( + "true", + ); + return; } - // The canonical field must actually be declared where we expect to read it, - // so an upstream rename fails loudly here instead of reading as "no drift". - expect(canonicalSchemaBody(canonicalSource, "InterruptSchema")).toContain("subagentRunId"); - }); - it("mirrors canonical subagentRunId onto the non-event interfaces", () => { - const drifts: string[] = []; - - for (const { canonical, aimock } of MIRRORS) { - const canonicalBody = canonicalSchemaBody(canonicalSource, canonical); - const aimockBody = aimockInterfaceBody(aimockSource, aimock); - if (canonicalBody === null || aimockBody === null) continue; // reported above - if (!/^\s*subagentRunId\s*:/m.test(canonicalBody)) continue; + expect( + canonical.error, + `canonical ag-ui types unreadable at ${CANONICAL_TYPES_PATH}: ${canonical.error}. ` + + `Clone the canonical repo next to this one (git clone --depth 1 ` + + `https://github.com/ag-ui-protocol/ag-ui.git ../ag-ui), or set ` + + `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1 to skip the comparison locally.`, + ).toBe(null); + }); +}); - if (!/^\s*subagentRunId\?\s*:\s*string;/m.test(aimockBody)) { - drifts.push( - `${canonical} declares optional "subagentRunId" but aimock's ${aimock} does not mirror it`, - ); +const canonicalSource = canonical.source; +const aimockSource = aimock.source; + +/** Matches the canonical `subagentRunId` field declaration in a zod object body. */ +const CANONICAL_SUBAGENT_RUN_ID = /^\s*subagentRunId\s*:/m; +/** Matches aimock's mirrored optional field declaration. */ +const AIMOCK_SUBAGENT_RUN_ID = /^\s*subagentRunId\?\s*:\s*string;/m; + +// Skipped ONLY under the explicit local opt-out asserted above; a missing +// checkout without that opt-out has already failed the gate. +describe.skipIf(canonical.error !== null || aimock.error !== null)( + "AG-UI non-event schema drift", + () => { + it("parses the canonical non-event schemas it compares", () => { + // Positive control: a mirror silently going unparsed would make the drift + // assertion below vacuously green. + for (const { canonical: schemaName } of MIRRORS) { + expect(canonicalSchemaBody(canonicalSource, schemaName), `${schemaName} body`).toBeTruthy(); + } + for (const { aimock: interfaceName } of new Map(MIRRORS.map((m) => [m.aimock, m])).values()) { + expect( + aimockInterfaceBody(aimockSource, interfaceName), + `${interfaceName} body`, + ).toBeTruthy(); + } + }); + + it("mirrors canonical subagentRunId onto the non-event interfaces", () => { + const drifts: string[] = []; + + for (const { canonical: schemaName, aimock: interfaceName } of MIRRORS) { + const canonicalBody = canonicalSchemaBody(canonicalSource, schemaName); + const aimockBody = aimockInterfaceBody(aimockSource, interfaceName); + if (canonicalBody === null || aimockBody === null) continue; // reported above + + // The canonical side is ASSERTED, not used as a silent precondition. An + // upstream rename or removal of `subagentRunId` is exactly the drift this + // file exists to catch, so `continue`-ing past it here would report the + // rename as "no drift". + if (!CANONICAL_SUBAGENT_RUN_ID.test(canonicalBody)) { + drifts.push( + `canonical ${schemaName} no longer declares "subagentRunId" — upstream renamed or ` + + `removed it; update MIRRORS and aimock's ${interfaceName} to match`, + ); + continue; + } + + if (!AIMOCK_SUBAGENT_RUN_ID.test(aimockBody)) { + drifts.push( + `${schemaName} declares optional "subagentRunId" but aimock's ${interfaceName} does not mirror it`, + ); + } } - } - expect(drifts, `Non-event subagent attribution drift:\n ${drifts.join("\n ")}`).toEqual([]); - }); -}); + expect(drifts, `Non-event subagent attribution drift:\n ${drifts.join("\n ")}`).toEqual([]); + }); + }, +); -// --------------------------------------------------------------------------- -// Type-level guard. The structural check above reads source text; this one -// fails the typecheck instead, so removing the field breaks consumers loudly -// even if the ag-ui checkout is absent and the suite above skips. -// -// NOTE: tsconfig.json excludes src/__tests__, so `pnpm build` does NOT cover -// this. Typecheck it explicitly: -// npx tsc --noEmit --strict --module NodeNext --moduleResolution NodeNext \ -// --target ES2022 src/__tests__/drift/agui-nonevent-schema.drift.ts -// --------------------------------------------------------------------------- - -describe("non-event subagent attribution is expressible in the type system", () => { - it("accepts subagentRunId on a message and on an interrupt", () => { - // Object literals, so excess-property checking rejects these at compile - // time if the field is not declared. - const message: AGUIMessage = { - id: "msg_1", - role: "assistant", - content: "hi", - subagentRunId: "sub_1", - }; - const interrupt: AGUIInterrupt = { - id: "int_1", - reason: "approval", - subagentRunId: "sub_1", - }; - - expect(message.subagentRunId).toBe("sub_1"); - expect(interrupt.subagentRunId).toBe("sub_1"); - }); -}); +// A type-level companion guard used to live here. It asserted nothing at +// runtime and the `tsc` invocation its comment documented was wired into no +// script and no CI lane, so it read as a second guard while being theatre. The +// structural check above is the guard; it now runs in CI (test-drift.yml) and +// fails loudly rather than skipping when the canonical checkout is absent. From b1d9cbf875b17fbd77e606d43c622090e2f71868 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 15:16:53 -0700 Subject: [PATCH 07/10] docs(changelog): correct subagent entry scope, subagentRunId citation, and record drift lane change --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89490caa..7469ac77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,12 @@ ### 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` (canonical `BaseMessageSchema`) and `AGUIInterrupt` (canonical `InterruptSchema`), 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, and by a new non-event drift suite covering the canonical schemas the existing `*EventSchema` walk could never see. **Scope: this is a type surface only.** Unlike 1.39.0's `AGUITokenUsage`, which was reachable through `AGUIBuildOpts`, nothing outside `agui-types.ts` references these types — `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) +- **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, and by a new non-event drift suite covering the canonical schemas the existing `*EventSchema` walk could never see. **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 — including the non-event suite above, which would otherwise have shipped never running in CI — as does any future guard, 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. +- **A missing canonical checkout now fails the non-event drift guard instead of skipping it green.** Its source-availability assertion no longer sits inside a `describe.skipIf` on the very condition it checks, so a CI run with no `../ag-ui` clone fails loudly rather than exiting 0 having compared nothing. The local `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1` escape hatch, for a developer running the drift suite with no sibling checkout, is inert whenever `CI=true` and pins that precondition as its own assertion (#391) - `aimock-pytest` 0.5.3 now defaults to `@copilotkit/aimock` 1.39.0. ### Fixed From efba4dee01790c5711d6948394984ca355cf6292 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 15:20:52 -0700 Subject: [PATCH 08/10] test(drift): read AG-UI non-event schemas with the TypeScript parser The non-event subagentRunId guard hand-parsed TypeScript with regexes and a brace counter, and every way that reader failed was a fail-open failure: - the brace counter ignored comments and strings, so a brace inside a comment ran the reader past the end of the schema it was reading; - the canonical-side check matched subagentRunId against the whole nested body, so a nested occurrence masked a top-level removal; - MIRRORS was a hardcoded list with no completeness check, so a new canonical schema carrying the field went silently uncompared. It also pinned the aimock side to the literal text subagentRunId?: string;, reporting false drift on a reformat, a readonly, or a widened type; and gated its local escape hatch on CI === "true", so a runner setting CI=1 reached an opt-out meant to be unreachable in CI. Both sides are now read with ts.createSourceFile (syntax-only, no program), following the pattern already established in agui-barrel-exports.test.ts. Members are read structurally, so comments and strings are trivia and a nested member is distinguishable from a top-level one by construction; the aimock mirror is compared by name, optionality and type under a stated widening rule (must admit absence/undefined and a bare string; extra union members are an acceptable widening, narrowing is drift). The canonical side of MIRRORS is derived and asserted equal to the hand-written list, so a new or renamed canonical schema fails loudly. The CI gate now treats any non-negating value as truthy, and the readers have direct unit tests. --- .../drift/agui-nonevent-schema.drift.ts | 393 +++++++++++++++--- 1 file changed, 339 insertions(+), 54 deletions(-) diff --git a/src/__tests__/drift/agui-nonevent-schema.drift.ts b/src/__tests__/drift/agui-nonevent-schema.drift.ts index 7082d1e4..1279d7c6 100644 --- a/src/__tests__/drift/agui-nonevent-schema.drift.ts +++ b/src/__tests__/drift/agui-nonevent-schema.drift.ts @@ -13,11 +13,25 @@ * the non-event types is a larger surface (aimock deliberately flattens the * seven canonical message schemas into one `AGUIMessage`) and is tracked * separately. + * + * Both sides are read with the TypeScript parser (`ts.createSourceFile`, + * syntax-only — no program, no type checker), never with regexes over the + * source text. Every way a regex reader of this shape fails is a fail-OPEN + * failure, which is the worst kind for a drift guard: a brace inside a comment + * runs a hand-rolled brace counter past the end of the schema it was reading, + * a `subagentRunId` nested one level down inside a property value masks its + * removal from the top level, and a literal-text pin on `subagentRunId?: + * string;` reports false drift on a reformat, a `readonly`, or a widened type. + * The parser sees comments and strings as trivia, distinguishes a top-level + * member from a nested one by construction, and exposes optionality and type + * as structure rather than as text, so none of those failures are expressible + * here. */ import { describe, it, expect } from "vitest"; import fs from "node:fs"; import path from "node:path"; +import ts from "typescript"; const CANONICAL_TYPES_PATH = path.resolve( import.meta.dirname, @@ -25,36 +39,144 @@ const CANONICAL_TYPES_PATH = path.resolve( ); const AIMOCK_TYPES_PATH = path.resolve(import.meta.dirname, "../../agui-types.ts"); +/** The one canonical field this guard tracks across the non-event types. */ +const FIELD = "subagentRunId"; + +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); + +const propertyName = (name: ts.PropertyName | undefined): string | null => + name && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? name.text : null; + /** - * Read the brace-balanced body that follows the first match of `header`. + * The member names a zod schema initializer declares *itself*, at the top + * level of its own object literal(s). + * + * The walk descends through the builder chain — `z.object({...})`, + * `Base.extend({...})`, `z.object({...}).strict()` — but stops at every object + * literal it reaches, collecting that literal's property names without + * descending into their values. That boundary is what makes a nested + * `subagentRunId` (say, inside a `z.object({ meta: z.object({ subagentRunId: + * ... }) })`) invisible here, which is the point: a nested occurrence must not + * mask the removal of the top-level one. * - * Balancing rather than a non-greedy `\{([\s\S]*?)\}`: both sides nest braces - * — canonical wraps schemas in `z.object({...})` chains, and aimock's - * `AGUIToolCall` declares an inline `function: { ... }` object type — so a - * lazy match stops at the first inner close brace. + * "Itself" also excludes inherited members: `UserMessageSchema = + * BaseMessageSchema.extend({ role: ... })` declares only `role`. Inheritance + * is deliberately not resolved — the mirror list below covers the schemas that + * *declare* the field, and resolving `.extend()` chains would drag in every + * message subtype for a field they do not restate. */ -function readBlock(source: string, header: RegExp): string | null { - const match = source.match(header); - if (!match || match.index === undefined) return null; - const open = source.indexOf("{", match.index + match[0].length - 1); - if (open === -1) return null; - let depth = 0; - for (let i = open; i < source.length; i++) { - if (source[i] === "{") depth++; - else if (source[i] === "}" && --depth === 0) return source.slice(open + 1, i); +function ownMemberNames(initializer: ts.Expression): string[] { + const names: string[] = []; + const visit = (node: ts.Node): void => { + if (ts.isObjectLiteralExpression(node)) { + for (const property of node.properties) { + const name = propertyName(property.name); + if (name !== null) names.push(name); + } + return; + } + ts.forEachChild(node, visit); + }; + visit(initializer); + return names; +} + +/** + * Every exported top-level `const = ` in the canonical + * types module, mapped to the member names it declares itself. + */ +export function canonicalSchemaMembers(fileName: string, source: string): Map { + const schemas = new Map(); + for (const statement of parse(fileName, source).statements) { + if (!ts.isVariableStatement(statement) || !isExported(statement)) continue; + for (const declaration of statement.declarationList.declarations) { + if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue; + schemas.set(declaration.name.text, ownMemberNames(declaration.initializer)); + } } - return null; + return schemas; } -function canonicalSchemaBody(source: string, schemaName: string): string | null { - return readBlock( - source, - new RegExp(`export const ${schemaName}\\s*=\\s*z\\s*\\.\\s*object\\(\\{`), - ); +/** The canonical schemas that declare `field` as a member of their own object literal. */ +export function canonicalSchemasDeclaring( + fileName: string, + source: string, + field: string, +): string[] { + return [...canonicalSchemaMembers(fileName, source)] + .filter(([, members]) => members.includes(field)) + .map(([name]) => name) + .sort(); } -function aimockInterfaceBody(source: string, interfaceName: string): string | null { - return readBlock(source, new RegExp(`export interface ${interfaceName}\\s*\\{`)); +/** + * One top-level property signature of an aimock interface, read structurally. + * + * `optional` is true when the member can be absent *or* explicitly + * `undefined`, so `x?: string` and `x: string | undefined` are the same fact. + * `types` is the set of syntax kinds the (flattened) union admits, which is + * what the widening rule below is expressed over. Nested type literals are not + * searched: only the interface's own members count. + */ +export function aimockInterfaceMember( + fileName: string, + source: string, + interfaceName: string, + field: string, +): { optional: boolean; typeText: string; parts: ts.TypeNode[] } | null | undefined { + for (const statement of parse(fileName, source).statements) { + if (!ts.isInterfaceDeclaration(statement) || statement.name.text !== interfaceName) continue; + for (const member of statement.members) { + if (!ts.isPropertySignature(member) || propertyName(member.name) !== field) continue; + const type = member.type; + const parts = type && ts.isUnionTypeNode(type) ? [...type.types] : type ? [type] : []; + return { + optional: member.questionToken !== undefined || parts.some(isUndefinedType), + typeText: type ? type.getText() : "(no type)", + parts, + }; + } + // Interface found, member absent. + return null; + } + // Interface itself absent — a distinct fact from "declared without the field". + return undefined; +} + +const isUndefinedType = (node: ts.TypeNode) => + node.kind === ts.SyntaxKind.UndefinedKeyword || + (ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.UndefinedKeyword); + +/** + * The widening rule, stated once. + * + * Canonical `subagentRunId: z.string().optional()` parses to `string | + * undefined`. An aimock mirror is CORRECT when it (a) exists, (b) can be + * absent or `undefined`, and (c) admits a bare `string`. Anything that adds + * further members to the union — `string | null`, `string | SomeBrand` — is an + * ACCEPTABLE WIDENING: every canonical value still fits, so no fixture that + * round-trips through the canonical schema can fail to type-check here. + * NARROWING is drift: dropping optionality (a canonical value may be absent), + * or replacing `string` with something stricter such as a literal union or a + * branded alias (a canonical value may then not fit). + * + * Formatting, `readonly`, trailing punctuation, and member ordering are not + * facts about the type and are invisible to this rule by construction. + */ +function mirrorProblem(member: { optional: boolean; typeText: string; parts: ts.TypeNode[] }) { + if (!member.optional) { + return `is required (\`${member.typeText}\`) but canonical declares it optional`; + } + const admitsString = member.parts.some((part) => part.kind === ts.SyntaxKind.StringKeyword); + if (!admitsString) { + return `has type \`${member.typeText}\`, which does not admit a bare \`string\``; + } + return null; } /** @@ -63,6 +185,11 @@ function aimockInterfaceBody(source: string, interfaceName: string): string | nu * Aimock flattens the canonical message union into a single `AGUIMessage` * discriminated by `role`, so all four canonical message schemas that carry * `subagentRunId` map onto that one interface. + * + * This list is not trusted to be complete: the completeness test below asserts + * it covers exactly the canonical schemas that declare the field, so a NEW + * canonical schema carrying `subagentRunId` fails loudly here instead of going + * silently uncompared. */ const MIRRORS: Array<{ canonical: string; aimock: string }> = [ { canonical: "BaseMessageSchema", aimock: "AGUIMessage" }, @@ -86,6 +213,20 @@ function readSource(file: string): { source: string; error: string | null } { } } +/** + * Truthiness for a CI-style environment flag. + * + * GitHub Actions sets `CI=true`, but other runners set `CI=1`, `CI=True`, or + * `CI=yes`, and an exact `=== "true"` comparison hands all of those the local + * escape hatch that is supposed to be unreachable in CI. Anything set and not + * an explicit negation counts as CI. + */ +export function isTruthyEnvFlag(value: string | undefined): boolean { + if (value === undefined) return false; + const normalized = value.trim().toLowerCase(); + return normalized !== "" && !["0", "false", "no", "off"].includes(normalized); +} + const canonical = readSource(CANONICAL_TYPES_PATH); const aimock = readSource(AIMOCK_TYPES_PATH); @@ -96,7 +237,7 @@ const aimock = readSource(AIMOCK_TYPES_PATH); * without the canonical checkout fails instead of reporting a clean drift check. */ const localOptOut = - process.env.AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT === "1" && process.env.CI !== "true"; + process.env.AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT === "1" && !isTruthyEnvFlag(process.env.CI); /** * Availability gate. This block is deliberately NOT skipped by the same @@ -117,9 +258,10 @@ describe("AG-UI non-event schema sources", () => { `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1: skipping AG-UI non-event drift comparison (${canonical.error}).`, ); // Pin the opt-out's own precondition so it can never apply inside CI. - expect(process.env.CI, "the missing-checkout opt-out must never apply in CI").not.toBe( - "true", - ); + expect( + isTruthyEnvFlag(process.env.CI), + "the missing-checkout opt-out must never apply in CI", + ).toBe(false); return; } @@ -136,53 +278,82 @@ describe("AG-UI non-event schema sources", () => { const canonicalSource = canonical.source; const aimockSource = aimock.source; -/** Matches the canonical `subagentRunId` field declaration in a zod object body. */ -const CANONICAL_SUBAGENT_RUN_ID = /^\s*subagentRunId\s*:/m; -/** Matches aimock's mirrored optional field declaration. */ -const AIMOCK_SUBAGENT_RUN_ID = /^\s*subagentRunId\?\s*:\s*string;/m; - -// Skipped ONLY under the explicit local opt-out asserted above; a missing -// checkout without that opt-out has already failed the gate. +// Skipped whenever either source failed to read — which is the local opt-out +// case, and otherwise a case the availability gate above has ALREADY failed on, +// so the file still exits non-zero. The skip only suppresses a cascade of +// secondary failures that would all be restating the same missing checkout. describe.skipIf(canonical.error !== null || aimock.error !== null)( "AG-UI non-event schema drift", () => { + const schemas = canonicalSchemaMembers(CANONICAL_TYPES_PATH, canonicalSource); + it("parses the canonical non-event schemas it compares", () => { // Positive control: a mirror silently going unparsed would make the drift // assertion below vacuously green. - for (const { canonical: schemaName } of MIRRORS) { - expect(canonicalSchemaBody(canonicalSource, schemaName), `${schemaName} body`).toBeTruthy(); - } - for (const { aimock: interfaceName } of new Map(MIRRORS.map((m) => [m.aimock, m])).values()) { - expect( - aimockInterfaceBody(aimockSource, interfaceName), - `${interfaceName} body`, - ).toBeTruthy(); - } + const unparsed = MIRRORS.map((m) => m.canonical).filter((name) => !schemas.has(name)); + expect(unparsed, `canonical schemas the parser did not find: ${unparsed.join(", ")}`).toEqual( + [], + ); + + const interfaces = [...new Set(MIRRORS.map((m) => m.aimock))]; + const missing = interfaces.filter( + (name) => aimockInterfaceMember(AIMOCK_TYPES_PATH, aimockSource, name, FIELD) === undefined, + ); + expect(missing, `aimock interfaces the parser did not find: ${missing.join(", ")}`).toEqual( + [], + ); + }); + + it("covers every canonical schema that declares subagentRunId", () => { + // Completeness. MIRRORS is a hand-written map because the aimock side of + // it cannot be derived (aimock flattens seven message schemas into one + // interface), so the canonical side is derived instead and the two are + // required to agree exactly. A new canonical schema carrying the field + // fails here rather than being silently left uncompared, and a schema + // that stops declaring it fails here rather than being compared against + // nothing. + const declared = canonicalSchemasDeclaring(CANONICAL_TYPES_PATH, canonicalSource, FIELD); + const covered = [...new Set(MIRRORS.map((m) => m.canonical))].sort(); + expect( + declared, + `MIRRORS must cover exactly the canonical schemas declaring "${FIELD}". ` + + `Canonical declares it on: ${declared.join(", ") || "(none)"}; ` + + `MIRRORS covers: ${covered.join(", ")}. ` + + `Add or remove a MIRRORS entry (and the matching aimock field) to match.`, + ).toEqual(covered); }); it("mirrors canonical subagentRunId onto the non-event interfaces", () => { const drifts: string[] = []; for (const { canonical: schemaName, aimock: interfaceName } of MIRRORS) { - const canonicalBody = canonicalSchemaBody(canonicalSource, schemaName); - const aimockBody = aimockInterfaceBody(aimockSource, interfaceName); - if (canonicalBody === null || aimockBody === null) continue; // reported above + const members = schemas.get(schemaName); + if (members === undefined) continue; // reported by the parse test above // The canonical side is ASSERTED, not used as a silent precondition. An // upstream rename or removal of `subagentRunId` is exactly the drift this // file exists to catch, so `continue`-ing past it here would report the // rename as "no drift". - if (!CANONICAL_SUBAGENT_RUN_ID.test(canonicalBody)) { + if (!members.includes(FIELD)) { drifts.push( - `canonical ${schemaName} no longer declares "subagentRunId" — upstream renamed or ` + + `canonical ${schemaName} no longer declares "${FIELD}" — upstream renamed or ` + `removed it; update MIRRORS and aimock's ${interfaceName} to match`, ); continue; } - if (!AIMOCK_SUBAGENT_RUN_ID.test(aimockBody)) { + const member = aimockInterfaceMember(AIMOCK_TYPES_PATH, aimockSource, interfaceName, FIELD); + if (member === undefined) continue; // reported by the parse test above + if (member === null) { drifts.push( - `${schemaName} declares optional "subagentRunId" but aimock's ${interfaceName} does not mirror it`, + `${schemaName} declares optional "${FIELD}" but aimock's ${interfaceName} does not mirror it`, + ); + continue; + } + const problem = mirrorProblem(member); + if (problem !== null) { + drifts.push( + `${schemaName} declares optional "${FIELD}" but aimock's ${interfaceName}.${FIELD} ${problem}`, ); } } @@ -192,8 +363,122 @@ describe.skipIf(canonical.error !== null || aimock.error !== null)( }, ); -// A type-level companion guard used to live here. It asserted nothing at -// runtime and the `tsc` invocation its comment documented was wired into no -// script and no CI lane, so it read as a second guard while being theatre. The -// structural check above is the guard; it now runs in CI (test-drift.yml) and -// fails loudly rather than skipping when the canonical checkout is absent. +// The guard is only as good as its readers, so the readers are tested directly +// on the shapes that defeat a regex/brace-counting implementation. +describe("non-event schema readers", () => { + const member = (source: string, iface = "I") => + aimockInterfaceMember("types.ts", source, iface, FIELD); + + it("is not confused by a brace inside a comment", () => { + const source = [ + "export const AlphaSchema = z.object({", + " // an opening brace { that a brace counter would follow", + " id: z.string(),", + "});", + "export const BetaSchema = z.object({", + " subagentRunId: z.string().optional(),", + "});", + ].join("\n"); + expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["BetaSchema"]); + }); + + it("is not confused by a brace inside a string literal", () => { + const source = [ + 'export const AlphaSchema = z.object({ id: z.literal("{"), name: z.string() });', + "export const BetaSchema = z.object({ subagentRunId: z.string().optional() });", + ].join("\n"); + expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["BetaSchema"]); + }); + + it("does not let a nested occurrence stand in for a top-level member", () => { + const source = + "export const AlphaSchema = z.object({ meta: z.object({ subagentRunId: z.string() }) });"; + expect(canonicalSchemaMembers("types.ts", source).get("AlphaSchema")).toEqual(["meta"]); + expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual([]); + }); + + it("reads members declared through an extend chain but not inherited ones", () => { + const source = [ + "export const AlphaSchema = z.object({ subagentRunId: z.string().optional() });", + "export const BetaSchema = AlphaSchema.extend({ role: z.literal('beta') });", + "export const GammaSchema = z.object({ id: z.string() }).extend({ subagentRunId: z.string() });", + ].join("\n"); + expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual([ + "AlphaSchema", + "GammaSchema", + ]); + }); + + it("skips unexported and non-schema declarations", () => { + const source = [ + "const HiddenSchema = z.object({ subagentRunId: z.string() });", + "export const VisibleSchema = z.object({ subagentRunId: z.string() });", + ].join("\n"); + expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["VisibleSchema"]); + }); + + it("distinguishes a missing interface from a missing member", () => { + expect(member("export interface Other { subagentRunId?: string }")).toBeUndefined(); + expect(member("export interface I { id: string }")).toBeNull(); + }); + + it("reads optionality from the question token", () => { + expect(member("export interface I { subagentRunId?: string }")).toMatchObject({ + optional: true, + }); + expect(member("export interface I { subagentRunId: string }")).toMatchObject({ + optional: false, + }); + }); + + it("treats an explicit `| undefined` union as optional", () => { + expect(member("export interface I { subagentRunId: string | undefined }")).toMatchObject({ + optional: true, + }); + }); + + it("ignores a nested type literal's members", () => { + expect(member("export interface I { nested: { subagentRunId?: string } }")).toBeNull(); + }); + + it("is unaffected by readonly, formatting, and missing semicolons", () => { + const source = [ + "export interface I {", + " readonly", + " subagentRunId?:", + " string", + "}", + ].join("\n"); + expect(mirrorProblem(member(source)!)).toBeNull(); + }); +}); + +describe("non-event widening rule", () => { + const problemFor = (declaration: string) => { + const parsed = aimockInterfaceMember( + "types.ts", + `export interface I { ${declaration} }`, + "I", + FIELD, + ); + if (parsed === null || parsed === undefined) throw new Error("member not parsed"); + return mirrorProblem(parsed); + }; + + it.each([ + "subagentRunId?: string;", + "subagentRunId?: string | null;", + "subagentRunId: string | undefined;", + "subagentRunId?: string | number;", + ])("accepts the widening %s", (declaration) => { + expect(problemFor(declaration)).toBeNull(); + }); + + it.each([ + ["subagentRunId: string;", "is required"], + ['subagentRunId?: "a" | "b";', "does not admit"], + ["subagentRunId?: number;", "does not admit"], + ])("rejects the narrowing %s", (declaration, fragment) => { + expect(problemFor(declaration)).toContain(fragment); + }); +}); From a0550c5ea053d38e42d43d60e5697d94b1f08dba Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 15:23:45 -0700 Subject: [PATCH 09/10] fix(drift): fail closed when the AG-UI collector cannot interpret a failure MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The AG-UI leg of the drift collector recognized exactly three failure-message shapes and DROPPED everything else — no entry, no counter, no warning. A genuinely failing AG-UI guard whose message matched none of them therefore produced zero entries, exit 0 and conclusion "clean": the collector reported a clean baseline for a run it could not see. Every unrecognized FAILED AG-UI assertion is now returned as a QuarantineEntry, reusing the collector's existing quarantine / exit-5 lane rather than inventing a parallel scheme. Unlike the HTTP leg's entries.length === 0 gated rescue, this is per-assertion and unconditional, so an uninterpretable failure survives a mixed run in which other failures did parse. ensureAgUiRepo also accepted any directory merely NAMED ag-ui. A stale or partial checkout passed that check, the drift suites' describe.skipIf gates then skipped everything, and the run was certified clean. classifyAgUiCheckout now requires the canonical sdks/typescript/packages/core/src/types.ts and reports a stale/incomplete checkout as exactly that — not as a git/network failure — which routes to the AG-UI-skipped lane (exit 1) instead of clean. --- scripts/drift-report-collector.ts | 173 +++++++++++++++++++----- src/__tests__/drift-collector.test.ts | 183 +++++++++++++++++++++++++- 2 files changed, 322 insertions(+), 34 deletions(-) diff --git a/scripts/drift-report-collector.ts b/scripts/drift-report-collector.ts index 8b5c8215..48266f41 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. @@ -1497,34 +1500,99 @@ 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 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 { + 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; } function runAgUiDriftTests(): VitestJsonResult | null { @@ -1564,9 +1632,25 @@ 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 guard (e.g. the non-event `subagentRunId` attribution + * check, whose message matches none of the three shapes) produced zero entries, + * exit 0 and `conclusion: "clean"`. Every unrecognized 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[] = []; @@ -1621,11 +1705,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", @@ -1636,6 +1720,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: `${assertion.ancestorTitles.join(" ")} > ${assertion.title}`.trim(), + rawLocation: extractRawLocation(fullMessage), + message: fullMessage, + }); + } } } @@ -1663,7 +1761,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 }; } // --------------------------------------------------------------------------- @@ -1753,15 +1860,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( @@ -1800,6 +1910,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__/drift-collector.test.ts b/src/__tests__/drift-collector.test.ts index d68f935f..f018f203 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,9 @@ import { extractScenario, parseKnownModelsCanary, collectDriftEntries, + collectAgUiDriftEntries, + classifyAgUiCheckout, + AGUI_CANONICAL_TYPES_RELPATH, computeExitCode, conclusionForExitCode, classifyUnparseableAsInfra, @@ -45,8 +48,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 +3265,168 @@ 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"`. The +// fixtures below are REAL vitest `--reporter=json` failure messages captured by +// mutating `src/agui-types.ts` (deleting `subagentRunId` from `AGUIMessage`, and +// 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 the non-event `subagentRunId` guard — matches NO recognizer. */ +const AGUI_NONEVENT_FAILURE = [ + "AssertionError: Non-event subagent attribution drift:", + ` BaseMessageSchema declares optional "subagentRunId" but aimock's AGUIMessage does not mirror it`, + ` ToolMessageSchema declares optional "subagentRunId" but aimock's AGUIMessage does not mirror it: expected [ …(4) ] to deeply equal []`, + " at /repo/src/__tests__/drift/agui-nonevent-schema.drift.ts:190:89", + " at file:///repo/node_modules/.pnpm/@vitest+runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js:155:11", +].join("\n"); + +/** Real failure of an EXISTING agui-schema.drift.ts assertion — also unrecognized. */ +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 non-event schema drift"], + title: "mirrors canonical subagentRunId onto the non-event interfaces", + failureMessages: [AGUI_NONEVENT_FAILURE], + }), + ]), + ); + + expect(result.entries).toEqual([]); + expect(result.quarantine).toHaveLength(1); + expect(result.quarantine[0].provider).toBe("AG-UI"); + expect(result.quarantine[0].testName).toContain( + "mirrors canonical subagentRunId onto the non-event interfaces", + ); + expect(result.quarantine[0].rawLocation).toBe( + "/repo/src/__tests__/drift/agui-nonevent-schema.drift.ts:190:89", + ); + expect(result.quarantine[0].message).toBe(AGUI_NONEVENT_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 and on a run with no failures", () => { + const result = collectAgUiDriftEntries( + makeResult([ + makeAssertion({ status: "passed", failureMessages: [] }), + makeAssertion({ status: "failed", failureMessages: [] }), + ]), + ); + expect(result.entries).toEqual([]); + expect(result.quarantine).toEqual([]); + expect(computeExitCode(0, 0, false, 0)).toBe(0); + }); +}); + +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"); + }); +}); From cf87142b2f939849802f618c0aeb7beb84affa1a Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Sun, 30 Aug 2026 16:12:14 -0700 Subject: [PATCH 10/10] fix(drift): withdraw the AG-UI non-event guard and close two collector fail-opens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hand-rolled schema differ in `src/__tests__/drift/agui-nonevent-schema.drift.ts` produced a fail-open bug in each of three consecutive review rounds. It is withdrawn rather than patched a fourth time; the follow-up that rewrites the legacy drift harness will build one differ properly, once. Its `AGUI_NONEVENT_FAILURE` collector fixture goes with it — it was documented as a verbatim vitest capture but carried 2 of 4 drift lines and the wrong frame, so it could not be trusted in any form. The fail-closed test it anchored now runs on `AGUI_UNPARSEABLE_SCHEMA_FAILURE`, a real capture from the surviving `agui-schema.drift.ts`, which is the guard the invariant actually protects. Two fail-opens that outlive the withdrawal are fixed: - `collectAgUiDriftEntries` skipped a FAILED assertion whose `failureMessages` was empty, before it was even looked at — zero entries, exit 0, `conclusion: "clean"`. A failure with no message is the least interpretable failure there is, so it now takes the same quarantine lane (exit 5) as an unrecognized message. The test that PINNED the old behavior pinned a fail-open; it now pins the quarantine. - A ZERO-exit AG-UI run whose stdout is not vitest JSON returned `{ testResults: [] }`, which the collector reads as "no failures", while the HTTP twin `runDriftTests()` throws on the identical condition. The AG-UI leg now throws too. The run/parse half is extracted as the exported `runAgUiVitest(exec)` so that contract is testable without spawning vitest. The barrel-export guard, `subagentRunId` on `AGUIMessage`/`AGUIInterrupt`, the CI lane's `agui-` path-prefix filter and naming contract, and the collector's fail-closed invariant are all untouched. `subagentRunId` on the two non-event types now ships with NO regression test — the CHANGELOG says so plainly rather than implying a guard exists. --- CHANGELOG.md | 7 +- scripts/drift-report-collector.ts | 72 ++- src/__tests__/drift-collector.test.ts | 98 +++- .../drift/agui-nonevent-schema.drift.ts | 484 ------------------ 4 files changed, 130 insertions(+), 531 deletions(-) delete mode 100644 src/__tests__/drift/agui-nonevent-schema.drift.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7469ac77..e675887e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,16 +4,17 @@ ### 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, and by a new non-event drift suite covering the canonical schemas the existing `*EventSchema` walk could never see. **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) +- **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 — including the non-event suite above, which would otherwise have shipped never running in CI — as does any future guard, 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. -- **A missing canonical checkout now fails the non-event drift guard instead of skipping it green.** Its source-availability assertion no longer sits inside a `describe.skipIf` on the very condition it checks, so a CI run with no `../ag-ui` clone fails loudly rather than exiting 0 having compared nothing. The local `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1` escape hatch, for a developer running the drift suite with no sibling checkout, is inert whenever `CI=true` and pins that precondition as its own assertion (#391) +- **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 diff --git a/scripts/drift-report-collector.ts b/scripts/drift-report-collector.ts index 48266f41..9a9318c1 100644 --- a/scripts/drift-report-collector.ts +++ b/scripts/drift-report-collector.ts @@ -1595,22 +1595,35 @@ function ensureAgUiRepo(): boolean { return true; } -function runAgUiDriftTests(): VitestJsonResult | null { - if (!ensureAgUiRepo()) return null; +/** 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 { - const stdout = execSync( + stdout = exec( `npx vitest run ${AGUI_DRIFT_TEST_FILTER} --config vitest.config.drift.ts --reporter=json`, - { - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - maxBuffer: 50 * 1024 * 1024, - }, ); - 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"); @@ -1620,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(); } /** @@ -1636,9 +1657,10 @@ function runAgUiDriftTests(): VitestJsonResult | null { * 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 guard (e.g. the non-event `subagentRunId` attribution - * check, whose message matches none of the three shapes) produced zero entries, - * exit 0 and `conclusion: "clean"`. Every unrecognized failure is now returned + * 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 @@ -1659,7 +1681,23 @@ export function collectAgUiDriftEntries(results: VitestJsonResult): { 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(" > "); @@ -1729,7 +1767,7 @@ export function collectAgUiDriftEntries(results: VitestJsonResult): { // HTTP leg quarantines its unmappable failures. quarantine.push({ provider: "AG-UI", - testName: `${assertion.ancestorTitles.join(" ")} > ${assertion.title}`.trim(), + testName: testNameForQuarantine, rawLocation: extractRawLocation(fullMessage), message: fullMessage, }); diff --git a/src/__tests__/drift-collector.test.ts b/src/__tests__/drift-collector.test.ts index f018f203..dca7ec2f 100644 --- a/src/__tests__/drift-collector.test.ts +++ b/src/__tests__/drift-collector.test.ts @@ -27,6 +27,7 @@ import { parseKnownModelsCanary, collectDriftEntries, collectAgUiDriftEntries, + runAgUiVitest, classifyAgUiCheckout, AGUI_CANONICAL_TYPES_RELPATH, computeExitCode, @@ -3272,24 +3273,18 @@ describe("WS-5 — SURFACE_REGISTRY coverage & integrity", () => { // // 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"`. The -// fixtures below are REAL vitest `--reporter=json` failure messages captured by -// mutating `src/agui-types.ts` (deleting `subagentRunId` from `AGUIMessage`, and -// renaming `TEXT_MESSAGE_START` in `AGUIEventType`) and running +// 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 the non-event `subagentRunId` guard — matches NO recognizer. */ -const AGUI_NONEVENT_FAILURE = [ - "AssertionError: Non-event subagent attribution drift:", - ` BaseMessageSchema declares optional "subagentRunId" but aimock's AGUIMessage does not mirror it`, - ` ToolMessageSchema declares optional "subagentRunId" but aimock's AGUIMessage does not mirror it: expected [ …(4) ] to deeply equal []`, - " at /repo/src/__tests__/drift/agui-nonevent-schema.drift.ts:190:89", - " at file:///repo/node_modules/.pnpm/@vitest+runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js:155:11", -].join("\n"); - -/** Real failure of an EXISTING agui-schema.drift.ts assertion — also unrecognized. */ +/** 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)", @@ -3308,9 +3303,9 @@ describe("collectAgUiDriftEntries — fail-closed on uninterpretable failures", const result = collectAgUiDriftEntries( makeResult([ makeAssertion({ - ancestorTitles: ["AG-UI non-event schema drift"], - title: "mirrors canonical subagentRunId onto the non-event interfaces", - failureMessages: [AGUI_NONEVENT_FAILURE], + ancestorTitles: ["AG-UI schema drift"], + title: "should parse aimock event types", + failureMessages: [AGUI_UNPARSEABLE_SCHEMA_FAILURE], }), ]), ); @@ -3318,13 +3313,11 @@ describe("collectAgUiDriftEntries — fail-closed on uninterpretable failures", expect(result.entries).toEqual([]); expect(result.quarantine).toHaveLength(1); expect(result.quarantine[0].provider).toBe("AG-UI"); - expect(result.quarantine[0].testName).toContain( - "mirrors canonical subagentRunId onto the non-event interfaces", - ); + expect(result.quarantine[0].testName).toContain("should parse aimock event types"); expect(result.quarantine[0].rawLocation).toBe( - "/repo/src/__tests__/drift/agui-nonevent-schema.drift.ts:190:89", + "/repo/src/__tests__/drift/agui-schema.drift.ts:404:25", ); - expect(result.quarantine[0].message).toBe(AGUI_NONEVENT_FAILURE); + 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. @@ -3375,17 +3368,68 @@ describe("collectAgUiDriftEntries — fail-closed on uninterpretable failures", expect(result.entries[0].diffs[0].path).toBe("AGUIEventType.TEXT_MESSAGE_START"); }); - it("stays silent on passing assertions and on a run with no failures", () => { + it("stays silent on passing assertions", () => { const result = collectAgUiDriftEntries( - makeResult([ - makeAssertion({ status: "passed", failureMessages: [] }), - makeAssertion({ status: "failed", failureMessages: [] }), - ]), + 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", () => { diff --git a/src/__tests__/drift/agui-nonevent-schema.drift.ts b/src/__tests__/drift/agui-nonevent-schema.drift.ts deleted file mode 100644 index 1279d7c6..00000000 --- a/src/__tests__/drift/agui-nonevent-schema.drift.ts +++ /dev/null @@ -1,484 +0,0 @@ -/** - * AG-UI non-event schema drift test. - * - * The sibling `agui-schema.drift.ts` only walks `*EventSchema` against - * `AGUI*Event` interfaces, so drift in the non-event types — messages, - * interrupts, tool calls — is invisible to it. This file closes that gap for - * subagent attribution specifically: canonical `subagentRunId` is what lets a - * client group replayed content under the subagent that produced it, and a - * fixture whose message or interrupt silently drops the field replays as - * root-attributed work. - * - * Scoped to `subagentRunId` on purpose. A general field-by-field comparison of - * the non-event types is a larger surface (aimock deliberately flattens the - * seven canonical message schemas into one `AGUIMessage`) and is tracked - * separately. - * - * Both sides are read with the TypeScript parser (`ts.createSourceFile`, - * syntax-only — no program, no type checker), never with regexes over the - * source text. Every way a regex reader of this shape fails is a fail-OPEN - * failure, which is the worst kind for a drift guard: a brace inside a comment - * runs a hand-rolled brace counter past the end of the schema it was reading, - * a `subagentRunId` nested one level down inside a property value masks its - * removal from the top level, and a literal-text pin on `subagentRunId?: - * string;` reports false drift on a reformat, a `readonly`, or a widened type. - * The parser sees comments and strings as trivia, distinguishes a top-level - * member from a nested one by construction, and exposes optionality and type - * as structure rather than as text, so none of those failures are expressible - * here. - */ - -import { describe, it, expect } from "vitest"; -import fs from "node:fs"; -import path from "node:path"; -import ts from "typescript"; - -const CANONICAL_TYPES_PATH = path.resolve( - import.meta.dirname, - "../../../../ag-ui/sdks/typescript/packages/core/src/types.ts", -); -const AIMOCK_TYPES_PATH = path.resolve(import.meta.dirname, "../../agui-types.ts"); - -/** The one canonical field this guard tracks across the non-event types. */ -const FIELD = "subagentRunId"; - -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); - -const propertyName = (name: ts.PropertyName | undefined): string | null => - name && (ts.isIdentifier(name) || ts.isStringLiteral(name)) ? name.text : null; - -/** - * The member names a zod schema initializer declares *itself*, at the top - * level of its own object literal(s). - * - * The walk descends through the builder chain — `z.object({...})`, - * `Base.extend({...})`, `z.object({...}).strict()` — but stops at every object - * literal it reaches, collecting that literal's property names without - * descending into their values. That boundary is what makes a nested - * `subagentRunId` (say, inside a `z.object({ meta: z.object({ subagentRunId: - * ... }) })`) invisible here, which is the point: a nested occurrence must not - * mask the removal of the top-level one. - * - * "Itself" also excludes inherited members: `UserMessageSchema = - * BaseMessageSchema.extend({ role: ... })` declares only `role`. Inheritance - * is deliberately not resolved — the mirror list below covers the schemas that - * *declare* the field, and resolving `.extend()` chains would drag in every - * message subtype for a field they do not restate. - */ -function ownMemberNames(initializer: ts.Expression): string[] { - const names: string[] = []; - const visit = (node: ts.Node): void => { - if (ts.isObjectLiteralExpression(node)) { - for (const property of node.properties) { - const name = propertyName(property.name); - if (name !== null) names.push(name); - } - return; - } - ts.forEachChild(node, visit); - }; - visit(initializer); - return names; -} - -/** - * Every exported top-level `const = ` in the canonical - * types module, mapped to the member names it declares itself. - */ -export function canonicalSchemaMembers(fileName: string, source: string): Map { - const schemas = new Map(); - for (const statement of parse(fileName, source).statements) { - if (!ts.isVariableStatement(statement) || !isExported(statement)) continue; - for (const declaration of statement.declarationList.declarations) { - if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue; - schemas.set(declaration.name.text, ownMemberNames(declaration.initializer)); - } - } - return schemas; -} - -/** The canonical schemas that declare `field` as a member of their own object literal. */ -export function canonicalSchemasDeclaring( - fileName: string, - source: string, - field: string, -): string[] { - return [...canonicalSchemaMembers(fileName, source)] - .filter(([, members]) => members.includes(field)) - .map(([name]) => name) - .sort(); -} - -/** - * One top-level property signature of an aimock interface, read structurally. - * - * `optional` is true when the member can be absent *or* explicitly - * `undefined`, so `x?: string` and `x: string | undefined` are the same fact. - * `types` is the set of syntax kinds the (flattened) union admits, which is - * what the widening rule below is expressed over. Nested type literals are not - * searched: only the interface's own members count. - */ -export function aimockInterfaceMember( - fileName: string, - source: string, - interfaceName: string, - field: string, -): { optional: boolean; typeText: string; parts: ts.TypeNode[] } | null | undefined { - for (const statement of parse(fileName, source).statements) { - if (!ts.isInterfaceDeclaration(statement) || statement.name.text !== interfaceName) continue; - for (const member of statement.members) { - if (!ts.isPropertySignature(member) || propertyName(member.name) !== field) continue; - const type = member.type; - const parts = type && ts.isUnionTypeNode(type) ? [...type.types] : type ? [type] : []; - return { - optional: member.questionToken !== undefined || parts.some(isUndefinedType), - typeText: type ? type.getText() : "(no type)", - parts, - }; - } - // Interface found, member absent. - return null; - } - // Interface itself absent — a distinct fact from "declared without the field". - return undefined; -} - -const isUndefinedType = (node: ts.TypeNode) => - node.kind === ts.SyntaxKind.UndefinedKeyword || - (ts.isLiteralTypeNode(node) && node.literal.kind === ts.SyntaxKind.UndefinedKeyword); - -/** - * The widening rule, stated once. - * - * Canonical `subagentRunId: z.string().optional()` parses to `string | - * undefined`. An aimock mirror is CORRECT when it (a) exists, (b) can be - * absent or `undefined`, and (c) admits a bare `string`. Anything that adds - * further members to the union — `string | null`, `string | SomeBrand` — is an - * ACCEPTABLE WIDENING: every canonical value still fits, so no fixture that - * round-trips through the canonical schema can fail to type-check here. - * NARROWING is drift: dropping optionality (a canonical value may be absent), - * or replacing `string` with something stricter such as a literal union or a - * branded alias (a canonical value may then not fit). - * - * Formatting, `readonly`, trailing punctuation, and member ordering are not - * facts about the type and are invisible to this rule by construction. - */ -function mirrorProblem(member: { optional: boolean; typeText: string; parts: ts.TypeNode[] }) { - if (!member.optional) { - return `is required (\`${member.typeText}\`) but canonical declares it optional`; - } - const admitsString = member.parts.some((part) => part.kind === ts.SyntaxKind.StringKeyword); - if (!admitsString) { - return `has type \`${member.typeText}\`, which does not admit a bare \`string\``; - } - return null; -} - -/** - * Canonical schema -> the aimock interface that mirrors it. - * - * Aimock flattens the canonical message union into a single `AGUIMessage` - * discriminated by `role`, so all four canonical message schemas that carry - * `subagentRunId` map onto that one interface. - * - * This list is not trusted to be complete: the completeness test below asserts - * it covers exactly the canonical schemas that declare the field, so a NEW - * canonical schema carrying `subagentRunId` fails loudly here instead of going - * silently uncompared. - */ -const MIRRORS: Array<{ canonical: string; aimock: string }> = [ - { canonical: "BaseMessageSchema", aimock: "AGUIMessage" }, - { canonical: "ToolMessageSchema", aimock: "AGUIMessage" }, - { canonical: "ActivityMessageSchema", aimock: "AGUIMessage" }, - { canonical: "ReasoningMessageSchema", aimock: "AGUIMessage" }, - { canonical: "InterruptSchema", aimock: "AGUIInterrupt" }, -]; - -/** - * Read a source file, returning the error rather than throwing, so the - * availability gate below can report *which* side is missing. - */ -function readSource(file: string): { source: string; error: string | null } { - try { - const source = fs.readFileSync(file, "utf-8"); - if (source.trim() === "") return { source: "", error: `${file} is empty` }; - return { source, error: null }; - } catch (err: unknown) { - return { source: "", error: err instanceof Error ? err.message : String(err) }; - } -} - -/** - * Truthiness for a CI-style environment flag. - * - * GitHub Actions sets `CI=true`, but other runners set `CI=1`, `CI=True`, or - * `CI=yes`, and an exact `=== "true"` comparison hands all of those the local - * escape hatch that is supposed to be unreachable in CI. Anything set and not - * an explicit negation counts as CI. - */ -export function isTruthyEnvFlag(value: string | undefined): boolean { - if (value === undefined) return false; - const normalized = value.trim().toLowerCase(); - return normalized !== "" && !["0", "false", "no", "off"].includes(normalized); -} - -const canonical = readSource(CANONICAL_TYPES_PATH); -const aimock = readSource(AIMOCK_TYPES_PATH); - -/** - * Escape hatch for a developer running `pnpm test:drift` with no sibling ag-ui - * checkout. Deliberately inert under CI: `CI` is set by every GitHub Actions - * runner, so the opt-out cannot be inherited by an automated lane, and a CI run - * without the canonical checkout fails instead of reporting a clean drift check. - */ -const localOptOut = - process.env.AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT === "1" && !isTruthyEnvFlag(process.env.CI); - -/** - * Availability gate. This block is deliberately NOT skipped by the same - * condition it checks: putting the "are the sources there?" assertion inside a - * `describe.skipIf(!sourcesThere)` — as this file originally did — makes a - * missing canonical checkout skip the assertion that was supposed to catch it, - * so the whole file exits 0 while comparing nothing. - */ -describe("AG-UI non-event schema sources", () => { - it("has both schema sources available", () => { - // aimock's own types ship in this repo; unreadable is always a hard failure. - expect(aimock.error, `aimock types unreadable at ${AIMOCK_TYPES_PATH}: ${aimock.error}`).toBe( - null, - ); - - if (canonical.error !== null && localOptOut) { - console.warn( - `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1: skipping AG-UI non-event drift comparison (${canonical.error}).`, - ); - // Pin the opt-out's own precondition so it can never apply inside CI. - expect( - isTruthyEnvFlag(process.env.CI), - "the missing-checkout opt-out must never apply in CI", - ).toBe(false); - return; - } - - expect( - canonical.error, - `canonical ag-ui types unreadable at ${CANONICAL_TYPES_PATH}: ${canonical.error}. ` + - `Clone the canonical repo next to this one (git clone --depth 1 ` + - `https://github.com/ag-ui-protocol/ag-ui.git ../ag-ui), or set ` + - `AIMOCK_ALLOW_MISSING_AGUI_CHECKOUT=1 to skip the comparison locally.`, - ).toBe(null); - }); -}); - -const canonicalSource = canonical.source; -const aimockSource = aimock.source; - -// Skipped whenever either source failed to read — which is the local opt-out -// case, and otherwise a case the availability gate above has ALREADY failed on, -// so the file still exits non-zero. The skip only suppresses a cascade of -// secondary failures that would all be restating the same missing checkout. -describe.skipIf(canonical.error !== null || aimock.error !== null)( - "AG-UI non-event schema drift", - () => { - const schemas = canonicalSchemaMembers(CANONICAL_TYPES_PATH, canonicalSource); - - it("parses the canonical non-event schemas it compares", () => { - // Positive control: a mirror silently going unparsed would make the drift - // assertion below vacuously green. - const unparsed = MIRRORS.map((m) => m.canonical).filter((name) => !schemas.has(name)); - expect(unparsed, `canonical schemas the parser did not find: ${unparsed.join(", ")}`).toEqual( - [], - ); - - const interfaces = [...new Set(MIRRORS.map((m) => m.aimock))]; - const missing = interfaces.filter( - (name) => aimockInterfaceMember(AIMOCK_TYPES_PATH, aimockSource, name, FIELD) === undefined, - ); - expect(missing, `aimock interfaces the parser did not find: ${missing.join(", ")}`).toEqual( - [], - ); - }); - - it("covers every canonical schema that declares subagentRunId", () => { - // Completeness. MIRRORS is a hand-written map because the aimock side of - // it cannot be derived (aimock flattens seven message schemas into one - // interface), so the canonical side is derived instead and the two are - // required to agree exactly. A new canonical schema carrying the field - // fails here rather than being silently left uncompared, and a schema - // that stops declaring it fails here rather than being compared against - // nothing. - const declared = canonicalSchemasDeclaring(CANONICAL_TYPES_PATH, canonicalSource, FIELD); - const covered = [...new Set(MIRRORS.map((m) => m.canonical))].sort(); - expect( - declared, - `MIRRORS must cover exactly the canonical schemas declaring "${FIELD}". ` + - `Canonical declares it on: ${declared.join(", ") || "(none)"}; ` + - `MIRRORS covers: ${covered.join(", ")}. ` + - `Add or remove a MIRRORS entry (and the matching aimock field) to match.`, - ).toEqual(covered); - }); - - it("mirrors canonical subagentRunId onto the non-event interfaces", () => { - const drifts: string[] = []; - - for (const { canonical: schemaName, aimock: interfaceName } of MIRRORS) { - const members = schemas.get(schemaName); - if (members === undefined) continue; // reported by the parse test above - - // The canonical side is ASSERTED, not used as a silent precondition. An - // upstream rename or removal of `subagentRunId` is exactly the drift this - // file exists to catch, so `continue`-ing past it here would report the - // rename as "no drift". - if (!members.includes(FIELD)) { - drifts.push( - `canonical ${schemaName} no longer declares "${FIELD}" — upstream renamed or ` + - `removed it; update MIRRORS and aimock's ${interfaceName} to match`, - ); - continue; - } - - const member = aimockInterfaceMember(AIMOCK_TYPES_PATH, aimockSource, interfaceName, FIELD); - if (member === undefined) continue; // reported by the parse test above - if (member === null) { - drifts.push( - `${schemaName} declares optional "${FIELD}" but aimock's ${interfaceName} does not mirror it`, - ); - continue; - } - const problem = mirrorProblem(member); - if (problem !== null) { - drifts.push( - `${schemaName} declares optional "${FIELD}" but aimock's ${interfaceName}.${FIELD} ${problem}`, - ); - } - } - - expect(drifts, `Non-event subagent attribution drift:\n ${drifts.join("\n ")}`).toEqual([]); - }); - }, -); - -// The guard is only as good as its readers, so the readers are tested directly -// on the shapes that defeat a regex/brace-counting implementation. -describe("non-event schema readers", () => { - const member = (source: string, iface = "I") => - aimockInterfaceMember("types.ts", source, iface, FIELD); - - it("is not confused by a brace inside a comment", () => { - const source = [ - "export const AlphaSchema = z.object({", - " // an opening brace { that a brace counter would follow", - " id: z.string(),", - "});", - "export const BetaSchema = z.object({", - " subagentRunId: z.string().optional(),", - "});", - ].join("\n"); - expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["BetaSchema"]); - }); - - it("is not confused by a brace inside a string literal", () => { - const source = [ - 'export const AlphaSchema = z.object({ id: z.literal("{"), name: z.string() });', - "export const BetaSchema = z.object({ subagentRunId: z.string().optional() });", - ].join("\n"); - expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["BetaSchema"]); - }); - - it("does not let a nested occurrence stand in for a top-level member", () => { - const source = - "export const AlphaSchema = z.object({ meta: z.object({ subagentRunId: z.string() }) });"; - expect(canonicalSchemaMembers("types.ts", source).get("AlphaSchema")).toEqual(["meta"]); - expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual([]); - }); - - it("reads members declared through an extend chain but not inherited ones", () => { - const source = [ - "export const AlphaSchema = z.object({ subagentRunId: z.string().optional() });", - "export const BetaSchema = AlphaSchema.extend({ role: z.literal('beta') });", - "export const GammaSchema = z.object({ id: z.string() }).extend({ subagentRunId: z.string() });", - ].join("\n"); - expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual([ - "AlphaSchema", - "GammaSchema", - ]); - }); - - it("skips unexported and non-schema declarations", () => { - const source = [ - "const HiddenSchema = z.object({ subagentRunId: z.string() });", - "export const VisibleSchema = z.object({ subagentRunId: z.string() });", - ].join("\n"); - expect(canonicalSchemasDeclaring("types.ts", source, FIELD)).toEqual(["VisibleSchema"]); - }); - - it("distinguishes a missing interface from a missing member", () => { - expect(member("export interface Other { subagentRunId?: string }")).toBeUndefined(); - expect(member("export interface I { id: string }")).toBeNull(); - }); - - it("reads optionality from the question token", () => { - expect(member("export interface I { subagentRunId?: string }")).toMatchObject({ - optional: true, - }); - expect(member("export interface I { subagentRunId: string }")).toMatchObject({ - optional: false, - }); - }); - - it("treats an explicit `| undefined` union as optional", () => { - expect(member("export interface I { subagentRunId: string | undefined }")).toMatchObject({ - optional: true, - }); - }); - - it("ignores a nested type literal's members", () => { - expect(member("export interface I { nested: { subagentRunId?: string } }")).toBeNull(); - }); - - it("is unaffected by readonly, formatting, and missing semicolons", () => { - const source = [ - "export interface I {", - " readonly", - " subagentRunId?:", - " string", - "}", - ].join("\n"); - expect(mirrorProblem(member(source)!)).toBeNull(); - }); -}); - -describe("non-event widening rule", () => { - const problemFor = (declaration: string) => { - const parsed = aimockInterfaceMember( - "types.ts", - `export interface I { ${declaration} }`, - "I", - FIELD, - ); - if (parsed === null || parsed === undefined) throw new Error("member not parsed"); - return mirrorProblem(parsed); - }; - - it.each([ - "subagentRunId?: string;", - "subagentRunId?: string | null;", - "subagentRunId: string | undefined;", - "subagentRunId?: string | number;", - ])("accepts the widening %s", (declaration) => { - expect(problemFor(declaration)).toBeNull(); - }); - - it.each([ - ["subagentRunId: string;", "is required"], - ['subagentRunId?: "a" | "b";', "does not admit"], - ["subagentRunId?: number;", "does not admit"], - ])("rejects the narrowing %s", (declaration, fragment) => { - expect(problemFor(declaration)).toContain(fragment); - }); -});