{"version":3,"file":"validation.cjs","names":[],"sources":["../../src/batteries/validation/profiles/permissive.ts","../../src/batteries/validation/profiles/tool_identity.ts","../../src/batteries/validation/profiles/non_empty_turn.ts","../../src/batteries/validation/profiles/schema_integrity.ts","../../src/batteries/validation/profiles/tool_call_id_format.ts","../../src/batteries/validation/profiles/strict_alternation.ts","../../src/batteries/validation/profiles/tool_call_id_uniqueness.ts","../../src/batteries/validation/profiles/openai_shape_baseline.ts","../../src/batteries/validation/profiles/stale_thinking_advisory.ts","../../src/batteries/validation/profiles/thinking_before_tool_use.ts","../../src/batteries/validation/profiles/single_tool_call_per_turn.ts","../../src/batteries/validation/profiles/full_history_preservation.ts","../../src/batteries/validation/profiles/thought_signature_required.ts","../../src/batteries/validation/profiles/thought_signature_advisory.ts","../../src/batteries/validation/profiles/payload_field_preservation.ts","../../src/batteries/validation/profiles/role_remap_split_tool_roles.ts","../../src/batteries/validation/profiles/role_remap_inline_tool_call.ts","../../src/batteries/validation/profiles/harmony_commentary_channel.ts","../../src/batteries/validation/profiles/function_response_adjacency.ts","../../src/batteries/validation/profiles/converse_text_before_tool_use.ts","../../src/batteries/validation/profiles/reasoning_pruned_after_latest_turn.ts","../../src/batteries/validation/profiles/index.ts","../../src/batteries/validation/helpers.ts","../../src/batteries/validation/profiles/families.ts","../../src/batteries/validation/middleware.ts"],"sourcesContent":["/**\n * The deliberately empty ordering baseline for xAI Grok.\n *\n * Grok documents no role-order limitation. That is a real vendor claim, not permission\n * to confuse missing validation with permissiveness. Source: xAI documentation; date\n * checked: this plan's research pass.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const permissive: OrderingProfile = {\n  name: 'permissive',\n  description:\n    \"xAI Grok documents no role-order limitation at all; source checked during this plan's research pass.\",\n  permissive: true,\n  rules: [],\n}\n","/**\n * A replayed tool result must name a tool the request actually declares.\n *\n * @remarks\n * MEASURED, not documented — this rule exists because of a root cause found in a production\n * gateway, not because a vendor wrote it down.\n *\n * Gemini matches `functionResponse.name` against the request's `functionDeclarations`. A name that\n * resolves to nothing — an opaque call id used in place of the tool name, or a tool that is no\n * longer offered this turn — makes it return an empty candidate (`parts: [{text: ''}]`, `STOP`, no\n * `candidatesTokenCount`) a large fraction of the time. A gateway then forwards that as an ordinary\n * `finish_reason: stop` with `content: null` and NO error, so the caller records a successful turn\n * that produced nothing and loops.\n *\n * That silence is what makes it worth a rule: there is no status code to catch, no error body to\n * classify, and the failure is intermittent rather than deterministic. Advisory by default like the\n * rest of the catalog — but this is a strong candidate for `blocking` on any Gemini-family target.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const toolIdentity: OrderingProfile = {\n  name: 'tool-identity',\n  description:\n    'Every replayed ToolCall must name a tool this request declares; an unresolvable name makes ' +\n    'name-matching providers return an empty generation with no error.',\n  rules: [\n    {\n      type: 'toolIdentity',\n      id: 'tool-result-names-a-declared-tool',\n    },\n  ],\n}\n","/**\n * A turn must carry something the provider can act on.\n *\n * @remarks\n * MEASURED against two vendors, which reject the same underlying defect in two different ways —\n * one loudly, one silently:\n *\n *  - Mistral: HTTP 400, \"Assistant message must have either content or tool_calls, but not none.\"\n *  - Gemini: a request whose FINAL `model` turn carries only a `thought: true` part comes back\n *    `finishReason: MALFORMED_RESPONSE` with no content — measured 4 of 4, against STOP-with-text\n *    when the identical history ends on the user turn instead.\n *\n * A thought alone does not satisfy the rule; that is precisely the shape Gemini refuses. The two\n * variants differ only in scope, so the factory takes it: Gemini's constraint is terminal-position\n * specific, Mistral's applies to any assistant turn in the history.\n */\nimport type { OrderingProfile } from '../types'\n\n/**\n * @param onlyTerminal - Check only the final turn (Gemini) rather than every one (Mistral).\n * @param role - Which role's turns are constrained.\n */\nexport const nonEmptyTurn = (\n  onlyTerminal: boolean = false,\n  role: 'assistant' | 'user' = 'assistant'\n): OrderingProfile => ({\n  name: onlyTerminal ? 'non-empty-terminal-turn' : 'non-empty-turn',\n  description:\n    `Every ${onlyTerminal ? 'terminal ' : ''}${role} turn must carry content or an adjacent tool ` +\n    'call; a turn carrying neither is rejected, sometimes silently.',\n  rules: [\n    {\n      type: 'nonEmptyTurn',\n      id: onlyTerminal ? 'non-empty-terminal-turn' : 'non-empty-turn',\n      role,\n      onlyTerminal,\n    },\n  ],\n})\n","/**\n * A declared tool's input schema must be internally satisfiable.\n *\n * @remarks\n * MEASURED, and the most insidious failure in this catalog. A schema whose `required` list names a\n * key its `properties` does not define cannot be satisfied by ANY argument object. Nova answers\n * such a request with a normal HTTP 200 that simply omits the field — a production gateway records\n * 25 responses silently missing it, with no error at any layer.\n *\n * The usual source is a schema-sanitising pass that strips a keyword from `properties` without\n * pruning the matching entry from `required` — `title` is both a JSON Schema annotation and an\n * ordinary property name, so a blind strip removes the user's field and leaves the requirement.\n *\n * Unlike every other rule here, this one inspects the TOOL DECLARATION rather than turn state, so\n * it catches the defect before a single token is generated.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const schemaIntegrity: OrderingProfile = {\n  name: 'schema-integrity',\n  description:\n    'Every key in a tool schema `required` list must exist in `properties`; an unsatisfiable ' +\n    'schema makes providers return a 200 that silently omits the field.',\n  rules: [\n    {\n      type: 'schemaIntegrity',\n      id: 'required-keys-must-exist-in-properties',\n    },\n  ],\n}\n","/**\n * A ToolCall identifier must satisfy the provider's format constraints.\n *\n * @remarks\n * MEASURED. Two constraints, both hard rejections that name neither the field nor the offending\n * character, and both failing on EVERY credential — so a violation exhausts a provider pool rather\n * than degrading gracefully:\n *\n *  - OpenAI Codex 400s an id longer than 64 characters. A production gateway's own translator names\n *    an ADK-generated id embedding a UUID plus an iteration counter as the trigger.\n *  - Bedrock Converse rejects a `toolUseId` outside `[A-Za-z0-9_-]`.\n *\n * The ADK's own uuidv6 ids satisfy both, so this guards CONSUMER-supplied ids — a caller\n * correlating tool calls by a composite key is the realistic case.\n */\nimport type { OrderingProfile } from '../types'\n\n/**\n * @param maxLength - Identifier cap. 64 matches both Codex and Converse.\n * @param allowedPattern - Character class, anchored by the evaluator.\n */\nexport const toolCallIdFormat = (\n  maxLength: number = 64,\n  allowedPattern: string = '[A-Za-z0-9_-]'\n): OrderingProfile => ({\n  name: 'tool-call-id-format',\n  description:\n    `ToolCall ids must be at most ${maxLength} characters and match ${allowedPattern}; ` +\n    'a violation is a hard rejection on every credential.',\n  rules: [\n    {\n      type: 'identifierFormat',\n      id: 'tool-call-id-format',\n      kind: 'toolCall',\n      maxLength,\n      allowedPattern,\n    },\n  ],\n})\n","/** Strict user/assistant alternation required by Nova, DeepSeek, Gemma, and Llama. Source: vendor model documentation; date checked: this plan's research pass. */\nimport type { OrderingProfile } from '../types'\n\nexport const strictAlternation: OrderingProfile = {\n  name: 'strict-alternation',\n  description:\n    \"User and assistant turns must alternate strictly; source checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'alternation',\n      id: 'strict-user-assistant-alternation',\n      roles: ['user', 'assistant'],\n      mode: 'strict',\n    },\n  ],\n}\n","/**\n * Tool-call identifiers must remain unique across a dispatch timeline.\n *\n * @remarks\n * MEASURED against grok-4.3 on Bedrock Mantle: this upstream resets its tool-call counter per\n * turn, returning identifiers such as `call_0` again on later turns. Well-behaved upstreams already\n * provide globally unique identifiers, so this is a no-op for them. The rule self-limits to actual\n * collisions and does not reject correctly numbered parallel calls in one response.\n *\n * The collision is blocking because an advisory finding cannot be repaired, while reusing an id\n * corrupts result correlation and can make a later dispatch reject the completed call.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const toolCallIdUniqueness: OrderingProfile = {\n  name: 'tool-call-id-uniqueness',\n  description:\n    'Tool-call identifiers must be unique across the dispatch timeline; this measured guard is a ' +\n    'no-op for well-behaved upstreams and self-limits to actual collisions.',\n  rules: [\n    {\n      type: 'identifierUniqueness',\n      id: 'tool-call-id-uniqueness',\n      kind: 'toolCall',\n      severity: 'blocking',\n      surface: 'dispatch',\n    },\n  ],\n}\n","/**\n * Universal tool-call/message immediate-adjacency guard for OpenAI-shaped conversations.\n *\n * Tool results are stored on ToolCall itself in this ADK, not as correlated Message payloads.\n * This catches a malformed Message wedged immediately after a ToolCall.\n */\nimport { toolCallIdUniqueness } from './tool_call_id_uniqueness'\nimport type { OrderingProfile } from '../types'\n\nexport const openaiShapeBaseline: OrderingProfile = {\n  name: 'openai-shape-baseline',\n  description:\n    'A Message may not be immediately wedged after a ToolCall; tool results live on ToolCall itself in this ADK.',\n  rules: [\n    {\n      type: 'adjacency',\n      id: 'message-not-immediately-after-tool-call',\n      first: 'toolCall',\n      disallowBetween: ['message'],\n    },\n    ...toolCallIdUniqueness.rules,\n  ],\n}\n","/**\n * Gemma 4 recommends dropping stale thinking, unless preserveThinking is requested.\n * This is deliberately an advisory, not preservation: sending old thought is discouraged,\n * not a missing invariant. Source: Google Gemma 4 model guidance; date checked: this plan's research pass.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const staleThinkingAdvisory: OrderingProfile = {\n  name: 'stale-thinking-advisory',\n  description:\n    \"Historical thought before the latest non-tool-call user turn is advisory-stale; it never gates dispatch, per Gemma 4 guidance checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'staleContentAdvisory',\n      id: 'stale-thinking-gemma4',\n      kind: 'thought',\n      scope: 'before-latest-user-turn',\n      optOutOptionKey: 'preserveThinking',\n    },\n  ],\n}\n","/** Anthropic manual-thinking mode requires thought before tool use in the latest group. Source: Anthropic extended-thinking documentation; date checked: this plan's research pass. */\nimport type { OrderingProfile } from '../types'\n\nexport const thinkingBeforeToolUse: OrderingProfile = {\n  name: 'thinking-before-tool-use',\n  description:\n    \"The latest same-role group must place thought before ToolCall; source checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'order',\n      id: 'thinking-before-tool-use',\n      before: 'thought',\n      after: 'toolCall',\n      scope: 'adjacent-same-role-group',\n      onlyLatestGroup: true,\n    },\n  ],\n}\n","/**\n * The Llama 3 one-tool-call cap, now enforced through AlternationRule.maxPerGroup.\n * Parallel tool calls are not a harmless formatting choice for this family. Source: Meta\n * Llama tool-calling documentation; date checked: this plan's research pass.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const singleToolCallPerTurn: OrderingProfile = {\n  name: 'single-tool-call-per-turn',\n  description:\n    \"Llama 3 permits at most one ToolCall per same-role group; maxPerGroup enforces that cap, as checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'alternation',\n      id: 'single-tool-call-per-turn',\n      roles: ['user', 'assistant'],\n      mode: 'strict',\n      maxPerGroup: 1,\n    },\n  ],\n}\n","/**\n * Builds the no-history-loss behavior used for tool calls and thoughts. Source: Kimi,\n * Qwen, MiniMax, Codex, and DeepSeek documentation; date checked: this plan's research pass.\n */\nimport type { OrderingPrimitiveKind, OrderingProfile } from '../types'\n\nexport const fullHistoryPreservation = (kind: OrderingPrimitiveKind): OrderingProfile => ({\n  name: `full-history-preservation-${kind}`,\n  description: `Historical ${kind} count must not decrease across dispatch iterations; source checked during this plan's research pass.`,\n  rules: [\n    {\n      type: 'preservation',\n      id: `full-history-preservation-${kind}`,\n      kind,\n      invariant: 'count-non-decreasing',\n    },\n  ],\n})\n","/**\n * Gemini 3 hard-requires thought_signature on the first function call. Source: Google Gemini\n * thought-signature documentation; date checked: this plan's research pass.\n *\n * @remarks\n * This rule only checks PRESENCE of `payload.thoughtSignature` — it has no way to verify the\n * signature is a genuine one produced by a real Gemini reasoning trace, and it doesn't need to:\n * Google documents two sentinel bypass values for exactly the case where a caller is replaying\n * tool-call history that did not originate from a Gemini call session (e.g. history translated\n * from an OpenAI-shaped conversation, or a model switch mid-conversation) — `'skip_thought_signature_validator'`\n * (works on both the Gemini API and Vertex AI) and `'context_engineering_is_the_way_to_go'`\n * (Gemini API only, NOT Vertex AI). Setting `ToolCall.payload.thoughtSignature` to either string\n * satisfies this rule and the real Gemini API's own validation — a caller assembling non-Gemini-\n * originated history for a Gemini 3+ target should populate one of these rather than fabricating\n * an opaque value or omitting the field. Google's own docs caution this should be a last resort,\n * not a default, since it can degrade output quality relative to a real signature.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const thoughtSignatureRequired: OrderingProfile = {\n  name: 'thought-signature-required',\n  description:\n    \"The first ToolCall in its group must carry thoughtSignature. Mutate mode can explicitly repair missing values for non-Gemini-originated replay using Google's documented portable sentinel; the replay tag records the consumer adapter convention.\",\n  rules: [\n    {\n      type: 'requiredMetadata',\n      id: 'thought-signature-required',\n      kind: 'toolCall',\n      applyTo: 'first-in-group',\n      requiredPayloadKey: 'thoughtSignature',\n      // THE ONE RULE THIS CATALOG HAS CONFIRMED. A live audit against each rule's own native API\n      // found 16 of 17 blocking turn state their vendor accepts; this is the exception. Gemini\n      // rejects an unsigned historical `functionCall` with a 400 naming the field and the position\n      // (\"Function call is missing a thought_signature in functionCall parts … position 2\"), and\n      // the same history with the sentinel returns 200. So it keeps `blocking` explicitly while the\n      // rest of the catalog defaults to advisory — see OrderRule.severity.\n      severity: 'blocking',\n      fallbackPayloadValue: 'skip_thought_signature_validator',\n      // Issue #15 defect 3: this fallback is GOOGLE'S OWN published sentinel for replaying\n      // non-Gemini-originated history, not a fabricated provenance claim — so mutate mode may apply\n      // it without the global `allowMetadataFallbackRepair`. Without this, `gemini-3` had no working\n      // configuration at all: enforce nacked, mutate nacked, and the only setting that dispatched\n      // was a flag documented as a last resort. Authorizes THIS rule only.\n      fallbackRepairAuthorized: true,\n      // Consumer convention (not ADK-reserved) identifying Gemini's sentinel replay shape.\n      fallbackReplayCompatibility: 'gemini-thought-signature-sentinel-v1',\n    },\n  ],\n}\n","/**\n * Gemini 2.5's thought signature is recommended, not enforced. RequiredMetadataRule has\n * severity: advisory, so missing metadata is reported without blocking dispatch. Source:\n * Google Gemini documentation; date checked:\n * this plan's research pass.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const thoughtSignatureAdvisory: OrderingProfile = {\n  name: 'thought-signature-advisory',\n  description:\n    \"Gemini 2.5 should carry thoughtSignature on the first ToolCall; severity advisory reports absence without blocking dispatch, as checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'requiredMetadata',\n      id: 'thought-signature-advisory',\n      kind: 'toolCall',\n      applyTo: 'first-in-group',\n      requiredPayloadKey: 'thoughtSignature',\n      severity: 'advisory',\n    },\n  ],\n}\n","/**\n * Builds the opaque-payload continuity behavior. The field is supplied by the recipe because\n * vendors keep different things stable; pretending they share a field would be worse than\n * making the caller say which one. Source: vendor model documentation; date checked: this plan's research pass.\n */\nimport type { OrderingPrimitiveKind, OrderingProfile } from '../types'\n\nexport const payloadFieldPreservation = (\n  payloadField: string,\n  kind: OrderingPrimitiveKind = 'thought'\n): OrderingProfile => ({\n  name: `payload-field-preservation-${kind}-${payloadField.replaceAll('.', '-')}`,\n  description: `${kind} payload field ${payloadField} must remain stable across dispatch iterations; source checked during this plan's research pass.`,\n  rules: [\n    {\n      type: 'preservation',\n      id: `payload-field-preservation-${kind}-${payloadField.replaceAll('.', '-')}`,\n      kind,\n      invariant: 'payload-field-stable',\n      payloadField,\n    },\n  ],\n})\n","/**\n * Granite 3.x renders tool calls and results under distinct wire roles. Source: IBM Granite\n * documentation; date checked: this plan's research pass.\n *\n * PARAMETERIZED, for the same reason {@link payloadFieldPreservation} is: the tag lives on a\n * CONSUMER-SUPPLIED payload field. Nothing in the ADK writes or reads it — no adapter emits it, no\n * primitive carries it by default — so the profile cannot know what a given consumer called it, or\n * what value they stamp. Hardcoding `roleTag` pretended every consumer shares a convention this\n * codebase never defined, and combined with a blocking default that rejected every ToolCall for\n * both Granite families.\n *\n * The caller therefore says which field to read and which value to require, exactly as they do for\n * `payload_field_preservation:signature`. Defaults preserve the previously-documented shape\n * (`payload.roleTag === 'granite-3.x'`) so an existing recipe keeps its meaning.\n */\nimport type { OrderingProfile } from '../types'\n\n/**\n * @param payloadField - Dot-path resolved INSIDE `ToolCall.payload` (so `'roleTag'` reads\n *   `payload.roleTag`). Must not re-state the `payload` prefix.\n * @param variant - The tag value this profile requires.\n * @param severity - `advisory` (default) reports a mismatch without gating dispatch; `blocking`\n *   rejects it. Advisory is the default because the annotation is consumer-supplied: a consumer who\n *   does not populate it must not be prevented from dispatching.\n */\nexport const roleRemapSplitToolRoles = (\n  payloadField: string = 'roleTag',\n  variant: string = 'granite-3.x',\n  severity: 'blocking' | 'advisory' = 'advisory'\n): OrderingProfile => ({\n  name: 'role-remap-split-tool-roles',\n  description:\n    `Granite 3.x requires an explicit wire-role tag for split tool-call and tool-response roles; ` +\n    `this profile reads ToolCall payload.${payloadField} and requires ${variant} (${severity}).`,\n  rules: [\n    {\n      type: 'roleRemap',\n      id: 'granite-3-x-split-tool-roles',\n      kind: 'toolCall',\n      variant,\n      expectedRoleTag: payloadField,\n      severity,\n    },\n  ],\n})\n","/**\n * Granite 4.x keeps calls inline in assistant and remaps tool responses. Source: IBM Granite\n * documentation; date checked: this plan's research pass.\n *\n * PARAMETERIZED for the same reason as {@link roleRemapSplitToolRoles}: the tag lives on a\n * consumer-supplied payload field that nothing in the ADK writes or reads, so the caller must say\n * which field carries it and what value to require. See that profile for the full rationale.\n */\nimport type { OrderingProfile } from '../types'\n\n/**\n * @param payloadField - Dot-path resolved INSIDE `ToolCall.payload` (so `'roleTag'` reads\n *   `payload.roleTag`). Must not re-state the `payload` prefix.\n * @param variant - The tag value this profile requires.\n * @param severity - `advisory` (default) reports a mismatch without gating dispatch; `blocking`\n *   rejects it.\n */\nexport const roleRemapInlineToolCall = (\n  payloadField: string = 'roleTag',\n  variant: string = 'granite-4.x',\n  severity: 'blocking' | 'advisory' = 'advisory'\n): OrderingProfile => ({\n  name: 'role-remap-inline-tool-call',\n  description:\n    `Granite 4.x requires the inline-call wire-role tag and remapped response representation; ` +\n    `this profile reads ToolCall payload.${payloadField} and requires ${variant} (${severity}).`,\n  rules: [\n    {\n      type: 'roleRemap',\n      id: 'granite-4-x-inline-tool-call',\n      kind: 'toolCall',\n      variant,\n      expectedRoleTag: payloadField,\n      severity,\n    },\n  ],\n})\n","/** GPT-OSS requires every function tool call to use Harmony's commentary channel. Source: OpenAI Harmony format documentation; date checked: this plan's research pass. */\nimport type { OrderingProfile } from '../types'\n\nexport const harmonyCommentaryChannel: OrderingProfile = {\n  name: 'harmony-commentary-channel',\n  description:\n    \"Every ToolCall must carry the commentary-channel tag; source checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'requiredMetadata',\n      id: 'harmony-commentary-channel',\n      kind: 'toolCall',\n      applyTo: 'every',\n      requiredPayloadKey: 'channel',\n      // Advisory by default like the rest of the catalog (OrderRule.severity): the live audit\n      // measured gpt-oss ACCEPTING a ToolCall with no channel tag, so blocking would reject a\n      // dispatch the model serves.\n      severity: 'advisory',\n      // Defect #4 from issue #15: this rule declared NO fallbackPayloadValue, so mutate-mode\n      // repair skipped it at helpers.ts's `fallbackPayloadValue !== undefined` guard and every\n      // gpt-oss tool dispatch landed in `unrepaired`. `'commentary'` is Harmony's own channel name\n      // for a function call, so a consumer opting into `blocking` now gets a repairable rule\n      // rather than an unrepairable one.\n      fallbackPayloadValue: 'commentary',\n    },\n  ],\n}\n","/**\n * Gemini function-call immediate-adjacency guard.\n *\n * This ADK has no separate tool-result Message primitive: results live on ToolCall itself.\n * Consequently no correlation field is needed; this directly rejects an unrelated Message\n * immediately following a ToolCall before the function-call sequence continues.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const functionResponseAdjacency: OrderingProfile = {\n  name: 'function-response-adjacency',\n  description:\n    'A Message may not immediately follow a ToolCall; ToolCall owns its function result in this ADK.',\n  rules: [\n    {\n      type: 'adjacency',\n      id: 'message-not-immediately-after-function-call',\n      first: 'toolCall',\n      disallowBetween: ['message'],\n    },\n  ],\n}\n","/** Bedrock Converse requires text blocks before toolUse blocks in one assistant message. Source: AWS Bedrock Converse tool-use documentation; date checked: this plan's research pass. */\nimport type { OrderingProfile } from '../types'\n\nexport const converseTextBeforeToolUse: OrderingProfile = {\n  name: 'converse-text-before-tool-use',\n  description:\n    \"Within one assistant turn, text must precede tool use; source checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'order',\n      id: 'converse-text-before-tool-use',\n      before: 'message',\n      after: 'toolCall',\n      scope: 'entire-turn',\n    },\n  ],\n}\n","/**\n * Qwen 3 may drop reasoning predating the latest non-tool-call user turn, but must retain\n * recent reasoning unchanged. The dedicated invariant expresses that boundary directly.\n * Source: Qwen 3 template documentation; date checked: this plan's research pass.\n */\nimport type { OrderingProfile } from '../types'\n\nexport const reasoningPrunedAfterLatestTurn: OrderingProfile = {\n  name: 'reasoning-pruned-after-latest-turn',\n  description:\n    \"Reasoning older than the latest non-tool-call user turn may be dropped; reasoning at or after that boundary must remain present and unchanged, as checked during this plan's research pass.\",\n  rules: [\n    {\n      type: 'preservation',\n      id: 'reasoning-pruned-after-latest-turn',\n      kind: 'thought',\n      invariant: 'pruned-after-latest-turn',\n    },\n  ],\n}\n","/**\n * Registry of atomic ordering behaviors; family names belong in `families.ts`, not here.\n */\nimport { permissive } from './permissive'\nimport { toolIdentity } from './tool_identity'\nimport { nonEmptyTurn } from './non_empty_turn'\nimport { schemaIntegrity } from './schema_integrity'\nimport { toolCallIdFormat } from './tool_call_id_format'\nimport { strictAlternation } from './strict_alternation'\nimport { E_UNKNOWN_ORDERING_PROFILE } from '../exceptions'\nimport { openaiShapeBaseline } from './openai_shape_baseline'\nimport { toolCallIdUniqueness } from './tool_call_id_uniqueness'\nimport { staleThinkingAdvisory } from './stale_thinking_advisory'\nimport { thinkingBeforeToolUse } from './thinking_before_tool_use'\nimport { singleToolCallPerTurn } from './single_tool_call_per_turn'\nimport { fullHistoryPreservation } from './full_history_preservation'\nimport { thoughtSignatureRequired } from './thought_signature_required'\nimport { thoughtSignatureAdvisory } from './thought_signature_advisory'\nimport { payloadFieldPreservation } from './payload_field_preservation'\nimport { roleRemapSplitToolRoles } from './role_remap_split_tool_roles'\nimport { roleRemapInlineToolCall } from './role_remap_inline_tool_call'\nimport { harmonyCommentaryChannel } from './harmony_commentary_channel'\nimport { functionResponseAdjacency } from './function_response_adjacency'\nimport { converseTextBeforeToolUse } from './converse_text_before_tool_use'\nimport { reasoningPrunedAfterLatestTurn } from './reasoning_pruned_after_latest_turn'\nimport type { OrderingProfile, OrderingPrimitiveKind } from '../types'\n\nexport {\n  fullHistoryPreservation,\n  payloadFieldPreservation,\n  nonEmptyTurn,\n  toolCallIdFormat,\n  toolCallIdUniqueness,\n  roleRemapSplitToolRoles,\n  roleRemapInlineToolCall,\n}\n\nexport type OrderingProfileFactory = (...args: never[]) => OrderingProfile\nexport type RegisteredOrderingProfile = OrderingProfile | OrderingProfileFactory\n\n/** The names are deliberately the behavior/file names used by family recipes. */\nexport const ORDERING_PROFILES: Readonly<Record<string, RegisteredOrderingProfile>> = {\n  permissive,\n  openai_shape_baseline: openaiShapeBaseline,\n  strict_alternation: strictAlternation,\n  single_tool_call_per_turn: singleToolCallPerTurn,\n  thinking_before_tool_use: thinkingBeforeToolUse,\n  thought_signature_required: thoughtSignatureRequired,\n  thought_signature_advisory: thoughtSignatureAdvisory,\n  function_response_adjacency: functionResponseAdjacency,\n  full_history_preservation: fullHistoryPreservation as unknown as OrderingProfileFactory,\n  payload_field_preservation: payloadFieldPreservation as unknown as OrderingProfileFactory,\n  reasoning_pruned_after_latest_turn: reasoningPrunedAfterLatestTurn,\n  stale_thinking_advisory: staleThinkingAdvisory,\n  role_remap_split_tool_roles: roleRemapSplitToolRoles as unknown as OrderingProfileFactory,\n  role_remap_inline_tool_call: roleRemapInlineToolCall as unknown as OrderingProfileFactory,\n  harmony_commentary_channel: harmonyCommentaryChannel,\n  converse_text_before_tool_use: converseTextBeforeToolUse,\n  // MEASURED rules — added from live vendor behaviour rather than vendor documentation. The first\n  // two catch the SILENT failure class: a provider answering 200 with nothing, or with a field\n  // quietly missing. See each profile's remarks for the evidence.\n  tool_identity: toolIdentity,\n  schema_integrity: schemaIntegrity,\n  non_empty_turn: nonEmptyTurn as unknown as OrderingProfileFactory,\n  tool_call_id_format: toolCallIdFormat as unknown as OrderingProfileFactory,\n  tool_call_id_uniqueness: toolCallIdUniqueness,\n}\n\n/** Resolves a non-parameterized behavior by its registry name. */\nexport const getOrderingProfile = (name: string): OrderingProfile => {\n  const registered = ORDERING_PROFILES[name]\n  if (registered === undefined || typeof registered === 'function')\n    throw new E_UNKNOWN_ORDERING_PROFILE([name])\n  return registered\n}\n\n/** Resolves a parameterized behavior token used by `FAMILY_RECIPES`. */\nexport const resolveOrderingBehavior = (name: string): OrderingProfile => {\n  const [behavior, ...args] = name.split(':')\n  if (behavior === 'full_history_preservation' && args.length === 1)\n    return fullHistoryPreservation(args[0] as OrderingPrimitiveKind)\n  if (behavior === 'payload_field_preservation' && args.length >= 1)\n    return payloadFieldPreservation(args.join(':'), 'thought')\n  // `role_remap_*[:field[:variant[:severity]]]` — the tag is a consumer-supplied payload field that\n  // nothing in the ADK writes, so the recipe says which field carries it and what value to require.\n  // Bare `role_remap_split_tool_roles` keeps the documented Granite defaults.\n  if (behavior === 'non_empty_turn')\n    return nonEmptyTurn(args[0] === 'terminal', (args[1] as 'assistant' | 'user') ?? 'assistant')\n  if (behavior === 'tool_call_id_format')\n    return toolCallIdFormat(args[0] ? Number(args[0]) : undefined, args[1])\n  if (behavior === 'role_remap_split_tool_roles')\n    return roleRemapSplitToolRoles(...(args as [string?, string?, ('blocking' | 'advisory')?]))\n  if (behavior === 'role_remap_inline_tool_call')\n    return roleRemapInlineToolCall(...(args as [string?, string?, ('blocking' | 'advisory')?]))\n  return getOrderingProfile(name)\n}\n\nexport {\n  permissive,\n  toolIdentity,\n  schemaIntegrity,\n  openaiShapeBaseline,\n  strictAlternation,\n  singleToolCallPerTurn,\n  thinkingBeforeToolUse,\n  thoughtSignatureRequired,\n  thoughtSignatureAdvisory,\n  functionResponseAdjacency,\n  reasoningPrunedAfterLatestTurn,\n  staleThinkingAdvisory,\n  harmonyCommentaryChannel,\n  converseTextBeforeToolUse,\n}\n","import { Tokenizable } from '@nhtio/adk/common'\nimport { isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport type { Message, Thought, ToolCall } from '@nhtio/adk/common'\nimport type {\n  BlockingOrderingViolation,\n  OrderingAdvisoryViolation,\n  OrderingProfile,\n  OrderingRule,\n  OrderingRepair,\n  OrderingTimelineEntry,\n} from './types'\n\nconst getDotPath = (value: unknown, path: string): unknown => {\n  let current = value\n  for (const segment of path.split('.')) {\n    if (current === null || typeof current !== 'object' || !(segment in current)) return undefined\n    current = (current as Record<string, unknown>)[segment]\n  }\n  return current\n}\n\n/**\n * Writes `value` at `path` inside `target`, creating any missing intermediate objects.\n * The write-side counterpart to {@link getDotPath} — a fallback repair must populate the exact\n * same nested location the evaluator reads, or the post-repair re-evaluation never clears.\n *\n * @remarks\n * Every intermediate object the path walks through is SHALLOW-CLONED before being written into,\n * even when it already exists — never mutated in place. A caller that only shallow-copies its own\n * top-level `target` (e.g. `{ ...snapshot.payload }`) still shares every NESTED object with the\n * original by reference; writing through those without cloning would corrupt the original\n * primitive's payload as a side effect of \"repairing\" an unrelated copy.\n */\nexport const setDotPath = (target: Record<string, unknown>, path: string, value: unknown): void => {\n  const segments = path.split('.')\n  let current = target\n  for (let i = 0; i < segments.length - 1; i++) {\n    const segment = segments[i]\n    const existing = current[segment]\n    current[segment] = isObject(existing) ? { ...existing } : {}\n    current = current[segment] as Record<string, unknown>\n  }\n  current[segments[segments.length - 1]] = value\n}\n\nconst idOf = (entry: OrderingTimelineEntry): string => {\n  const value = entry.value as { id?: unknown }\n  return typeof value.id === 'string' ? value.id : `${entry.kind}:${entry.seq}`\n}\n\nconst blocking = (\n  rule: Exclude<OrderingRule, { type: 'staleContentAdvisory' }>,\n  profile: OrderingProfile,\n  entries: OrderingTimelineEntry[],\n  detail: string\n): BlockingOrderingViolation => ({\n  ruleId: rule.id,\n  ruleType: rule.type,\n  severity: 'blocking',\n  profileName: profile.name,\n  primitiveIds: entries.map(idOf),\n  detail,\n})\n\nconst advisory = (\n  rule: Extract<OrderingRule, { type: 'staleContentAdvisory' }>,\n  profile: OrderingProfile,\n  entries: OrderingTimelineEntry[],\n  detail: string\n): OrderingAdvisoryViolation => ({\n  ruleId: rule.id,\n  ruleType: rule.type,\n  severity: 'advisory',\n  profileName: profile.name,\n  primitiveIds: entries.map(idOf),\n  detail,\n})\n\nconst metadataAdvisory = (\n  rule: OrderingRule,\n  profile: OrderingProfile,\n  entry: OrderingTimelineEntry,\n  detail: string\n): OrderingAdvisoryViolation => ({\n  ruleId: rule.id,\n  ruleType: rule.type,\n  severity: 'advisory',\n  profileName: profile.name,\n  primitiveIds: [idOf(entry)],\n  detail,\n})\n\n/**\n * Route a finding to `blocking` or `advisories` per the rule's own severity.\n *\n * @remarks\n * Omitted severity means ADVISORY for every rule type. See {@link OrderRule.severity} for why:\n * a live audit found 16 of 17 rules blocked turn state their own vendor accepts, so the catalog\n * reports by default and gates only where a consumer has verified the constraint.\n */\nconst record = (\n  result: { blocking: BlockingOrderingViolation[]; advisories: OrderingAdvisoryViolation[] },\n  // Every rule type EXCEPT staleContentAdvisory, which is advisory-only and has its own branch.\n  rule: Exclude<OrderingRule, { type: 'staleContentAdvisory' }>,\n  profile: OrderingProfile,\n  entries: OrderingTimelineEntry[],\n  detail: string\n): void => {\n  const severity = (rule as { severity?: 'blocking' | 'advisory' }).severity\n  if (severity === 'blocking') result.blocking.push(blocking(rule, profile, entries, detail))\n  else result.advisories.push(metadataAdvisory(rule, profile, entries[0]!, detail))\n}\n\nconst entriesForKind = (timeline: OrderingTimelineEntry[], kind: OrderingTimelineEntry['kind']) =>\n  timeline.filter((entry) => entry.kind === kind)\n\nconst roleGroups = (timeline: OrderingTimelineEntry[]): OrderingTimelineEntry[][] => {\n  const roles = timeline.map((entry, index) => {\n    if (entry.kind === 'message') return entry.role\n    let prior = index - 1\n    while (prior >= 0 && timeline[prior].kind !== 'message') prior--\n    let following = index + 1\n    while (following < timeline.length && timeline[following].kind !== 'message') following++\n    // A primitive run between a user prompt and the following assistant message is\n    // the assistant turn being assembled; this keeps the canonical thinking/tool run\n    // together even when adapters timestamp its blocks before the assistant envelope.\n    if (\n      prior >= 0 &&\n      following < timeline.length &&\n      timeline[prior].role === 'user' &&\n      timeline[following].role === 'assistant'\n    )\n      return 'assistant'\n    if (prior < 0 && following >= timeline.length) return undefined\n    if (prior < 0) return timeline[following].role\n    return timeline[prior].role\n  })\n  const groups: OrderingTimelineEntry[][] = []\n  let current: OrderingTimelineEntry[] = []\n  let role: OrderingTimelineEntry['role']\n  timeline.forEach((entry, index) => {\n    if (current.length > 0 && roles[index] !== role) {\n      groups.push(current)\n      current = []\n    }\n    role = roles[index]\n    current.push(entry)\n  })\n  if (current.length > 0) groups.push(current)\n  return groups\n}\n\nconst requiredEntries = (\n  timeline: OrderingTimelineEntry[],\n  rule: Extract<OrderingRule, { type: 'requiredMetadata' }>\n) => {\n  const candidates = entriesForKind(timeline, rule.kind).filter((entry) => {\n    if (rule.gatedByReplayCompatibility === undefined) return true\n    const compatibility = (entry.value as { replayCompatibility?: string }).replayCompatibility\n    return rule.gatedByReplayCompatibility.includes(compatibility ?? '')\n  })\n  if (rule.applyTo === 'every') return candidates\n  return roleGroups(timeline).flatMap((group) => {\n    const first = group.find((entry) => entry.kind === rule.kind)\n    return first !== undefined && candidates.includes(first) ? [first] : []\n  })\n}\n\n/**\n * Builds the adapter-compatible, deterministically ordered primitive timeline.\n *\n * @param messages - Messages to place first in the insertion-order tie-break domain.\n * @param thoughts - Thoughts to place after messages in the tie-break domain.\n * @param toolCalls - Tool calls to place after thoughts in the tie-break domain.\n * @returns A new timeline sorted by creation time and then insertion sequence.\n * @remarks The fixed collection order mirrors existing adapters, making equal-millisecond behavior\n * predictable instead of introducing a guard-only wire ordering.\n */\nexport const buildOrderingTimeline = (\n  messages: Iterable<Message>,\n  thoughts: Iterable<Thought>,\n  toolCalls: Iterable<ToolCall>\n): OrderingTimelineEntry[] => {\n  const entries: OrderingTimelineEntry[] = []\n  let seq = 0\n  for (const value of messages)\n    entries.push({\n      kind: 'message',\n      at: value.createdAt.toMillis(),\n      seq: seq++,\n      role: value.role,\n      value,\n    })\n  for (const value of thoughts)\n    entries.push({\n      kind: 'thought',\n      at: value.createdAt.toMillis(),\n      seq: seq++,\n      role: undefined,\n      value,\n    })\n  for (const value of toolCalls)\n    entries.push({\n      kind: 'toolCall',\n      at: value.createdAt.toMillis(),\n      seq: seq++,\n      role: undefined,\n      value,\n    })\n  return entries.sort((a, b) => a.at - b.at || a.seq - b.seq)\n}\n\n/**\n * Evaluates all stateless ordering rules in a profile.\n *\n * @param timeline - Stable primitive timeline to inspect.\n * @param profile - Declarative rules and reporting identity.\n * @returns Blocking violations and non-blocking advisory findings.\n * @remarks Preservation is intentionally skipped: its previous snapshot belongs in middleware,\n * where the long-lived dispatch context exists; keeping this evaluator pure prevents hidden state.\n */\nexport const evaluateOrderingProfile = (\n  timeline: OrderingTimelineEntry[],\n  profile: OrderingProfile,\n  /**\n   * Optional request context. `toolIdentity` and `schemaIntegrity` need the tools the request\n   * actually declares, which the timeline alone cannot supply; both skip silently when it is\n   * absent, so every existing caller keeps working unchanged.\n   */\n  context?: { tools?: ReadonlyArray<{ name: string; inputSchema?: unknown }> }\n): {\n  blocking: BlockingOrderingViolation[]\n  advisories: OrderingAdvisoryViolation[]\n} => {\n  const result: {\n    blocking: BlockingOrderingViolation[]\n    advisories: OrderingAdvisoryViolation[]\n  } = { blocking: [], advisories: [] }\n  for (const rule of profile.rules) {\n    if (rule.type === 'preservation') continue\n    if (rule.type === 'order') {\n      const groups = rule.scope === 'entire-turn' ? [timeline] : roleGroups(timeline)\n      const selected = rule.onlyLatestGroup ? groups.slice(-1) : groups\n      for (const group of selected) {\n        const before = group.filter((entry) => entry.kind === rule.before)\n        const after = group.filter((entry) => entry.kind === rule.after)\n        if (\n          before.length > 0 &&\n          after.length > 0 &&\n          group.indexOf(before[before.length - 1]) > group.indexOf(after[0])\n        ) {\n          record(\n            result,\n            rule,\n            profile,\n            [...before, ...after],\n            `${rule.before} must precede ${rule.after} in its ordering group.`\n          )\n        }\n      }\n    } else if (rule.type === 'requiredMetadata') {\n      for (const entry of requiredEntries(timeline, rule)) {\n        if (\n          getDotPath((entry.value as { payload?: unknown }).payload, rule.requiredPayloadKey) ===\n          undefined\n        ) {\n          const detail = `Payload is missing required field ${rule.requiredPayloadKey}.`\n          if (rule.severity === 'advisory') {\n            result.advisories.push(metadataAdvisory(rule, profile, entry, detail))\n          } else {\n            result.blocking.push(blocking(rule, profile, [entry], detail))\n          }\n        }\n      }\n    } else if (rule.type === 'alternation') {\n      const messages = timeline.filter(\n        (entry) => entry.kind === 'message' && entry.role !== undefined\n      )\n      for (let index = 1; index < messages.length; index++) {\n        if (messages[index].role === messages[index - 1].role) {\n          record(\n            result,\n            rule,\n            profile,\n            messages.slice(index - 1, index + 1),\n            `Message roles must alternate; both entries are ${messages[index].role}.`\n          )\n        }\n      }\n      if (rule.maxPerGroup !== undefined) {\n        for (const group of roleGroups(timeline)) {\n          const calls = group.filter((entry) => entry.kind === 'toolCall')\n          if (calls.length > rule.maxPerGroup) {\n            record(\n              result,\n              rule,\n              profile,\n              calls,\n              `At most ${rule.maxPerGroup} tool call(s) are allowed in one role group.`\n            )\n          }\n        }\n      }\n    } else if (rule.type === 'adjacency') {\n      const firstEntries = entriesForKind(timeline, rule.first)\n      for (const first of firstEntries) {\n        const firstIndex = timeline.indexOf(first)\n        const next = timeline[firstIndex + 1]\n        // The final entry has no successor, so there is no primitive that can violate adjacency.\n        if (next !== undefined && rule.disallowBetween.includes(next.kind)) {\n          record(\n            result,\n            rule,\n            profile,\n            [first, next],\n            `A ${next.kind} may not immediately follow this ${rule.first}.`\n          )\n        }\n      }\n    } else if (rule.type === 'roleRemap') {\n      for (const entry of entriesForKind(timeline, rule.kind)) {\n        if (\n          getDotPath((entry.value as { payload?: unknown }).payload, rule.expectedRoleTag) !==\n          rule.variant\n        ) {\n          const detail = `Expected role-remap tag ${rule.expectedRoleTag} to equal ${rule.variant}.`\n          // Advisory unless the profile explicitly opts into blocking. `payload.roleTag` is a\n          // consumer-supplied annotation that nothing in the ADK writes, so a blocking default\n          // rejected EVERY ToolCall for both Granite families — with no repair strategy for\n          // `roleRemap`, that left them unable to dispatch a tool call under any configuration.\n          if (rule.severity === 'blocking') {\n            result.blocking.push(blocking(rule, profile, [entry], detail))\n          } else {\n            result.advisories.push(metadataAdvisory(rule, profile, entry, detail))\n          }\n        }\n      }\n    } else if (rule.type === 'identifierFormat') {\n      for (const entry of entriesForKind(timeline, rule.kind)) {\n        const id = String(idOf(entry))\n        if (rule.maxLength !== undefined && id.length > rule.maxLength) {\n          record(\n            result,\n            rule,\n            profile,\n            [entry],\n            `Identifier is ${id.length} characters; this provider caps it at ${rule.maxLength}.`\n          )\n          continue\n        }\n        if (\n          rule.allowedPattern !== undefined &&\n          !new RegExp(`^(?:${rule.allowedPattern})+$`).test(id)\n        ) {\n          record(\n            result,\n            rule,\n            profile,\n            [entry],\n            `Identifier contains characters outside ${rule.allowedPattern}.`\n          )\n        }\n      }\n    } else if (rule.type === 'identifierUniqueness') {\n      // Group the complete timeline rather than partitioning by turn: the defect is specifically\n      // a cross-turn collision, and splitting the timeline would hide the pair we need to report.\n      const entriesById = new Map<string, OrderingTimelineEntry[]>()\n      for (const entry of entriesForKind(timeline, rule.kind)) {\n        const id = idOf(entry)\n        const group = entriesById.get(id)\n        if (group === undefined) entriesById.set(id, [entry])\n        else group.push(entry)\n      }\n      for (const [id, group] of entriesById) {\n        if (group.length > 1) {\n          record(\n            result,\n            rule,\n            profile,\n            group,\n            `Identifier ${id} is shared by ${group.length} ${rule.kind} entries.`\n          )\n        }\n      }\n    } else if (rule.type === 'nonEmptyTurn') {\n      // A turn is non-empty if it carries prose OR an adjacent tool call. A thought alone does not\n      // count: Gemini's terminal thought-only turn is exactly the shape that fails.\n      const messages = timeline.filter(\n        (entry) => entry.kind === 'message' && entry.role === rule.role\n      )\n      const candidates = rule.onlyTerminal\n        ? timeline.length > 0 &&\n          timeline[timeline.length - 1].kind === 'message' &&\n          timeline[timeline.length - 1].role === rule.role\n          ? [timeline[timeline.length - 1]]\n          : []\n        : messages\n      for (const entry of candidates) {\n        // `Message.content` is a Tokenizable, never a bare string. A `typeof === 'string'` test here\n        // silently degraded to a null check no Message could fail — the schema already rejects an\n        // empty content at construction — so this rule caught nothing at all. Whitespace-only IS\n        // constructible, and is the shape that actually reaches a provider.\n        //\n        // A DYNAMIC Tokenizable holds a `(ctx) => string` that cannot be resolved without a\n        // context, which this evaluator does not have. It counts as prose: assuming it renders\n        // empty would reject turns that are fine at assembly time, and a false rejection is the\n        // worse error for a rule whose whole purpose is to avoid one.\n        const content = (entry.value as { content?: unknown }).content\n        const isTokenizable = isInstanceOf(content, 'Tokenizable', Tokenizable)\n        const hasProse =\n          isTokenizable && content.dynamic\n            ? true\n            : (isTokenizable ? String(content.valueOf()) : String(content ?? '')).trim().length > 0\n        const index = timeline.indexOf(entry)\n        const neighbourIsCall =\n          timeline[index + 1]?.kind === 'toolCall' || timeline[index - 1]?.kind === 'toolCall'\n        if (!hasProse && !neighbourIsCall) {\n          record(\n            result,\n            rule,\n            profile,\n            [entry],\n            `A ${rule.role} turn must carry content or an adjacent tool call; this one carries neither.`\n          )\n        }\n      }\n    } else if (rule.type === 'toolIdentity') {\n      // Needs the request's declared tools; skip silently when the caller supplied none.\n      const declared = context?.tools\n      if (declared !== undefined) {\n        const names = new Set(declared.map((tool) => tool.name))\n        for (const entry of entriesForKind(timeline, 'toolCall')) {\n          const name = (entry.value as { tool?: unknown }).tool\n          if (typeof name === 'string' && !names.has(name)) {\n            record(\n              result,\n              rule,\n              profile,\n              [entry],\n              `Tool result names '${name}', which this request does not declare. ` +\n                `Providers that match results against declarations by NAME answer such a request ` +\n                `with an empty generation and no error.`\n            )\n          }\n        }\n      }\n    } else if (rule.type === 'schemaIntegrity') {\n      const declared = context?.tools\n      if (declared !== undefined) {\n        for (const tool of declared) {\n          const schema = tool.inputSchema\n          if (schema === null || typeof schema !== 'object') continue\n          const { required, properties } = schema as {\n            required?: unknown\n            properties?: Record<string, unknown>\n          }\n          if (!Array.isArray(required)) continue\n          const known = new Set(Object.keys(properties ?? {}))\n          const orphans = required.filter((key) => typeof key === 'string' && !known.has(key))\n          if (orphans.length > 0) {\n            // No timeline entry to blame — the defect is in the DECLARATION, so the finding names\n            // the tool. `record` needs an entry, so fall back to the first tool call if present.\n            const anchor = entriesForKind(timeline, 'toolCall')[0] ?? timeline[0]\n            if (anchor !== undefined) {\n              record(\n                result,\n                rule,\n                profile,\n                [anchor],\n                `Tool '${tool.name}' requires ${orphans.join(', ')}, which its properties do not ` +\n                  `define — an unsatisfiable schema. Providers answer such a request with a normal ` +\n                  `200 that silently omits the field.`\n              )\n            }\n          }\n        }\n      }\n    } else if (rule.type === 'staleContentAdvisory') {\n      const latestUser = timeline\n        .map((entry, index) => ({ entry, index }))\n        .filter(({ entry }) => entry.kind === 'message' && entry.role === 'user')\n        .at(-1)\n      if (latestUser) {\n        const stale = timeline.filter(\n          (entry, index) => entry.kind === rule.kind && index < latestUser.index\n        )\n        if (stale.length > 0)\n          result.advisories.push(\n            advisory(\n              rule,\n              profile,\n              stale,\n              `${rule.kind} content predates the latest user turn and is recommended for removal.`\n            )\n          )\n      }\n    }\n  }\n  return result\n}\n\n/**\n * Combines profiles without mutating their rule arrays.\n *\n * @param profiles - Profiles whose rules should be composed in supplied order.\n * @returns A profile containing every input rule, with a deterministic synthesized name.\n * @remarks Union composition is intentionally mechanical so independently sourced vendor rules\n * remain visible and are not silently deduplicated by coincidental ids.\n */\nexport const unionOfRules = (profiles: OrderingProfile[]): OrderingProfile => ({\n  name: `union(${profiles.map((profile) => profile.name).join('+')})`,\n  description: `Union of ${profiles.map((profile) => profile.name).join(', ')}.`,\n  permissive: profiles.every((profile) => profile.permissive === true),\n  rules: profiles.flatMap((profile) => [...profile.rules]),\n})\n\n/**\n * Describes safe repairs for blocking violations without changing caller-owned data.\n *\n * @param timeline - Timeline used to locate implicated primitives; it is never mutated.\n * @param violations - Blocking findings to classify; they are never mutated.\n * @param profiles - Optional profiles used only by explicitly enabled metadata fallback repair.\n * @param authorized - Profiles whose rules authorize their own fallback, reachable without the\n *   global opt-in. See RequiredMetadataRule.fallbackRepairAuthorized.\n * @returns Repairs for reorder/filler strategies and all remaining violations.\n * @remarks Metadata fallback is deliberately unreachable for a rule that neither appears in\n *   `profiles` nor authorizes itself.\n */\nexport const repairViolations = (\n  timeline: OrderingTimelineEntry[],\n  violations: BlockingOrderingViolation[],\n  profiles?: OrderingProfile[],\n  authorized: OrderingProfile[] = []\n): {\n  repaired: OrderingRepair[]\n  unrepaired: BlockingOrderingViolation[]\n  timeline: OrderingTimelineEntry[]\n} => {\n  const copy = timeline.map((entry) => ({ ...entry }))\n  const repaired: OrderingRepair[] = []\n  const unrepaired: BlockingOrderingViolation[] = []\n  for (const violation of violations) {\n    if (violation.ruleType === 'order' && violation.primitiveIds.length >= 2) {\n      const implicated = copy.filter((entry) => violation.primitiveIds.includes(idOf(entry)))\n      const match = /^(\\w+) must precede (\\w+)/.exec(violation.detail)\n      const target = implicated.find((entry) => entry.kind === match?.[1])\n      const blocker = implicated.find((entry) => entry.kind === match?.[2])\n      if (target !== undefined && blocker !== undefined && target !== blocker) {\n        // The rule's directional relationship identifies the item to move. The returned copy is\n        // pre-ordered and must not be re-sorted by callers, or the repair would be undone.\n        copy.splice(copy.indexOf(target), 1)\n        copy.splice(copy.indexOf(blocker), 0, target)\n        repaired.push({\n          violation,\n          strategy: 'reorder',\n          detail: `Move ${idOf(target)} immediately before ${idOf(blocker)} in the pre-ordered timeline.`,\n          targetId: idOf(target),\n          blockerId: idOf(blocker),\n        })\n        continue\n      }\n    }\n    if (violation.ruleType === 'adjacency' && violation.primitiveIds.length >= 2) {\n      // Issue #15 defect 1: adjacency had NO repair branch, so every violation fell through to\n      // `unrepaired` — and `mutate` was identical to `enforce` for the 27 recipes carrying one.\n      //\n      // The violation names [starter, disallowedSuccessor] in that order. Moving the successor to\n      // just BEFORE the starter clears the adjacency while preserving every primitive: the content\n      // still reaches the model, only its position changes. Dropping it would be simpler and lossy,\n      // which is the wrong trade for a rule this catalog now knows most vendors do not enforce.\n      const [starterId, successorId] = violation.primitiveIds\n      const starter = copy.find((entry) => idOf(entry) === starterId)\n      const successor = copy.find((entry) => idOf(entry) === successorId)\n      if (starter !== undefined && successor !== undefined && starter !== successor) {\n        copy.splice(copy.indexOf(successor), 1)\n        copy.splice(copy.indexOf(starter), 0, successor)\n        repaired.push({\n          violation,\n          strategy: 'reorder-adjacent',\n          detail: `Move ${successorId} immediately before ${starterId} so it no longer follows it.`,\n          targetId: successorId,\n          blockerId: starterId,\n        })\n        continue\n      }\n    }\n    // `profiles` is supplied only when the GLOBAL `allowMetadataFallbackRepair` is on; `authorized`\n    // carries the rules that opted in individually, and is always supplied. A rule reachable\n    // through either is repairable. See RequiredMetadataRule.fallbackRepairAuthorized.\n    const candidates = profiles ?? authorized\n    if (violation.ruleType === 'requiredMetadata') {\n      const rule = candidates\n        .find((profile) => profile.name === violation.profileName)\n        ?.rules.find((candidate) => candidate.id === violation.ruleId)\n      if (rule?.type === 'requiredMetadata' && rule.fallbackPayloadValue !== undefined) {\n        repaired.push({\n          violation,\n          strategy: 'fill-required-metadata',\n          detail: `Fill ${violation.primitiveIds[0]} payload.${rule.requiredPayloadKey} with a configured fallback value.`,\n        })\n        continue\n      }\n    }\n    if (violation.ruleType === 'identifierUniqueness' && violation.primitiveIds.length > 1) {\n      // The finding names the complete collision group. Keep this as ONE repair: replacing\n      // members independently lets an id-keyed DELETE remove an unmentioned sibling.\n      repaired.push({\n        violation,\n        strategy: 'renumber-colliding-ids',\n        detail: `Assign a fresh identifier to every member of collision group ${violation.primitiveIds.join(', ')}.`,\n      })\n      continue\n    }\n    if (violation.ruleType === 'alternation' && violation.primitiveIds.length >= 2) {\n      repaired.push({\n        violation,\n        strategy: 'insert-alternation-filler',\n        detail: `Insert synthetic user_continue_message-${violation.primitiveIds[1]} between ${violation.primitiveIds[0]} and ${violation.primitiveIds[1]}; the middleware must materialize the filler.`,\n      })\n      continue\n    }\n    unrepaired.push(violation)\n  }\n  return {\n    repaired,\n    unrepaired,\n    timeline: copy,\n  }\n}\n","/**\n * Family recipes compose atomic behaviors without duplicating profile objects. Parameterized\n * entries use `behavior:argument` so the registry remains a plain string catalog.\n */\nimport { unionOfRules } from '../helpers'\nimport { E_UNKNOWN_ORDERING_PROFILE } from '../exceptions'\nimport { getOrderingProfile, permissive, resolveOrderingBehavior } from './index'\nimport type { OrderingProfile } from '../types'\n\n/**\n * ByteDance Seed is an UNCONFIRMED baseline guess. Do not trust it in `enforce` mode without\n * independent verification against the target's own template documentation.\n */\n/**\n * Muse Spark is an UNCONFIRMED baseline guess. Do not trust it in `enforce` mode without\n * independent verification against Meta's own template documentation.\n */\n/**\n * Muse Glimmer is an UNCONFIRMED baseline guess. Do not trust it in `enforce` mode without\n * independent verification against Meta's own template documentation.\n */\nexport const FAMILY_RECIPES: Record<string, readonly string[]> = {\n  'anthropic-manual-thinking': ['thinking_before_tool_use', 'payload_field_preservation:signature'],\n  'anthropic-adaptive-thinking': ['payload_field_preservation:signature'],\n  'gemini-3': ['thought_signature_required', 'function_response_adjacency'],\n  'gemini-2-5': ['thought_signature_advisory', 'function_response_adjacency'],\n  'nova': ['strict_alternation', 'openai_shape_baseline'],\n  'bedrock-converse': ['converse_text_before_tool_use'],\n  'deepseek-v3-base': ['strict_alternation', 'openai_shape_baseline'],\n  'deepseek-thinking': ['strict_alternation', 'full_history_preservation:thought'],\n  'deepseek-v4': ['strict_alternation', 'full_history_preservation:thought'],\n  'qwen-2-5': ['openai_shape_baseline'],\n  'qwen-3': ['openai_shape_baseline', 'reasoning_pruned_after_latest_turn'],\n  'glm-4-5': ['openai_shape_baseline'],\n  'glm-4-7': ['openai_shape_baseline', 'payload_field_preservation:clear_thinking'],\n  'kimi-k2': ['openai_shape_baseline', 'full_history_preservation:toolCall'],\n  'kimi-k3': [\n    'openai_shape_baseline',\n    'full_history_preservation:toolCall',\n    'full_history_preservation:thought',\n  ],\n  'minimax-m2': [\n    'openai_shape_baseline',\n    'full_history_preservation:toolCall',\n    'full_history_preservation:thought',\n  ],\n  'minimax-m3': [\n    'openai_shape_baseline',\n    'full_history_preservation:toolCall',\n    'full_history_preservation:thought',\n  ],\n  'mistral': ['openai_shape_baseline'],\n  'llama-3': ['openai_shape_baseline', 'single_tool_call_per_turn'],\n  'llama-4': ['openai_shape_baseline'],\n  'nemotron': ['openai_shape_baseline'],\n  'gemma-3': ['strict_alternation'],\n  'gemma-4': ['strict_alternation', 'stale_thinking_advisory'],\n  'gpt-oss': ['harmony_commentary_channel'],\n  'codex-responses': ['payload_field_preservation:encrypted_content'],\n  'cohere-command-r': ['openai_shape_baseline'],\n  'phi': ['openai_shape_baseline'],\n  'mai': ['openai_shape_baseline'],\n  'jamba': ['openai_shape_baseline'],\n  'falcon': ['openai_shape_baseline'],\n  'palmyra': ['openai_shape_baseline'],\n  'ernie': ['openai_shape_baseline'],\n  'gpt-4-legacy': ['openai_shape_baseline'],\n  /** UNCONFIRMED baseline guess: verify independently before relying on this in `enforce` mode. */\n  'bytedance-seed': ['openai_shape_baseline'],\n  /** UNCONFIRMED baseline guess: verify independently before relying on this in `enforce` mode. */\n  'muse-spark': ['openai_shape_baseline'],\n  /** UNCONFIRMED baseline guess: verify independently before relying on this in `enforce` mode. */\n  'muse-glimmer': ['openai_shape_baseline'],\n  'granite-3-x': ['role_remap_split_tool_roles'],\n  'granite-4-x': ['role_remap_inline_tool_call'],\n}\n\nconst resolved = new Map<string, OrderingProfile>()\n\n/** Resolves and memoizes a family recipe; Grok is a true no-rule baseline, not an empty recipe. */\nexport const resolveFamilyRecipe = (key: string): OrderingProfile => {\n  if (key === 'grok') return permissive\n  const cached = resolved.get(key)\n  if (cached !== undefined) return cached\n  const recipe = FAMILY_RECIPES[key]\n  if (recipe === undefined) throw new E_UNKNOWN_ORDERING_PROFILE([key])\n  const profile = unionOfRules(recipe.map(resolveOrderingBehavior))\n  if (recipe.includes('function_response_adjacency'))\n    profile.description +=\n      ' Gemini function-response adjacency is enforced directly: a Message may not immediately follow a ToolCall because the ToolCall owns its result.'\n  resolved.set(key, profile)\n  return profile\n}\n\nexport { getOrderingProfile }\n","import { v6 as uuidv6 } from 'uuid'\nimport { validateOptions } from './validation'\nimport { getOrderingProfile } from './profiles'\nimport { isInstanceOf, isError } from '@nhtio/adk/guards'\nimport { Message, Thought, ToolCall } from '@nhtio/adk/common'\nimport { FAMILY_RECIPES, resolveFamilyRecipe } from './profiles/families'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../../lib/utils/encoder_symbols'\nimport { createOrderingRepairError, createOrderingViolationError } from './exceptions'\nimport {\n  buildOrderingTimeline,\n  evaluateOrderingProfile,\n  repairViolations,\n  setDotPath,\n  unionOfRules,\n} from './helpers'\nimport type { NextFn } from '@nhtio/middleware'\nimport type {\n  TurnContext,\n  DispatchContext,\n  TurnPipelineMiddlewareFn,\n  DispatchPipelineMiddlewareFn,\n} from '@nhtio/adk/types'\nimport type {\n  BlockingOrderingViolation,\n  OrderingAdvisoryViolation,\n  OrderingGuardOptions,\n  OrderingGuardResult,\n  OrderingProfile,\n  OrderingRepair,\n  OrderingStashedTimelineEntry,\n  OrderingTimelineEntry,\n} from './types'\n\n/** `ctx.stash` key under which the prior-iteration primitive snapshot is kept for\n *  {@link @nhtio/adk!PreservationRule} statefulness — see the plan's \"Statefulness for\n *  `PreservationRule`\" section. Exported (as `ORDERING_GUARD_SNAPSHOT_STASH_KEY`) so a caller\n *  can pass a custom `options.snapshotStashKey` without guessing the default's exact string. */\nconst SNAPSHOT = '__orderingGuardSnapshot'\n/**\n * Id prefix marking a message this guard synthesised as an alternation filler.\n *\n * @remarks\n * Load-bearing in two places: fillers are excluded from the timeline the guard evaluates (so its\n * own output can never become its next input), and a consumer can recognise and drop them when\n * persisting turn state.\n */\nconst FILLER_PREFIX = '__ordering-guard-filler-'\n/**\n * Body of a synthesised filler turn.\n *\n * @remarks\n * Deliberately anodyne. A filler exists only to satisfy a provider's role-alternation grammar, so\n * its content should be the least assertive thing that still counts as a turn — it must not put\n * words in the model's mouth or in the user's.\n */\nconst FILLER_CONTENT = 'Understood.'\n/**\n * Monotonic source of filler ids, never reset.\n *\n * @remarks\n * Per-dispatch numbering would repeat ids across dispatches, which only stays harmless while\n * `ctx.deleteMessage` is available to reap the previous batch. `deleteMessage` is optional on\n * {@link GuardContext}, so a store that keeps them would end up holding several messages under one\n * id. Counting for the life of the process costs nothing and removes that dependency.\n */\nlet fillerSequence = 0\n/** `ctx.stash` key under which the most recent {@link OrderingGuardResult} (repaired +\n *  unrepaired + advisories) is recorded, so a caller or a later pipeline stage can inspect\n *  exactly what this middleware did on the current iteration without parsing the nack error. */\nconst RESULT = '__orderingGuardLastResult'\n/** `ctx.stash` key under which the post-repair \"effective timeline\" (the in-memory,\n *  already-ordered copy `repairViolations` produced, with any inserted alternation fillers)\n *  is recorded for the current iteration, so repairs can be re-evaluated against it. */\nconst EFFECTIVE_TIMELINE = '__orderingGuardEffectiveTimeline'\n\ntype GuardContext = Pick<\n  TurnContext,\n  | 'stash'\n  | 'turnMessages'\n  | 'turnThoughts'\n  | 'turnToolCalls'\n  | 'storeMessage'\n  | 'mutateMessage'\n  | 'mutateToolCall'\n  | 'mutateThought'\n> &\n  Partial<Pick<DispatchContext, 'replaceToolCallGroup' | 'storeToolCall' | 'deleteToolCall'>> &\n  // Optional: `toolIdentity` and `schemaIntegrity` read the request's declared tools, and\n  // `deleteMessage` reaps this guard's own spent fillers. Optional so every existing caller — and\n  // every test double — keeps working without them.\n  Partial<Pick<TurnContext, 'tools' | 'deleteMessage'>> &\n  Partial<Pick<DispatchContext, 'nack'>> &\n  Pick<TurnContext, 'abort'>\n\ntype SnapshotEntry = {\n  id: string\n  kind: OrderingTimelineEntry['kind']\n  payload: unknown\n  at: number\n}\n\ntype Snapshot = SnapshotEntry[]\n\nconst idOf = (entry: OrderingTimelineEntry): string => {\n  const id = (entry.value as { id?: unknown }).id\n  return typeof id === 'string' ? id : `${entry.kind}:${entry.seq}`\n}\n\nconst path = (value: unknown, key: string): unknown => {\n  let current = value\n  for (const part of key.split('.')) {\n    if (current === null || typeof current !== 'object') return undefined\n    current = (current as Record<string, unknown>)[part]\n  }\n  return current\n}\n\nconst snapshotOf = (timeline: OrderingTimelineEntry[]): Snapshot =>\n  timeline.map((entry) => ({\n    id: idOf(entry),\n    kind: entry.kind,\n    payload: (entry.value as { payload?: unknown }).payload,\n    at: entry.at,\n  }))\n\nconst same = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b)\n\nconst preservationViolations = (\n  timeline: OrderingTimelineEntry[],\n  prior: Snapshot | undefined,\n  profiles: OrderingProfile[]\n): { blocking: BlockingOrderingViolation[]; advisories: OrderingAdvisoryViolation[] } => {\n  if (!prior) return { blocking: [], advisories: [] }\n  const current = snapshotOf(timeline)\n  const output: BlockingOrderingViolation[] = []\n  const advisories: OrderingAdvisoryViolation[] = []\n  const seen = new Set<string>()\n  for (const profile of profiles) {\n    for (const rule of profile.rules) {\n      if (rule.type !== 'preservation' || seen.has(`${profile.name}:${rule.id}`)) continue\n      // Model identity is not part of DispatchContext/TurnContext, so resetOnModelSwitch is deliberately deferred until the runner exposes it.\n      seen.add(`${profile.name}:${rule.id}`)\n      const before = prior.filter((entry) => entry.kind === rule.kind)\n      const now = current.filter((entry) => entry.kind === rule.kind)\n      let broken: SnapshotEntry[] = []\n      if (rule.invariant === 'count-non-decreasing') {\n        if (now.length < before.length)\n          broken = before.filter((entry) => !now.some((item) => item.id === entry.id))\n      } else if (rule.invariant === 'payload-field-stable') {\n        broken = before.filter((entry) => {\n          const found = now.find((item) => item.id === entry.id)\n          return (\n            found === undefined ||\n            !same(\n              path(entry.payload, rule.payloadField ?? ''),\n              path(found.payload, rule.payloadField ?? '')\n            )\n          )\n        })\n      } else {\n        const latestUser = timeline\n          .map((entry, index) => ({ entry, index }))\n          .filter(({ entry }) => entry.kind === 'message' && entry.role === 'user')\n          .at(-1)\n        const boundary = latestUser ? timeline[latestUser.index].at : -Infinity\n        const retained = before.filter((entry) => entry.at >= boundary)\n        broken = retained.filter((entry) => {\n          const found = now.find((item) => item.id === entry.id)\n          return found === undefined || !same(found.payload, entry.payload)\n        })\n      }\n      if (broken.length > 0) {\n        const detail = `Preservation invariant ${rule.invariant} was violated for ${rule.kind}.`\n        const shared = {\n          ruleId: rule.id,\n          ruleType: 'preservation' as const,\n          profileName: profile.name,\n          primitiveIds: broken.map((entry) => entry.id),\n          detail,\n        }\n        // Honour the rule's own severity, defaulting to ADVISORY like every other rule type. This\n        // was hardcoded `blocking`, which meant a preservation profile gated dispatch regardless of\n        // what the recipe asked for. See OrderRule.severity for why advisory is the default.\n        if (rule.severity === 'blocking') output.push({ ...shared, severity: 'blocking' })\n        else advisories.push({ ...shared, severity: 'advisory' })\n      }\n    }\n  }\n  return { blocking: output, advisories }\n}\n\nconst resolveProfiles = (options: OrderingGuardOptions): OrderingProfile[] => {\n  const profiles = options.profiles.map((profile) => {\n    if (typeof profile !== 'string') return profile\n    if (profile === 'grok' || Object.prototype.hasOwnProperty.call(FAMILY_RECIPES, profile))\n      return resolveFamilyRecipe(profile)\n    return getOrderingProfile(profile)\n  })\n  if (options.mode === 'first-match') return profiles.slice(0, 1)\n  if (options.mode === 'union-of-rules' || options.mode === undefined)\n    return [unionOfRules(profiles)]\n  return profiles\n}\n\nconst logRepair = (repair: OrderingRepair): void => {\n  // Middleware contexts have no helpers.log channel; console.warn preserves the repository's warn-level intent until observability injection exists.\n  console.warn({\n    kind: 'ordering-guard-repair',\n    message: repair.detail,\n    payload: repair,\n  })\n}\n\nconst enforceViolation = (\n  ctx: GuardContext,\n  options: OrderingGuardOptions,\n  violations: BlockingOrderingViolation[],\n  cause?: unknown\n): void => {\n  const error = createOrderingViolationError(violations.length, violations[0].detail, violations)\n  if (cause !== undefined) (error as Error & { cause?: unknown }).cause = cause\n  if (options.onViolation === 'throw') throw error\n  if (ctx.nack) ctx.nack(error)\n  else ctx.abort(error)\n}\n\nconst applyRepairs = async (\n  ctx: GuardContext,\n  repairs: OrderingRepair[],\n  timeline: OrderingTimelineEntry[],\n  profiles: OrderingProfile[]\n): Promise<{\n  timeline: OrderingTimelineEntry[]\n  placement: Map<string, string>\n  completed: OrderingRepair[]\n  failures: { repair: OrderingRepair; error: Error; deletedIds: string[] }[]\n}> => {\n  const synthetic: OrderingTimelineEntry[] = []\n  const syntheticPlacement = new Map<string, string>()\n  const effective = timeline.map((entry) => ({ ...entry }))\n  const completed: OrderingRepair[] = []\n  const failures: { repair: OrderingRepair; error: Error; deletedIds: string[] }[] = []\n  for (const repair of repairs) {\n    try {\n      if (repair.strategy === 'fill-required-metadata') {\n        const rule = profiles\n          .find((p) => p.name === repair.violation.profileName)\n          ?.rules.find((r) => r.id === repair.violation.ruleId)\n        const entry = effective.find((e) => idOf(e) === repair.violation.primitiveIds[0])\n        if (rule?.type !== 'requiredMetadata' || rule.fallbackPayloadValue === undefined || !entry)\n          continue\n        if (entry.kind === 'message') {\n          // Message has no payload field; this repair cannot materialize on messages.\n          continue\n        }\n        const snapshot = {\n          ...((entry.value as ToolCall | Thought)[ENCODE_METHOD]() as Record<string, unknown>),\n        }\n        const payload =\n          snapshot.payload && typeof snapshot.payload === 'object'\n            ? { ...(snapshot.payload as Record<string, unknown>) }\n            : {}\n        setDotPath(payload, rule.requiredPayloadKey, rule.fallbackPayloadValue)\n        snapshot.payload = payload\n        if (\n          snapshot.replayCompatibility === undefined &&\n          rule.fallbackReplayCompatibility !== undefined\n        )\n          snapshot.replayCompatibility = rule.fallbackReplayCompatibility\n        const replacement =\n          entry.kind === 'toolCall'\n            ? ToolCall[DECODE_METHOD](snapshot as never)\n            : Thought[DECODE_METHOD](snapshot as never)\n        if (entry.kind === 'toolCall') await ctx.mutateToolCall(replacement as ToolCall)\n        else await ctx.mutateThought(replacement as Thought)\n        effective[effective.indexOf(entry)] = { ...entry, value: replacement }\n        completed.push(repair)\n        continue\n      }\n      if (repair.strategy === 'renumber-colliding-ids') {\n        // A collision violation intentionally repeats the shared id for every member. Resolve the\n        // group by scanning timeline entries once, rather than calling find once per id: find would\n        // return the first colliding entry for every occurrence and silently drop its siblings.\n        const group = timeline\n          .filter((entry) => repair.violation.primitiveIds.includes(idOf(entry)))\n          .sort((a, b) => a.seq - b.seq)\n        if (\n          group.length !== repair.violation.primitiveIds.length ||\n          group.some((e) => e.kind !== 'toolCall')\n        )\n          continue\n        const rule = profiles\n          .flatMap((profile) => profile.rules)\n          .find((candidate) => candidate.id === repair.violation.ruleId)\n        const rename = rule?.type === 'identifierUniqueness' ? rule.renameStrategy : undefined\n        // The member index is what a deterministic strategy varies on: every member of the group\n        // shares one id, so `previousId` alone cannot tell them apart.\n        const replacementIds = group.map((entry, index) => rename?.(idOf(entry), index) ?? uuidv6())\n        // Uniqueness has to hold against the WHOLE timeline, not just within the group: a strategy\n        // that returns an id belonging to an unrelated call would re-point that call's results.\n        const occupiedIds = new Set(\n          effective\n            .filter((entry) => !repair.violation.primitiveIds.includes(idOf(entry)))\n            .map(idOf)\n        )\n        if (\n          replacementIds.some((id) => typeof id !== 'string') ||\n          new Set(replacementIds).size !== replacementIds.length ||\n          replacementIds.some((id) => occupiedIds.has(id))\n        )\n          throw new Error('Identifier rename strategy returned colliding ids')\n        const replacements = group.map((entry, index) => {\n          const raw = {\n            ...(entry.value[ENCODE_METHOD]() as Record<string, unknown>),\n            id: replacementIds[index],\n          }\n          return ToolCall[DECODE_METHOD](raw as never)\n        })\n        const ids = group.map((entry) => idOf(entry))\n        if (!ctx.replaceToolCallGroup || !ctx.storeToolCall || !ctx.deleteToolCall) {\n          const error = createOrderingRepairError(\n            'Tool-call group replacement is unavailable on this context',\n            new Error('Tool-call group replacement is unavailable on this context'),\n            ids,\n            []\n          )\n          failures.push({ repair, error, deletedIds: [] })\n          continue\n        }\n        await ctx.replaceToolCallGroup(ids, replacements)\n        for (const [i, element] of group.entries()) {\n          const index = effective.findIndex((entry) => entry.seq === element.seq)\n          if (index >= 0) effective[index] = { ...effective[index], value: replacements[i] }\n        }\n        completed.push(repair)\n        continue\n      }\n      // `reorder-adjacent` (adjacency) and `reorder` (order) differ in how helpers.ts CHOOSES the\n      // pair, not in how the move is applied: both name a target to place before a blocker, and both\n      // populate the same typed fields. One materialiser serves both.\n      if (repair.strategy === 'reorder' || repair.strategy === 'reorder-adjacent') {\n        // Typed fields, not a prose-parsing regex against `detail` — `detail` is a human-readable\n        // description that can legitimately be reworded in helpers.ts without this consumer noticing,\n        // and a silently-broken parse here would let a violation continue to report as \"repaired\"\n        // while never actually reaching the live turn state.\n        const targetId = repair.targetId\n        const blockerId = repair.blockerId\n        const targetEntry = targetId ? effective.find((e) => idOf(e) === targetId) : undefined\n        const blockerEntry = blockerId ? effective.find((e) => idOf(e) === blockerId) : undefined\n        if (!targetEntry || !blockerEntry) continue\n        // Timestamps, not array position, are what every LLM adapter's own history assembly sorts\n        // by — moving `targetEntry` in this in-memory copy alone never reaches the wire. Nudge its\n        // createdAt to sort at or before `blockerEntry`'s so the real turn state (not just this\n        // guard's own bookkeeping) reflects the repaired order on the next timeline build.\n        //\n        // Never goes negative: some parts of this codebase (e.g. the context/compact summarizer) use\n        // epoch-zero as a documented \"sort before every real turn\" sentinel — shifting a repaired\n        // primitive to a NEGATIVE timestamp would sort it before that sentinel, inverting its\n        // meaning, and a negative value can also throw inside `new Date(at).toISOString()`. When the\n        // blocker is already at epoch zero, `at` ties rather than strictly precedes — this alone does\n        // NOT guarantee the fix, so it is deliberately NOT reported as repaired here; the mandatory\n        // post-repair re-evaluation (in runGuard, below) is what actually decides whether a tie\n        // still resolves the violation (a tie can still resolve it, since the timeline's own tie-break\n        // on identical timestamps is the target's position within its Set, and #replaceById-style\n        // repairs preserve that position rather than moving the primitive to the end) — this comment\n        // exists so a future reader doesn't mistake the clamp itself for the correctness guarantee.\n        const at = Math.max(0, blockerEntry.at - 1)\n        const snapshot = {\n          ...(targetEntry.value[ENCODE_METHOD]() as Record<string, unknown>),\n          createdAt: new Date(at).toISOString(),\n        }\n        const replacement =\n          targetEntry.kind === 'toolCall'\n            ? ToolCall[DECODE_METHOD](snapshot as never)\n            : targetEntry.kind === 'thought'\n              ? Thought[DECODE_METHOD](snapshot as never)\n              : Message[DECODE_METHOD](snapshot as never)\n        if (targetEntry.kind === 'toolCall') await ctx.mutateToolCall(replacement as ToolCall)\n        else if (targetEntry.kind === 'thought') await ctx.mutateThought(replacement as Thought)\n        else await ctx.mutateMessage(replacement as Message)\n        const index = effective.indexOf(targetEntry)\n        effective[index] = { ...targetEntry, at, value: replacement }\n        completed.push(repair)\n        continue\n      }\n      const [firstId, secondId] = repair.violation.primitiveIds\n      const first = timeline.find((entry) => idOf(entry) === firstId)\n      const second = timeline.find((entry) => idOf(entry) === secondId)\n      if (!first || !second) continue\n      const role = first.role === 'user' ? 'assistant' : 'user'\n      const at = (first.at + second.at) / 2\n      // A CONTENT-FREE id. It used to embed both neighbour ids, which is precisely why they nested:\n      // a filler placed between two fillers inherited both of their already-compound ids. A counter\n      // keeps it bounded and readable, and uniqueness now comes from position rather than lineage.\n      const id = `${FILLER_PREFIX}${fillerSequence++}`\n      const date = new Date(at)\n      const message = new Message({\n        id,\n        role,\n        // Neutral prose, NOT the id. The content used to be the id itself, so a\n        // `__ordering-guard-filler-…` string was sent to the model as a genuine conversational turn —\n        // a synthetic token sequence no vendor has ever seen, inserted to satisfy a role-alternation\n        // check. This says the minimum a turn can say while still being a turn.\n        content: FILLER_CONTENT,\n        createdAt: date,\n        updatedAt: date,\n      })\n      await ctx.storeMessage(message)\n      synthetic.push({\n        kind: 'message',\n        at,\n        seq: first.seq + 0.5,\n        role,\n        value: message,\n      })\n      syntheticPlacement.set(id, firstId)\n      completed.push(repair)\n    } catch (cause) {\n      const original = isError(cause) ? cause : new Error(String(cause))\n      // The context-owned degraded group operation may expose completed deletes on its error. The\n      // dispatch-context contract currently has no typed progress channel, so accept the established\n      // non-invasive error metadata until that contract is extended by its owner.\n      const deletedIds = Array.isArray((original as Error & { deletedIds?: unknown }).deletedIds)\n        ? [...(original as Error & { deletedIds: string[] }).deletedIds]\n        : []\n      const error = createOrderingRepairError(\n        original.message,\n        original,\n        [...repair.violation.primitiveIds],\n        deletedIds\n      )\n      failures.push({ repair, error, deletedIds })\n    }\n  }\n  return {\n    timeline: [...effective, ...synthetic],\n    placement: syntheticPlacement,\n    completed,\n    failures,\n  }\n}\n\nconst runGuard = async (\n  ctx: GuardContext,\n  options: OrderingGuardOptions\n): Promise<{\n  blocked: BlockingOrderingViolation[]\n  result: OrderingGuardResult\n  repairCause?: unknown\n}> => {\n  const profiles = resolveProfiles(options)\n  // Reap the previous dispatch's fillers before doing anything else.\n  //\n  // A filler is scaffolding for ONE dispatch: it exists to satisfy a provider's role-alternation\n  // grammar for the request about to be sent, and has no meaning in the persisted transcript. Left\n  // behind it accumulates without bound — issue #15 defect 2 — so each dispatch removes what the\n  // last one built and re-derives from the real turn state. Excluding them from the timeline (just\n  // below) keeps the guard correct even where `deleteMessage` is unavailable; this keeps the STORE\n  // clean too.\n  if (ctx.deleteMessage !== undefined) {\n    for (const message of ctx.turnMessages) {\n      if (message.id.startsWith(FILLER_PREFIX)) await ctx.deleteMessage(message.id)\n    }\n  }\n\n  // Exclude this guard's OWN fillers from the timeline it evaluates.\n  //\n  // Issue #15 defect 2: a filler was materialised via `ctx.storeMessage` and never removed, so on\n  // the next dispatch it was itself an input to alternation checking — the guard generated fillers\n  // BETWEEN its own fillers, with ids nesting exponentially. Measured before this fix: 2 -> 5 -> 9\n  // fillers over three iterations, ids reaching 139 characters, 5 of them duplicates, and\n  // `repaired` AND `unrepaired` both non-empty for the same dispatch. A repair function whose\n  // output is its own next input has no fixed point; excluding them gives it one.\n  const timeline = buildOrderingTimeline(\n    ctx.turnMessages,\n    ctx.turnThoughts,\n    ctx.turnToolCalls\n  ).filter((entry) => !idOf(entry).startsWith(FILLER_PREFIX))\n  // Supply the request's declared tools so `toolIdentity` and `schemaIntegrity` can run. Both\n  // catch SILENT failures — a tool result naming an undeclared tool, and a schema whose `required`\n  // names a key its `properties` omit — that providers answer with a normal 200 and no error.\n  const declaredTools = (\n    ctx as { tools?: { all?: () => ReadonlyArray<{ name: string; describe?: () => unknown }> } }\n  ).tools\n    ?.all?.()\n    ?.map((tool) => {\n      const described = tool.describe?.() as { name?: string; inputSchema?: unknown } | undefined\n      return {\n        name: described?.name ?? tool.name,\n        inputSchema: described?.inputSchema,\n      }\n    })\n  const evaluationContext = declaredTools === undefined ? undefined : { tools: declaredTools }\n  const surface: 'dispatch' | 'turn' = ctx.nack !== undefined ? 'dispatch' : 'turn'\n  const applicableProfiles = profiles.map((profile) => ({\n    ...profile,\n    rules: profile.rules.filter((rule) => {\n      const ruleSurface = (rule as { surface?: 'dispatch' | 'turn' | 'both' }).surface\n      return ruleSurface === undefined || ruleSurface === 'both' || ruleSurface === surface\n    }),\n  }))\n  const evaluations = applicableProfiles.map((profile) =>\n    evaluateOrderingProfile(timeline, profile, evaluationContext)\n  )\n  const blocked = evaluations.flatMap((evaluation) => evaluation.blocking)\n  const advisories = evaluations\n    .flatMap((evaluation) => evaluation.advisories)\n    .filter((violation) => !options.disableAdvisoryRuleIds?.includes(violation.ruleId))\n  const prior = ctx.stash.get<Snapshot | undefined>(options.snapshotStashKey ?? SNAPSHOT)\n  const preservation = preservationViolations(timeline, prior, applicableProfiles)\n  const allBlocked = [...blocked, ...preservation.blocking]\n  // Preservation advisories join the evaluator's own, and are subject to the same opt-out.\n  const allAdvisories = [\n    ...advisories,\n    ...preservation.advisories.filter(\n      (violation) => !options.disableAdvisoryRuleIds?.includes(violation.ruleId)\n    ),\n  ]\n  // The snapshot is replaced even on rejection so retries compare against the state just observed.\n  ctx.stash.set(options.snapshotStashKey ?? SNAPSHOT, snapshotOf(timeline))\n  if (options.action !== 'mutate')\n    return {\n      blocked: allBlocked,\n      result: {\n        repaired: [],\n        unrepaired: allBlocked,\n        advisories: allAdvisories,\n        repairFailures: [],\n      },\n    }\n  const repaired = repairViolations(\n    timeline,\n    allBlocked,\n    options.allowMetadataFallbackRepair === true ? profiles : undefined,\n    // Rules that authorize their own fallback are repairable WITHOUT the global flag. Narrowed to\n    // just those rules, so enabling one vendor's documented sentinel never widens the surface to\n    // sibling rules in the same profile.\n    applicableProfiles\n      .map((profile) => ({\n        ...profile,\n        rules: profile.rules.filter(\n          (rule) => rule.type === 'requiredMetadata' && rule.fallbackRepairAuthorized === true\n        ),\n      }))\n      .filter((profile) => profile.rules.length > 0)\n  )\n  const applied = await applyRepairs(ctx, repaired.repaired, timeline, applicableProfiles)\n  const effectiveTimeline = [...repaired.timeline]\n  for (const entry of applied.timeline) {\n    const index = effectiveTimeline.findIndex((candidate) => candidate.seq === entry.seq)\n    if (index >= 0) effectiveTimeline[index] = entry\n  }\n  const synthetic = {\n    timeline: applied.timeline.filter((entry) => idOf(entry).startsWith(FILLER_PREFIX)),\n    placement: applied.placement,\n  }\n  for (const entry of synthetic.timeline) {\n    const firstId = synthetic.placement.get(idOf(entry))\n    const firstIndex = effectiveTimeline.findIndex((candidate) => idOf(candidate) === firstId)\n    effectiveTimeline.splice(firstIndex < 0 ? effectiveTimeline.length : firstIndex + 1, 0, entry)\n  }\n  // `ctx.stash` (a Registry) klona-clones its ENTIRE store on every `.get()`, including for\n  // unrelated keys — and klona's generic-object strategy does `new x.constructor()` before\n  // copying properties. Message/Thought/ToolCall all throw on zero-arg construction (schema\n  // validation requires a raw payload), so stashing `effectiveTimeline` with its live `.value`\n  // instances verbatim poisons every subsequent `.get()` call for the rest of the dispatch. Its\n  // own `[ENCODE_METHOD]()` snapshot doesn't fix this either — it still nests other live class\n  // instances (`Identity`, Luxon `DateTime`) that klona chokes on the same way one level down.\n  // Every consumer of the stashed timeline (`helpers.ts`, this file's own repair/apply paths,\n  // and every profile spec that reads this stash key back out) only ever reads `.value.id`,\n  // `.value.payload`, and `.value.replayCompatibility` — all plain values already — so project\n  // just those onto a bare object instead of round-tripping through the full encoder snapshot.\n  // A `.value` that isn't a real primitive instance (already-plain test doubles) is left as-is;\n  // klona's crash is specific to non-plain-object constructors, so a plain object is already\n  // stash-safe. `payload` itself is vendor-opaque (`unknown`) and can independently nest a\n  // clone-hostile class instance (a caller-supplied `Identity`, a `DateTime`, anything with a\n  // non-`Object` constructor) — every documented `payload` shape is meant to round-trip to a\n  // wire protocol, i.e. JSON-serializable, so a JSON round-trip both proves that contract and\n  // guarantees klona never walks into anything but plain objects/arrays/primitives.\n  const toPlainJson = (value: unknown): unknown => {\n    if (value === undefined) return undefined\n    try {\n      return JSON.parse(JSON.stringify(value)) as unknown\n    } catch {\n      return null\n    }\n  }\n  const stashableTimeline: OrderingStashedTimelineEntry[] = effectiveTimeline.map((entry) => {\n    const isPrimitiveInstance =\n      isInstanceOf(entry.value, 'Message', Message) ||\n      isInstanceOf(entry.value, 'Thought', Thought) ||\n      isInstanceOf(entry.value, 'ToolCall', ToolCall)\n    if (!isPrimitiveInstance) {\n      const plain = entry.value as { payload?: unknown }\n      return {\n        ...entry,\n        value: {\n          ...(entry.value as OrderingStashedTimelineEntry['value']),\n          payload: toPlainJson(plain.payload),\n        },\n      }\n    }\n    const raw = entry.value as { id?: unknown; payload?: unknown; replayCompatibility?: unknown }\n    return {\n      ...entry,\n      value: {\n        id: raw.id,\n        payload: toPlainJson(raw.payload),\n        replayCompatibility: raw.replayCompatibility,\n      },\n    }\n  })\n  ctx.stash.set(EFFECTIVE_TIMELINE, stashableTimeline)\n  const postRepairBlocking = applicableProfiles.flatMap(\n    (profile) => evaluateOrderingProfile(effectiveTimeline, profile, evaluationContext).blocking\n  )\n  const unrepaired = [...repaired.unrepaired]\n  const known = new Set(\n    unrepaired.map((violation) => `${violation.ruleId}:${violation.primitiveIds.join(',')}`)\n  )\n  for (const violation of postRepairBlocking) {\n    const key = `${violation.ruleId}:${violation.primitiveIds.join(',')}`\n    if (!known.has(key)) {\n      known.add(key)\n      unrepaired.push(violation)\n    }\n  }\n  const repairFailures = applied.failures.map(({ repair, error, deletedIds }) => ({\n    ruleId: repair.violation.ruleId,\n    primitiveIds: [...repair.violation.primitiveIds],\n    deletedIds: [...deletedIds],\n    message: error.message,\n  }))\n  for (const failure of applied.failures) {\n    const key = `${failure.repair.violation.ruleId}:${failure.repair.violation.primitiveIds.join(',')}`\n    if (!known.has(key)) {\n      known.add(key)\n      unrepaired.push(failure.repair.violation)\n    }\n  }\n  const result: OrderingGuardResult = {\n    repaired: applied.completed,\n    unrepaired,\n    advisories: allAdvisories,\n    repairFailures,\n  }\n  ctx.stash.set(RESULT, result)\n  if (options.onRepair !== 'silent') applied.completed.forEach(logRepair)\n  return { blocked: unrepaired, result, repairCause: applied.failures[0]?.error }\n}\n\nconst makeMiddleware = (\n  options: OrderingGuardOptions\n): DispatchPipelineMiddlewareFn | TurnPipelineMiddlewareFn => {\n  const checked = validateOptions(options)\n  return (async (ctx: DispatchContext | TurnContext, next: NextFn) => {\n    const { blocked, result, repairCause } = await runGuard(ctx as GuardContext, checked)\n    if (checked.action === 'enforce') ctx.stash.set(RESULT, result)\n    if (blocked.length > 0) {\n      enforceViolation(ctx as GuardContext, checked, blocked, repairCause)\n      return\n    }\n    await next()\n  }) as DispatchPipelineMiddlewareFn | TurnPipelineMiddlewareFn\n}\n\n/**\n * Builds a {@link @nhtio/adk!DispatchPipelineMiddlewareFn} that validates (and, in `'mutate'`\n * mode, best-effort repairs) turn-state primitive ordering against `options.profiles` before\n * every executor call.\n *\n * @remarks\n * Runs on every `dispatchInputPipeline` iteration, since that is the point where a caught\n * ordering bug is cheapest to fix — before the wire payload is ever built. See the plan's\n * \"Middleware — `dispatchInputPipeline`/`turnInputPipeline` integration\" section for why this\n * insertion point was chosen over a one-shot turn-level check alone.\n *\n * @param options - Validated via {@link validateOptions} at call time; throws\n * `E_INVALID_ORDERING_GUARD_OPTIONS` synchronously on malformed input.\n * @returns A middleware function following the `(ctx, next) => void | Promise<void>` idiom —\n * nacks via `ctx.nack(error)` (or throws, per `options.onViolation`) without calling `next()`\n * on an unrepaired blocking violation.\n */\nexport const orderingGuardDispatchMiddleware = (\n  options: OrderingGuardOptions\n): DispatchPipelineMiddlewareFn => makeMiddleware(options) as DispatchPipelineMiddlewareFn\n\n/**\n * Builds a {@link @nhtio/adk!TurnPipelineMiddlewareFn} running the same ordering-guard core as\n * {@link orderingGuardDispatchMiddleware}, once per turn before the first executor call.\n *\n * @remarks\n * `TurnContext` has no `nack()` — only `abort()` — so the default `onViolation: 'nack'`\n * behavior maps to `ctx.abort(error)` here rather than a dispatch-style nack; `onViolation:\n * 'throw'` still throws in both middleware. This asymmetry is a real, documented difference\n * between the two contexts, not an inconsistency.\n *\n * @param options - Same shape and validation as {@link orderingGuardDispatchMiddleware}.\n * @returns A turn-pipeline middleware function with the same enforce/mutate semantics.\n */\nexport const orderingGuardTurnMiddleware = (\n  options: OrderingGuardOptions\n): TurnPipelineMiddlewareFn => makeMiddleware(options) as TurnPipelineMiddlewareFn\n\nexport {\n  SNAPSHOT as ORDERING_GUARD_SNAPSHOT_STASH_KEY,\n  RESULT as ORDERING_GUARD_RESULT_STASH_KEY,\n  EFFECTIVE_TIMELINE as ORDERING_GUARD_EFFECTIVE_TIMELINE_STASH_KEY,\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAa,aAA8B;CACzC,MAAM;CACN,aACE;CACF,YAAY;CACZ,OAAO,CAAC;AACV;;;ACKA,IAAa,eAAgC;CAC3C,MAAM;CACN,aACE;CAEF,OAAO,CACL;EACE,MAAM;EACN,IAAI;CACN,CACF;AACF;;;;;;;ACTA,IAAa,gBACX,eAAwB,OACxB,OAA6B,iBACR;CACrB,MAAM,eAAe,4BAA4B;CACjD,aACE,SAAS,eAAe,cAAc,KAAK,KAAK;CAElD,OAAO,CACL;EACE,MAAM;EACN,IAAI,eAAe,4BAA4B;EAC/C;EACA;CACF,CACF;AACF;;;ACpBA,IAAa,kBAAmC;CAC9C,MAAM;CACN,aACE;CAEF,OAAO,CACL;EACE,MAAM;EACN,IAAI;CACN,CACF;AACF;;;;;;;ACRA,IAAa,oBACX,YAAoB,IACpB,iBAAyB,qBACJ;CACrB,MAAM;CACN,aACE,gCAAgC,UAAU,wBAAwB,eAAe;CAEnF,OAAO,CACL;EACE,MAAM;EACN,IAAI;EACJ,MAAM;EACN;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