diff --git a/AgentCore.sln b/AgentCore.sln index 9beaf91c..4d2e451e 100644 --- a/AgentCore.sln +++ b/AgentCore.sln @@ -33,8 +33,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentCore.TestSupport", "te EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentCore.AspNetCore", "src\AgentCore.AspNetCore\AgentCore.AspNetCore.csproj", "{DB5D8634-2691-4048-A6F7-FFA9F6016FE2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentCore.Application.Unicode.Tests", "tests\AgentCore.Application.Unicode.Tests\AgentCore.Application.Unicode.Tests.csproj", "{5586509D-101A-4F39-8161-15ED573E7EC9}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -189,18 +187,6 @@ Global {DB5D8634-2691-4048-A6F7-FFA9F6016FE2}.Release|x64.Build.0 = Release|Any CPU {DB5D8634-2691-4048-A6F7-FFA9F6016FE2}.Release|x86.ActiveCfg = Release|Any CPU {DB5D8634-2691-4048-A6F7-FFA9F6016FE2}.Release|x86.Build.0 = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|x64.ActiveCfg = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|x64.Build.0 = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|x86.ActiveCfg = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Debug|x86.Build.0 = Debug|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|Any CPU.Build.0 = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|x64.ActiveCfg = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|x64.Build.0 = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|x86.ActiveCfg = Release|Any CPU - {5586509D-101A-4F39-8161-15ED573E7EC9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -218,6 +204,5 @@ Global {DE0D9F78-60D2-4A95-B71C-E01480048CA0} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {E70C6362-5778-4498-9BA9-7FED110762AE} = {0AB3BF05-4346-4AA6-1389-037BE0695223} {DB5D8634-2691-4048-A6F7-FFA9F6016FE2} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} - {5586509D-101A-4F39-8161-15ED573E7EC9} = {0AB3BF05-4346-4AA6-1389-037BE0695223} EndGlobalSection EndGlobal diff --git a/demo/AgentCore.Demo/config/example.yaml b/demo/AgentCore.Demo/config/example.yaml index 50d8b513..a97804b0 100644 --- a/demo/AgentCore.Demo/config/example.yaml +++ b/demo/AgentCore.Demo/config/example.yaml @@ -406,6 +406,34 @@ providers: # condition on that facet at all, and every value of it would be in reach before the caller has # said anything. + filterable: + - key: applies_to + description: "The machine the question is about, as one tag, such as ct900 or f63-2019." + # The facets a mode: tool agent may narrow its own search by. Each entry becomes one choice in + # the search tool's filters argument, and the description is the only thing the model reads + # before it picks a value — so write it for the model, not for the deployer. Adding a facet + # here is the whole job: no host writes code for one. + # + # A filter can only ever narrow. A facet the host opened or the extractor filled is left + # exactly as it was, because those two are who is asking and what they said; only a facet + # holding the wildcard, or one the scope does not carry at all, is open for the model to write. + # So this is safe to name a reach facet in, and still never a way out of an isolation facet. + # + # A filter that clears no card at all is dropped and the search runs once more without it. The + # model's filter is its guess at the subject, and a wrong guess must not become "nothing is + # documented". That costs one extra search only on a filtered search that found nothing. + # + # A key whose name matches a vocabulary: slot is matched through that slot's fold, so a mention + # written "the 2023 LCR" reaches the stored lcr-2023 rather than filtering on a string no card + # carries, and a value the collection has never held is dropped rather than searched for. A key + # with no such slot is matched exactly as the model wrote it. + # + # Prefer a key that HAS such a slot. Without one nothing checks what the model invents, so it + # filters on values no card carries and the retry pays for a second search most times out. + # A facet worth filtering by is usually worth a vocabulary: slot of its own. + # + # Prefetch agents ignore this block: they advertise no function, so there is no argument to fill. + links: field: see_also lookup: uuid5 # uuid5 | direct | filter diff --git a/src/AgentCore.Application/AgentCore.Application.csproj b/src/AgentCore.Application/AgentCore.Application.csproj index 931cf630..0b947998 100644 --- a/src/AgentCore.Application/AgentCore.Application.csproj +++ b/src/AgentCore.Application/AgentCore.Application.csproj @@ -38,7 +38,6 @@ - diff --git a/src/AgentCore.Application/Calls/CallClarificationState.cs b/src/AgentCore.Application/Calls/CallClarificationState.cs index c8191249..54ff3588 100644 --- a/src/AgentCore.Application/Calls/CallClarificationState.cs +++ b/src/AgentCore.Application/Calls/CallClarificationState.cs @@ -1,6 +1,6 @@ namespace AgentCore.Application.Calls; -/// What one slot's ambiguity channels have already spent of their ask budget (§7, §8). +/// What one slot's knowledge probe has already spent of its ask budget (§8). /// /// Carried on so a caller who drops and reconnects mid-call is not /// asked the same clarification a second maxAsks times. What was last named to the caller is @@ -10,10 +10,4 @@ public sealed record CallClarificationState { /// Gets how many times the knowledge probe has offered this slot (§8, K22). public int ProbeAsks { get; init; } - - /// Gets how many times the clarification instruction has named this slot (§7). - public int NamedAsks { get; init; } - - /// Gets whether §7 step 3's one counter reset has already been spent. - public bool ResetSpent { get; init; } } diff --git a/src/AgentCore.Application/Calls/CallSessionState.cs b/src/AgentCore.Application/Calls/CallSessionState.cs index d557ecb8..274d6a73 100644 --- a/src/AgentCore.Application/Calls/CallSessionState.cs +++ b/src/AgentCore.Application/Calls/CallSessionState.cs @@ -10,7 +10,7 @@ public sealed record CallSessionState private static readonly IReadOnlyDictionary NoSlots = ReadOnlyDictionary.Empty; - /// The slots of a call whose ambiguity channels asked about none. + /// The slots of a call whose knowledge probe asked about none. private static readonly IReadOnlyDictionary NoClarifications = ReadOnlyDictionary.Empty; @@ -36,7 +36,7 @@ public sealed record CallSessionState public IReadOnlyDictionary Slots { get; init; } = NoSlots; /// - /// Gets what each slot's ambiguity channels have spent of their ask budget, by slot name. A slot + /// Gets what each slot's knowledge probe has spent of its ask budget, by slot name. A slot /// nothing has asked about is absent. /// public IReadOnlyDictionary Clarifications { get; init; } = NoClarifications; diff --git a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs index 7b204724..c66b36d6 100644 --- a/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/AgentContextProviderCompiler.cs @@ -18,9 +18,9 @@ internal static class AgentContextProviderCompiler private static readonly SourceLocatorCitationFormatter DefaultCitations = new(); /// - /// Builds the context providers of one agent. and - /// are the document's ambiguity wiring (§7), the same - /// for every agent — built once by the caller rather than re-derived per agent. + /// Builds the context providers of one agent. is the document's + /// ambiguity wiring (§8), the same for every agent — built once by the caller rather than + /// re-derived per agent. /// public static List Build( AgentDefaults? defaults, @@ -28,18 +28,10 @@ public static List Build( AgentCompilationContext context, string pointer, ResolvedClarification clarification, - ClarificationProvider? clarificationProvider) + KnowledgeScopeConfiguration? scope) { List providers = [new TurnContextProvider()]; - // Bound ahead of the knowledge early-return below: channel 1 asks about a scope's fromState - // slots regardless of whether THIS agent composes its own knowledge: block, because the - // clarification is document-level state, not a per-agent search setting. - if (clarificationProvider is not null) - { - providers.Add(clarificationProvider); - } - if (item.Skills.Count > 0) { if (context.Skills is not { } catalog) @@ -92,8 +84,8 @@ public static List Build( + $"{nameof(IKnowledgeRetrievalPort)}, or remove the knowledge: block."); } - // The same document-level wiring channel 1 reads above, carried onto this agent's own - // resolved knowledge so the search side does not have to re-derive it. + // The document-level wiring, carried onto this agent's own resolved knowledge so the search + // side does not have to re-derive it. var knowledge = composed with { Clarification = clarification }; providers.Add(KnowledgeProviderFactory.Create( @@ -101,7 +93,8 @@ public static List Build( knowledge, item.Id, context.Citations ?? DefaultCitations, - context.Loggers)); + context.Loggers, + scope)); return providers; } diff --git a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs index 67b68f93..b73dfe23 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ConfigurationCompiler.cs @@ -196,13 +196,6 @@ private static Dictionary BuildAgents( var clarification = ResolvedClarification.From(configuration); - // Nothing on this provider is per agent: its three fields are the document's own wiring, and - // every other value it reads comes off the turn's ambients. The framework only ever calls - // into it, passing the agent and the session as arguments, so one instance serves them all. - var clarificationProvider = clarification.Ambiguity is { } documentAmbiguity - ? new ClarificationProvider(documentAmbiguity, clarification.FromState, clarification.SlotDescriptions) - : null; - Dictionary tools = new(StringComparer.Ordinal); foreach (var tool in configuration.Tools) { @@ -272,7 +265,12 @@ private static Dictionary BuildAgents( }, ChatHistoryProvider = history, AIContextProviders = AgentContextProviderCompiler.Build( - section.Defaults, item, context, pointer, clarification, clarificationProvider), + section.Defaults, + item, + context, + pointer, + clarification, + configuration.Providers?.Knowledge?.Scope), }); path.RemoveAt(path.Count - 1); diff --git a/src/AgentCore.Application/Configuration/Compilation/ResolvedClarification.cs b/src/AgentCore.Application/Configuration/Compilation/ResolvedClarification.cs index 62993bf9..68e7ceed 100644 --- a/src/AgentCore.Application/Configuration/Compilation/ResolvedClarification.cs +++ b/src/AgentCore.Application/Configuration/Compilation/ResolvedClarification.cs @@ -5,13 +5,12 @@ namespace AgentCore.Application.Configuration.Compilation; /// -/// The document-level ambiguity wiring §7 needs, read once from providers.knowledge and the -/// declared state: slots. +/// The document-level ambiguity wiring the knowledge probe needs (§8), read once from +/// providers.knowledge and the declared state: slots. /// /// /// The same for every agent, so builds it once rather than -/// letting each agent re-derive it, and both channels — the clarification provider and the agent's -/// own search — read the one instance. +/// letting each agent re-derive it. /// public sealed record ResolvedClarification { diff --git a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs index 8d654b64..005d349b 100644 --- a/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/ProvidersConfiguration.cs @@ -59,6 +59,19 @@ public sealed record KnowledgeScopeConfiguration /// Gets the state slots the turn's scope is built from. Each name becomes one facet key. public IReadOnlyList FromState { get; init; } = []; + + /// Gets the facets a tool-mode agent may narrow its own search by. Empty offers none. + public IReadOnlyList Filterable { get; init; } = []; +} + +/// One facet the model may name in the search tool's filters argument. +public sealed record KnowledgeFilterableFacetConfiguration +{ + /// Gets the facet key, which scope.template turns into the payload path. + public required string Key { get; init; } + + /// Gets what this facet means, in the words the model reads before it picks a value. + public required string Description { get; init; } } /// Which facets a card may opt out of, and the value it opts out with. @@ -197,8 +210,7 @@ public sealed record KnowledgeProviderConfiguration /// /// How the knowledge search asks the caller which machine they meant, when the scope narrows to more -/// than one and the search itself came back empty. See section 4 of the ambiguity-and-vocabulary -/// design. +/// than one and the search itself came back empty. See section 4 of the ambiguity design. /// public sealed record KnowledgeAmbiguityConfiguration { @@ -218,8 +230,7 @@ public sealed record KnowledgeAmbiguityConfiguration public int MaxCandidates { get; init; } = DefaultMaxCandidates; /// - /// Gets the cap on each of a slot's two ask counters. 0 means never ask: the vocabulary - /// and the gate still work. + /// Gets the cap on a slot's probe ask counter. 0 means never ask: the gate still works. /// public int MaxAsks { get; init; } = DefaultMaxAsks; diff --git a/src/AgentCore.Application/Configuration/Schema/StateSlotConfiguration.cs b/src/AgentCore.Application/Configuration/Schema/StateSlotConfiguration.cs index f43281ee..c7117ae9 100644 --- a/src/AgentCore.Application/Configuration/Schema/StateSlotConfiguration.cs +++ b/src/AgentCore.Application/Configuration/Schema/StateSlotConfiguration.cs @@ -68,48 +68,4 @@ public sealed record StateSlotConfiguration /// Gets the fixed value of the slot. It is set when the writer is . public JsonNode? Value { get; init; } - - /// - /// Gets the declaration that this slot's domain is read from a provider rather than hand-written - /// as , or when this document names none. - /// - public SlotVocabularyConfiguration? Vocabulary { get; init; } -} - -/// -/// A slot's domain, read from a provider at boot instead of written by hand as enum:. See -/// section 4 of the ambiguity-and-vocabulary design. -/// -public sealed record SlotVocabularyConfiguration -{ - /// The linker name used when the document names none. - public const string DefaultLinker = "exact"; - - /// The refresh interval used when the document sets none, in seconds. Boot only. - public const int DefaultRefreshSeconds = 0; - - /// The read limit used when the document sets none. - public const int DefaultMaxValues = 2000; - - /// Gets the provider the domain is read from. knowledge is the only member. - public required string From { get; init; } - - /// Gets the IStateValueLinker name. Only exact ships. - public string Linker { get; init; } = DefaultLinker; - - /// Gets how often the domain is re-read, in seconds. 0 means boot only. - public int RefreshSeconds { get; init; } = DefaultRefreshSeconds; - - /// - /// Gets the limit passed to the facet read. A read returning exactly this many fails startup: it - /// cannot be told from a truncation. - /// - public int MaxValues { get; init; } = DefaultMaxValues; - - /// - /// Gets whether every id in the collection, and every mention the extractor emits, is already - /// NFC. Lifts the refusal on a runtime that cannot compose Unicode, and carries the obligation - /// that every id and every mention really is already normalised. - /// - public bool AssumeNormalized { get; init; } } diff --git a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json index 508b4bbd..8aecb095 100644 --- a/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json +++ b/src/AgentCore.Application/Configuration/Schema/agentcore-v1.schema.json @@ -198,43 +198,6 @@ }, "value": { "description": "writer: const. The fixed value of the slot." - }, - "vocabulary": { - "type": "object", - "description": "Declares that this slot's domain is read from a provider at boot, rather than hand-written as enum:. Absent by default.", - "additionalProperties": false, - "required": [ - "from" - ], - "properties": { - "from": { - "enum": [ - "knowledge" - ], - "description": "The provider to read the domain from. knowledge is the only member." - }, - "linker": { - "type": "string", - "minLength": 1, - "default": "exact", - "description": "The IStateValueLinker name. Only exact ships." - }, - "refreshSeconds": { - "type": "integer", - "default": 0, - "description": "How often the domain is re-read. 0 means boot only." - }, - "maxValues": { - "type": "integer", - "default": 2000, - "description": "The limit passed to the facet read. A read returning exactly this many fails startup: it cannot be told from a truncation." - }, - "assumeNormalized": { - "type": "boolean", - "default": false, - "description": "Declares that every id in the collection, and every mention the extractor emits, is already NFC. Lifts the refusal on a runtime that cannot compose Unicode." - } - } } }, "allOf": [ @@ -1244,6 +1207,27 @@ "type": "array", "items": { "type": "string", "minLength": 1 }, "description": "The state slots the turn's scope is built from. Each becomes one facet key." + }, + "filterable": { + "type": "array", + "description": "The facets a tool-mode agent may narrow its own search by. Each becomes one choice in the search tool's filters argument. A facet the host or the extractor already answered is never overwritten by one.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["key", "description"], + "properties": { + "key": { + "type": "string", + "minLength": 1, + "description": "The facet key, which scope.template turns into the payload path." + }, + "description": { + "type": "string", + "minLength": 1, + "description": "What this facet means, in the words the model reads before it picks a value." + } + } + } } } }, @@ -1260,7 +1244,7 @@ "maxAsks": { "type": "integer", "default": 2, - "description": "The cap on each of a slot's two ask counters. 0 means never ask: the vocabulary and the gate still work." + "description": "The cap on each of a slot's two ask counters. 0 means never ask: the gate still works." }, "probeDeadlineSeconds": { "type": "integer", diff --git a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs index 6619c657..7e337529 100644 --- a/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs +++ b/src/AgentCore.Application/Configuration/Validation/ConfigurationValidator.cs @@ -75,7 +75,7 @@ public static ConfigurationValidationResult EvaluateStructure(AgentCoreConfigura ReasoningTemperatureCheck.Run(configuration, errors); CheckSlotWriters(configuration, errors); CheckKnowledgeScopeSlots(configuration, errors); - CheckVocabularyAndAmbiguity(configuration, errors, warnings); + CheckAmbiguity(configuration, errors, warnings); CheckGuardRules(configuration, errors); CheckExclusivity(configuration, errors, warnings); CheckReachability(configuration, errors); @@ -135,32 +135,6 @@ public static void ValidateToolReferences(AgentCoreConfiguration configuration, } } - /// - /// Resolves every slot's vocabulary.linker against the names the linker registry actually - /// serves, and throws when one names a linker nothing registered. - /// - /// - /// K12: a two-argument validator, run after the linker registry is built — the registry itself - /// lives in Application and is not reachable from here. A caller runs this after building it, - /// the same way runs after MCP discovery. - /// - /// The bound document. - /// Every linker name the registry serves. Always includes exact. - /// A slot names a linker nothing registered. - public static void ValidateLinkerNames(AgentCoreConfiguration configuration, IReadOnlySet registered) - { - ArgumentNullException.ThrowIfNull(configuration); - ArgumentNullException.ThrowIfNull(registered); - - var errors = new List(); - CheckLinkerReferences(configuration, registered, errors); - - if (errors.Count > 0) - { - throw new ConfigurationLoadException(errors); - } - } - /// /// Resolves every skills: entry against the names the bound skills folder serves, and /// throws when one names a skill nothing serves. @@ -385,30 +359,6 @@ private static void CheckToolReferences(AgentCoreConfiguration configuration, IR } } - // --------------------------------------------------------------------------------------------- - // Check 2, linker names: K12's two-argument validator, run after the linker registry is built. - // --------------------------------------------------------------------------------------------- - /// Resolves every declared vocabulary.linker against what the registry serves. - /// The bound document. - /// Every linker name the registry serves. - /// The list every failure is added to. - private static void CheckLinkerReferences( - AgentCoreConfiguration configuration, IReadOnlySet registered, List errors) - { - foreach (var slot in configuration.State) - { - if (slot.Value.Vocabulary is not { } vocabulary || registered.Contains(vocabulary.Linker)) - { - continue; - } - - errors.Add(Reference( - ConfigurationError.AppendPointer(ConfigurationError.AppendPointer(Pointer.State(slot.Key), "vocabulary"), "linker"), - $"the slot '{slot.Key}' declares vocabulary.linker: '{vocabulary.Linker}', which nothing " - + "registered. Register it with UseStateValueLinkers, or use 'exact'.")); - } - } - /// Resolves every agent's skills: entry against what the bound folder serves. /// The bound document. /// Every skill name the bound folder serves. @@ -552,6 +502,8 @@ private static void CheckKnowledgeScopeSlots( return; } + KnowledgeFilterValidator.Check(scope, errors); + if (scope.Wildcard is { } wildcard) { if (string.IsNullOrWhiteSpace(wildcard.Value)) @@ -657,87 +609,26 @@ private static void CheckKnowledgeScopeSlots( + "scope mid-call.")); } - if (slot.EnumValues is not { Count: > 0 } && slot.Vocabulary is null) + if (slot.EnumValues is not { Count: > 0 }) { errors.Add(Reference( ConfigurationError.AppendPointer(pointer, "enum"), - $"the facet slot '{name}' declares neither enum nor vocabulary. Nothing would then " - + "stop a value the corpus has never been tagged with, which the wildcard turns " - + "into an answer from the wrong bucket rather than an empty result.")); + $"the facet slot '{name}' declares no enum. Nothing would then stop a value the " + + "corpus has never been tagged with, which the wildcard turns into an answer " + + "from the wrong bucket rather than an empty result.")); } } } // --------------------------------------------------------------------------------------------- - // Check 2, vocabulary and ambiguity: section 10 of the ambiguity-and-vocabulary design. + // Check 2, ambiguity: section 10 of the ambiguity design. // --------------------------------------------------------------------------------------------- - /// Refuses a vocabulary: or ambiguity: block that could not do what it declares. - private static void CheckVocabularyAndAmbiguity( + /// Refuses an ambiguity: block that could not do what it declares. + private static void CheckAmbiguity( AgentCoreConfiguration configuration, List errors, List warnings) { var knowledge = configuration.Providers?.Knowledge; - var anyVocabulary = false; - - foreach (var entry in configuration.State) - { - if (entry.Value.Vocabulary is not { } vocabulary) - { - continue; - } - - anyVocabulary = true; - var pointer = Pointer.State(entry.Key); - var vocabularyPointer = ConfigurationError.AppendPointer(pointer, "vocabulary"); - - if (entry.Value.EnumValues is { Count: > 0 }) - { - errors.Add(Reference( - vocabularyPointer, - $"the slot '{entry.Key}' declares both enum and vocabulary. enum is a fixed, " - + "hand-written list; vocabulary reads the domain from a provider at boot. A slot " - + "cannot have both.")); - } - - if (entry.Value.Value is not null) - { - errors.Add(Reference( - ConfigurationError.AppendPointer(pointer, "value"), - $"the slot '{entry.Key}' declares both value and vocabulary. value is writer: " - + "const's fixed value; vocabulary reads a domain the extractor fills at runtime. " - + "A slot cannot have both.")); - } - - CheckRange( - vocabulary.MaxValues, - 2, - int.MaxValue, - ConfigurationError.AppendPointer(vocabularyPointer, "maxValues"), - $"vocabulary.maxValues on the slot '{entry.Key}'", - "A read of fewer than two values could never be told apart from a truncated one.", - errors); - - CheckRange( - vocabulary.RefreshSeconds, - 0, - MaxIntervalSeconds, - ConfigurationError.AppendPointer(vocabularyPointer, "refreshSeconds"), - $"vocabulary.refreshSeconds on the slot '{entry.Key}'", - "0 means boot only. A negative interval matches AgentCoreBoot's own " - + "{ RefreshSeconds: > 0 } guard on nothing, so the slot would silently read once at " - + "boot and never refresh again, and one above the range throws out of the " - + "PeriodicTimer VocabularyRefreshService builds from it.", - errors); - } - - if (anyVocabulary && knowledge?.Ambiguity is null) - { - errors.Add(Reference( - Pointer.Ambiguity, - "a slot declares vocabulary, and providers.knowledge.ambiguity is absent. vocabulary " - + "installs the linker, which can return Ambiguous — an outcome a plain enum gate never " - + "produces — and without ambiguity there is no channel to tell anyone.")); - } if (knowledge?.Ambiguity is not { } ambiguity) { @@ -812,15 +703,6 @@ private static void CheckVocabularyAndAmbiguity( + "facet. That deployment has no droppable facet other than its only one, so the probe " + "is unreachable unless the host sets one too.")); } - - if (configuration.Graph is not null) - { - warnings.Add(Reference( - Pointer.Ambiguity, - "providers.knowledge.ambiguity is declared on a graph: document. The clarification's " - + "turn-context guard only passes on a session whose row carries history, which a " - + "graph run does not, so channel 1 is silent here.")); - } } // --------------------------------------------------------------------------------------------- diff --git a/src/AgentCore.Application/Configuration/Validation/KnowledgeFilterValidator.cs b/src/AgentCore.Application/Configuration/Validation/KnowledgeFilterValidator.cs new file mode 100644 index 00000000..7183ca35 --- /dev/null +++ b/src/AgentCore.Application/Configuration/Validation/KnowledgeFilterValidator.cs @@ -0,0 +1,67 @@ +using AgentCore.Application.Configuration.Parsing; +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Configuration.Validation; + +/// +/// Refuses a scope.filterable block the search tool could not be built from. +/// +internal static class KnowledgeFilterValidator +{ + private const string Pointer = "/providers/knowledge/scope/filterable"; + + /// Checks the block, adding one error per fault. + /// The document's providers.knowledge.scope block, or . + /// Where the faults go. + /// is . + internal static void Check(KnowledgeScopeConfiguration? scope, List errors) + { + ArgumentNullException.ThrowIfNull(errors); + + if (scope?.Filterable is not { Count: > 0 } filterable) + { + return; + } + + if (string.IsNullOrWhiteSpace(scope.Template)) + { + errors.Add(Reference( + Pointer, + "filterable names facets and scope.template is not set, so there is no payload path " + + "to resolve a facet key to. Set the template, or drop filterable.")); + } + + HashSet seen = new(StringComparer.Ordinal); + + for (var index = 0; index < filterable.Count; index++) + { + var facet = filterable[index]; + var pointer = ConfigurationError.AppendPointer(Pointer, index); + + if (string.IsNullOrWhiteSpace(facet.Key)) + { + errors.Add(Reference(pointer, "the facet key is blank, so it names no facet.")); + } + else if (!seen.Add(facet.Key)) + { + errors.Add(Reference( + pointer, + $"the facet key '{facet.Key}' is named twice. One key is one choice in the " + + "search tool's filters argument, and a repeat offers the model the same choice " + + "again.")); + } + + if (string.IsNullOrWhiteSpace(facet.Description)) + { + errors.Add(Reference( + pointer, + $"the facet '{facet.Key}' has no description. The description is the only thing " + + "the model reads before it picks a value, so a facet without one is a key it " + + "can only guess at.")); + } + } + } + + private static ConfigurationError Reference(string pointer, string message) + => new() { Pointer = pointer, Message = message, Check = ConfigurationCheck.ReferenceResolution }; +} diff --git a/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs new file mode 100644 index 00000000..4535de6b --- /dev/null +++ b/src/AgentCore.Application/Knowledge/FacetFilterProvider.cs @@ -0,0 +1,64 @@ +using AgentCore.Application.Configuration.Schema; + +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Knowledge; + +/// +/// Puts a filters argument on whichever search function the inner provider offers. +/// +internal sealed class FacetFilterProvider( + AIContextProvider innerProvider, + IReadOnlyList facets) + : AIContextProvider +{ + private readonly AIContextProvider _inner = innerProvider + ?? throw new ArgumentNullException(nameof(innerProvider)); + + private readonly IReadOnlyList _facets = facets + ?? throw new ArgumentNullException(nameof(facets)); + + /// + public override IReadOnlyList StateKeys => _inner.StateKeys; + + /// + public override object? GetService(Type serviceType, object? serviceKey = null) + { + ArgumentNullException.ThrowIfNull(serviceType); + + return serviceType.IsInstanceOfType(this) && serviceKey is null + ? this + : _inner.GetService(serviceType, serviceKey); + } + + /// + protected override async ValueTask InvokingCoreAsync( + InvokingContext context, CancellationToken cancellationToken) + { + var provided = await _inner.InvokingAsync(context, cancellationToken).ConfigureAwait(false); + + if (provided.Tools is not { } tools) + { + return provided; + } + + List wrapped = []; + + foreach (var tool in tools) + { + wrapped.Add(tool is AIFunction function + ? new FacetFilteredSearch(function, _facets) + : tool); + } + + provided.Tools = wrapped; + + return provided; + } + + /// + protected override ValueTask InvokedCoreAsync( + InvokedContext context, CancellationToken cancellationToken) + => _inner.InvokedAsync(context, cancellationToken); +} diff --git a/src/AgentCore.Application/Knowledge/FacetFilterReader.cs b/src/AgentCore.Application/Knowledge/FacetFilterReader.cs new file mode 100644 index 00000000..2cbd9c1b --- /dev/null +++ b/src/AgentCore.Application/Knowledge/FacetFilterReader.cs @@ -0,0 +1,79 @@ +using System.Text.Json; + +using AgentCore.Application.Configuration.Schema; + +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Knowledge; + +/// +/// Reads the filters argument into the facets one search narrows by. +/// +internal static class FacetFilterReader +{ + /// Reads the argument, keeping only the facets the document declared. + /// What the model called the search tool with. + /// What scope.filterable declared. + /// The facet key to value, as the model wrote it. Empty when the argument named none, or none survived. + /// A required argument is . + internal static IReadOnlyDictionary Read( + AIFunctionArguments arguments, + IReadOnlyList facets) + { + ArgumentNullException.ThrowIfNull(arguments); + ArgumentNullException.ThrowIfNull(facets); + + Dictionary read = new(StringComparer.Ordinal); + + if (!arguments.TryGetValue(FacetFilterSchema.ArgumentName, out var raw) || raw is null) + { + return read; + } + + if (Array(raw) is not { } entries) + { + return read; + } + + foreach (var entry in entries.EnumerateArray()) + { + if (Text(entry, FacetFilterSchema.KeyProperty) is not { Length: > 0 } key + || Text(entry, FacetFilterSchema.ValueProperty) is not { Length: > 0 } value + || !facets.Any(facet => string.Equals(facet.Key, key, StringComparison.Ordinal))) + { + continue; + } + + read[key] = value; + } + + return read; + } + + /// The argument as an array, whatever shape the caller handed it in. + private static JsonElement? Array(object raw) + { + var element = raw as JsonElement? ?? Reserialized(raw); + + return element is { ValueKind: JsonValueKind.Array } array ? array : null; + } + + private static JsonElement? Reserialized(object raw) + { + try + { + return JsonSerializer.SerializeToElement(raw); + } + catch (NotSupportedException) + { + return null; + } + } + + private static string? Text(JsonElement entry, string property) + => entry.ValueKind == JsonValueKind.Object + && entry.TryGetProperty(property, out var value) + && value.ValueKind == JsonValueKind.String + ? value.GetString() + : null; +} diff --git a/src/AgentCore.Application/Knowledge/FacetFilterSchema.cs b/src/AgentCore.Application/Knowledge/FacetFilterSchema.cs new file mode 100644 index 00000000..c57ed600 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/FacetFilterSchema.cs @@ -0,0 +1,96 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +using AgentCore.Application.Configuration.Schema; + +namespace AgentCore.Application.Knowledge; + +/// +/// Grows the framework's one-string search schema by a filters argument. +/// +internal static class FacetFilterSchema +{ + /// The argument the model fills to narrow its own search. + internal const string ArgumentName = "filters"; + + /// The key of one filter entry. + internal const string KeyProperty = "key"; + + /// The value of one filter entry. + internal const string ValueProperty = "value"; + + /// Adds the argument to a schema that does not carry it. + /// The schema of the function being wrapped. + /// What scope.filterable declared, in document order. + /// The extended schema. + /// is . + internal static JsonElement Extend( + JsonElement innerSchema, IReadOnlyList facets) + { + ArgumentNullException.ThrowIfNull(facets); + + if (JsonSerializer.Deserialize(innerSchema) is not JsonObject schema) + { + return innerSchema; + } + + if (schema["properties"] is not JsonObject properties) + { + properties = []; + schema["properties"] = properties; + } + + properties[ArgumentName] = Argument(facets); + + return JsonSerializer.Deserialize(schema); + } + + private static JsonObject Argument(IReadOnlyList facets) + => new() + { + ["type"] = "array", + ["description"] = Wording(facets), + ["items"] = new JsonObject + { + ["type"] = "object", + ["properties"] = new JsonObject + { + [KeyProperty] = new JsonObject + { + ["type"] = "string", + ["enum"] = new JsonArray([.. facets.Select(facet => (JsonNode)facet.Key)]), + }, + [ValueProperty] = new JsonObject + { + ["type"] = "string", + ["description"] = + "The value the cards must carry, as the collection stores it. Write what " + + "the person said and it will be matched against the stored values.", + }, + }, + ["required"] = new JsonArray(KeyProperty, ValueProperty), + }, + }; + + /// + /// The one place a facet's meaning reaches the model. + /// + /// + /// Per key, because JSON Schema hangs no description off an enum member, and the alternative — + /// an anyOf of const branches — is read unevenly across vendors. + /// + private static string Wording(IReadOnlyList facets) + { + StringBuilder wording = new( + "Narrow the search to cards carrying these facet values. Leave it out when the question " + + "names none: a filter that matches nothing returns nothing. The keys are:"); + + foreach (var facet in facets) + { + wording.Append("\n- ").Append(facet.Key).Append(": ").Append(facet.Description); + } + + return wording.ToString(); + } +} diff --git a/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs new file mode 100644 index 00000000..a738efe5 --- /dev/null +++ b/src/AgentCore.Application/Knowledge/FacetFilteredSearch.cs @@ -0,0 +1,74 @@ +using System.Text.Json; + +using AgentCore.Application.Configuration.Schema; + +using Microsoft.Extensions.AI; + +namespace AgentCore.Application.Knowledge; + +/// +/// The framework's search function, with a filters argument in front of it. +/// +internal sealed class FacetFilteredSearch : DelegatingAIFunction +{ + private readonly IReadOnlyList _facets; + + private readonly JsonElement _schema; + + /// Wraps one search function. + /// The function the framework built. + /// What scope.filterable declared, in document order. + /// A required argument is . + internal FacetFilteredSearch( + AIFunction innerFunction, + IReadOnlyList facets) + : base(innerFunction) + { + ArgumentNullException.ThrowIfNull(innerFunction); + ArgumentNullException.ThrowIfNull(facets); + + _facets = facets; + _schema = FacetFilterSchema.Extend(innerFunction.JsonSchema, facets); + } + + /// + public override JsonElement JsonSchema => _schema; + + /// + protected override async ValueTask InvokeCoreAsync( + AIFunctionArguments arguments, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(arguments); + + var named = FacetFilterReader.Read(arguments, _facets); + + using var scope = named.Count > 0 ? ToolFacetScope.Open(named) : null; + + return await base.InvokeCoreAsync(Forwarded(arguments), cancellationToken).ConfigureAwait(false); + } + + /// The arguments without the one this wrapper owns. + private static AIFunctionArguments Forwarded(AIFunctionArguments arguments) + { + if (!arguments.ContainsKey(FacetFilterSchema.ArgumentName)) + { + return arguments; + } + + Dictionary kept = new(StringComparer.Ordinal); + + foreach (var (name, value) in arguments) + { + if (!string.Equals(name, FacetFilterSchema.ArgumentName, StringComparison.Ordinal)) + { + kept[name] = value; + } + } + + return new AIFunctionArguments(kept) + { + Services = arguments.Services, + Context = arguments.Context, + }; + } +} diff --git a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs index 7bac2fe1..c8cbc965 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeAuditRecord.cs @@ -78,12 +78,23 @@ public static KnowledgeAuditRecord For( Agent = Agent, Mode = Mode, QueryLength = Query.Length, - Scope = Scope, - ScopeOrigins = ScopeOrigins, + Scope = ScopeText(), LatencyMs = LatencyMs, Cards = Cards, }; + /// + /// Writes the scope as code=* (Wildcard), model=f85-2019 (Tool), keys in ordinal order. + /// The log line prints the view with the record's own ToString, and a dictionary prints + /// as its type name there. + /// + private string ScopeText() + => string.Join(", ", Scope + .OrderBy(facet => facet.Key, StringComparer.Ordinal) + .Select(facet => ScopeOrigins.TryGetValue(facet.Key, out var origin) + ? $"{facet.Key}={facet.Value} ({origin})" + : $"{facet.Key}={facet.Value}")); + /// /// The part of one retrieval that may be written to a log store. /// @@ -101,11 +112,11 @@ internal sealed record LogView /// Gets how many characters the search input held. Never the input itself. public required int QueryLength { get; init; } - /// Gets the facets the turn's scope carried, or empty when none was open. - public required IReadOnlyDictionary Scope { get; init; } - - /// Gets where each facet's value came from, or empty when none was open. - public required IReadOnlyDictionary ScopeOrigins { get; init; } + /// + /// Gets the facets the turn's scope carried, each with where its value came from, as + /// code=* (Wildcard), model=f85-2019 (Tool). Empty when no scope was open. + /// + public required string Scope { get; init; } /// Gets how long the whole retrieval took, in milliseconds. public required double LatencyMs { get; init; } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs index 8532964d..107b74c7 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProbe.cs @@ -12,8 +12,8 @@ namespace AgentCore.Application.Knowledge; /// -/// §8 steps 3-6: the probe. Channel 2 of the ambiguity design — when a scoped search clears no card, -/// it drops one wildcard-filled facet, searches again, and names what the wider search holds. +/// §8 steps 3-6: the probe. When a scoped search clears no card, it drops one wildcard-filled facet, +/// searches again, and names what the wider search holds. /// internal static class KnowledgeProbe { @@ -207,25 +207,16 @@ internal static class KnowledgeProbe // out, but the record of what was named — which arms K21's tie-break — does not. var carriesHistory = TurnAmbients.Current?.Context?.CarriesHistory ?? false; - // Whether the note repeats what was last named, and the pending list and record that follow - // from it, are one transition under one lock acquisition. Deciding from an earlier Read() and - // writing after would let a concurrent participant on the same call slip between the two. + // Whether the note repeats what was last named, and the record that follows from it, are one + // transition under one lock acquisition. Deciding from an earlier Read() and writing after + // would let a concurrent participant on the same call slip between the two. var repeats = false; clarifications.Update(facet, s => { - repeats = wouldName.Names(s.EffectiveLastNamed); + repeats = wouldName.Names(s.LastNamed); - if (repeats) - { - return; - } - - // K41: the probe sets a pending list only where there is none. The linker's own list is - // what the caller was actually answering, and a search's guess must never replace it. - s.Pending ??= candidates; - - if (carriesHistory) + if (!repeats && carriesHistory) { s.LastNamed = wouldName; } @@ -252,8 +243,7 @@ internal static class KnowledgeProbe /// /// §8 step 3: the first facet, in fromState declaration order, the wildcard filled and that - /// dropping would not empty the scope, skip a slot at its ask cap, or repeat channel 1's own - /// question this turn. + /// dropping would not empty the scope or skip a slot at its ask cap. /// private static string? DroppableFacet( IReadOnlyList fromState, @@ -287,12 +277,8 @@ internal static class KnowledgeProbe continue; } - var snapshot = clarifications.Read(name); - - // K22: the probe's own counter is monotone and capped at maxAsks. K41: channel 1 already - // asked about this slot this turn, so the probe moves on rather than paying for a search - // it would then abandon. - if (snapshot.ProbeAsks >= ambiguity.MaxAsks || snapshot.AskedThisTurn) + // K22: the probe's own counter is monotone and capped at maxAsks. + if (clarifications.Read(name).ProbeAsks >= ambiguity.MaxAsks) { continue; } diff --git a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs index ad43f34c..79423574 100644 --- a/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs +++ b/src/AgentCore.Application/Knowledge/KnowledgeProviderFactory.cs @@ -4,6 +4,7 @@ using AgentCore.Application.Diagnostics; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; +using AgentCore.Application.State; using AgentCore.Domain.Knowledge; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; @@ -33,6 +34,7 @@ internal static class KnowledgeProviderFactory /// sink is not, because AuditEvent requires a call id and a sequence number that no /// ambient carries down here. /// + /// The document's providers.knowledge.scope block, or . /// The provider to hang on that agent. /// A required argument is . internal static AIContextProvider Create( @@ -40,7 +42,8 @@ internal static AIContextProvider Create( ResolvedKnowledge knowledge, string agent, IKnowledgeCitationFormatter citations, - ILoggerFactory? loggers) + ILoggerFactory? loggers, + KnowledgeScopeConfiguration? scope = null) { ArgumentNullException.ThrowIfNull(port); ArgumentNullException.ThrowIfNull(knowledge); @@ -62,7 +65,11 @@ internal static AIContextProvider Create( RecentMessageMemoryLimit = 4, }; - return new TextSearchProvider(SearchAsync, options, loggers); + AIContextProvider provider = new TextSearchProvider(SearchAsync, options, loggers); + + return knowledge.Mode == KnowledgeMode.Tool && scope?.Filterable is { Count: > 0 } filterable + ? new FacetFilterProvider(provider, filterable) + : provider; async Task> SearchAsync( string query, CancellationToken cancellationToken) @@ -76,38 +83,34 @@ internal static AIContextProvider Create( return [KnowledgeNotices.Of(KnowledgeNotices.NoScope)]; } - using var whole = knowledge.Scoped ? null : KnowledgeScopeScope.Open(WholeCorpus); + var composed = knowledge.Scoped ? KnowledgeScopeScope.Current! : WholeCorpus; + + var (narrowed, byTool) = ToolFacetOverlay.Apply(composed, ToolFacetScope.Current); var started = Stopwatch.GetTimestamp(); - // Held from the moment the main search returns, so a failure raised by anything after it — - // the probe's own second search included — is still recorded against the time the main - // search took, rather than against however long the probe went on to run. double? searched = null; try { - var cards = await port.SearchAsync(query, cancellationToken).ConfigureAwait(false); - searched = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + var under = narrowed; + var (cards, latency) = await Under(narrowed).ConfigureAwait(false); + searched = latency; - if (logger.IsEnabled(LogLevel.Debug)) + if (cards.Count == 0 && byTool) { - var record = KnowledgeSearchRecord - .Of(agent, knowledge, query, cards, searched.Value, failure: null) - .ForLog(); - - Log.KnowledgeRetrieved(logger, agent, cards.Count, record); + under = composed; + (cards, _) = await Under(composed).ConfigureAwait(false); } - // §8 step 1-2: the probe runs only for a tool-mode search that cleared no card at - // all (K13) and only for a scoped agent — an unscoped agent opened WholeCorpus, which - // holds no facets, and its empty search stays an empty list, exactly as today (K19). + using var tail = KnowledgeScopeScope.Open(under); + if (cards.Count == 0 && knowledge.Mode == KnowledgeMode.Tool - && KnowledgeScopeScope.Current is { Facets.Count: > 0 } scope) + && under.Facets.Count > 0) { return await KnowledgeProbe - .RunAsync(port, knowledge, scope, agent, query, logger, cancellationToken) + .RunAsync(port, knowledge, under, agent, query, logger, cancellationToken) .ConfigureAwait(false); } @@ -127,6 +130,26 @@ internal static AIContextProvider Create( return [KnowledgeNotices.Of(KnowledgeNotices.Unreachable)]; } + + async Task<(IReadOnlyList Cards, double LatencyMs)> Under(KnowledgeScope open) + { + using var held = KnowledgeScopeScope.Open(open); + + var cards = await port.SearchAsync(query, cancellationToken).ConfigureAwait(false); + + var latency = Stopwatch.GetElapsedTime(started).TotalMilliseconds; + + if (logger.IsEnabled(LogLevel.Debug)) + { + var record = KnowledgeSearchRecord + .Of(agent, knowledge, query, cards, latency, failure: null) + .ForLog(); + + Log.KnowledgeRetrieved(logger, agent, cards.Count, record); + } + + return (cards, latency); + } } } diff --git a/src/AgentCore.Application/Knowledge/ToolFacetOverlay.cs b/src/AgentCore.Application/Knowledge/ToolFacetOverlay.cs new file mode 100644 index 00000000..471fc02e --- /dev/null +++ b/src/AgentCore.Application/Knowledge/ToolFacetOverlay.cs @@ -0,0 +1,49 @@ +using AgentCore.Domain.Knowledge; + +namespace AgentCore.Application.Knowledge; + +/// +/// Lays the facets a tool argument carried over the scope the turn composed. +/// +internal static class ToolFacetOverlay +{ + /// Writes the named facets into the scope, where the turn left room for them. + /// The scope the search would otherwise run under. + /// What the argument carried, or when it carried nothing. + /// + /// The scope to search under, and when it differs from + /// . A caller that gets holds both, so dropping + /// these facets later is reopening the one it came in with rather than unpicking this one. + /// + internal static (KnowledgeScope Scope, bool Narrowed) Apply( + KnowledgeScope scope, IReadOnlyDictionary? named) + { + ArgumentNullException.ThrowIfNull(scope); + + if (named is not { Count: > 0 }) + { + return (scope, false); + } + + Dictionary facets = new(scope.Facets, StringComparer.Ordinal); + Dictionary origins = new(scope.Origins, StringComparer.Ordinal); + var wrote = false; + + foreach (var (key, value) in named) + { + if (scope.Origins.TryGetValue(key, out var origin) + && origin is not KnowledgeFacetOrigin.Wildcard) + { + continue; + } + + facets[key] = value; + origins[key] = KnowledgeFacetOrigin.Tool; + wrote = true; + } + + return wrote + ? (new KnowledgeScope { Facets = facets, Origins = origins }, true) + : (scope, false); + } +} diff --git a/src/AgentCore.Application/Knowledge/ToolFacetScope.cs b/src/AgentCore.Application/Knowledge/ToolFacetScope.cs new file mode 100644 index 00000000..d46fa58e --- /dev/null +++ b/src/AgentCore.Application/Knowledge/ToolFacetScope.cs @@ -0,0 +1,42 @@ +namespace AgentCore.Application.Knowledge; + +/// +/// Carries the facets a search tool's argument named down to the search itself. +/// +internal static class ToolFacetScope +{ + private static readonly AsyncLocal?> Named = new(); + + /// Gets what a tool argument named on this flow, or when none did. + internal static IReadOnlyDictionary? Current => Named.Value; + + /// Opens one set of named facets over this flow. + /// The facet key to stored value. + /// A handle that puts back what was open before. + /// is . + internal static IDisposable Open(IReadOnlyDictionary facets) + { + ArgumentNullException.ThrowIfNull(facets); + + var before = Named.Value; + Named.Value = facets; + + return new Handle(before); + } + + private sealed class Handle(IReadOnlyDictionary? before) : IDisposable + { + private bool _closed; + + public void Dispose() + { + if (_closed) + { + return; + } + + _closed = true; + Named.Value = before; + } + } +} diff --git a/src/AgentCore.Application/Ports/IFacetVocabularyPort.cs b/src/AgentCore.Application/Ports/IFacetVocabularyPort.cs deleted file mode 100644 index 4a4dc93c..00000000 --- a/src/AgentCore.Application/Ports/IFacetVocabularyPort.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace AgentCore.Application.Ports; - -/// -/// Reads the distinct values a store holds at one payload path — the vocabulary a -/// vocabulary: slot gates writes against and links mentions to. -/// -public interface IFacetVocabularyPort -{ - /// Reads the distinct values stored at one payload path. - /// The payload path, already resolved from scope.template. - /// The most values to return. A result of exactly this size is a truncation. - /// Cancels the read. - ValueTask> ReadAsync( - string path, - int limit, - CancellationToken cancellationToken = default); -} diff --git a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs index 01c21c4f..10b3c043 100644 --- a/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs +++ b/src/AgentCore.Application/Ports/IKnowledgeRetrievalPort.cs @@ -6,10 +6,10 @@ namespace AgentCore.Application.Ports; /// The whole knowledge base, behind one method — and a way to ask for the rest. /// /// -/// Search is the one thing every store owes. Everything beyond it — reading a facet vocabulary, -/// reading whole cards by an exact facet value — is a capability a store may or may not have, and -/// it lives on its own interface that only a store able to serve it implements. A caller asks for -/// one through . +/// Search is the one thing every store owes. Everything beyond it — reading whole cards by an +/// exact facet value, say — is a capability a store may or may not have, and it lives on its own +/// interface that only a store able to serve it implements. A caller asks for one through +/// . /// public interface IKnowledgeRetrievalPort { @@ -22,7 +22,7 @@ ValueTask> SearchAsync( CancellationToken cancellationToken = default); /// Asks this store for a capability it may also serve. - /// The capability being asked for, such as . + /// The capability being asked for, such as . /// Names one of several, when a store serves more than one. Most serve none. /// The capability, or when this store does not serve it. /// diff --git a/src/AgentCore.Application/PublicAPI.Unshipped.txt b/src/AgentCore.Application/PublicAPI.Unshipped.txt index 2fb07d07..9ea185ea 100644 --- a/src/AgentCore.Application/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Application/PublicAPI.Unshipped.txt @@ -62,12 +62,8 @@ AgentCore.Application.Calls.CallClarificationState AgentCore.Application.Calls.CallClarificationState.$() -> AgentCore.Application.Calls.CallClarificationState! AgentCore.Application.Calls.CallClarificationState.CallClarificationState() -> void AgentCore.Application.Calls.CallClarificationState.Equals(AgentCore.Application.Calls.CallClarificationState? other) -> bool -AgentCore.Application.Calls.CallClarificationState.NamedAsks.get -> int -AgentCore.Application.Calls.CallClarificationState.NamedAsks.init -> void AgentCore.Application.Calls.CallClarificationState.ProbeAsks.get -> int AgentCore.Application.Calls.CallClarificationState.ProbeAsks.init -> void -AgentCore.Application.Calls.CallClarificationState.ResetSpent.get -> bool -AgentCore.Application.Calls.CallClarificationState.ResetSpent.init -> void AgentCore.Application.Calls.CallCursor AgentCore.Application.Calls.CallPage AgentCore.Application.Calls.CallPage.$() -> AgentCore.Application.Calls.CallPage! @@ -527,6 +523,14 @@ AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Locator. AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Locator.init -> void AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Source.get -> string? AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Source.init -> void +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.$() -> AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration! +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Description.get -> string! +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Description.init -> void +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Equals(AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Key.get -> string! +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Key.init -> void +AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.KnowledgeFilterableFacetConfiguration() -> void AgentCore.Application.Configuration.Schema.KnowledgeLinkLookup AgentCore.Application.Configuration.Schema.KnowledgeLinkLookup.Direct = 1 -> AgentCore.Application.Configuration.Schema.KnowledgeLinkLookup AgentCore.Application.Configuration.Schema.KnowledgeLinkLookup.Filter = 2 -> AgentCore.Application.Configuration.Schema.KnowledgeLinkLookup @@ -577,6 +581,8 @@ AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.Vector AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.$() -> AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration! AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.Equals(AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration? other) -> bool +AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.Filterable.get -> System.Collections.Generic.IReadOnlyList! +AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.Filterable.init -> void AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.FromState.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.FromState.init -> void AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.KnowledgeScopeConfiguration() -> void @@ -692,20 +698,6 @@ AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telemetry.init AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telephony.get -> AgentCore.Application.Configuration.Schema.VendorProviderConfiguration? AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Telephony.init -> void AgentCore.Application.Configuration.Schema.ReservedStateSlots -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.$() -> AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration! -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.AssumeNormalized.get -> bool -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.AssumeNormalized.init -> void -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.Equals(AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? other) -> bool -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.From.get -> string! -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.From.init -> void -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.Linker.get -> string! -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.Linker.init -> void -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.MaxValues.get -> int -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.MaxValues.init -> void -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.RefreshSeconds.get -> int -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.RefreshSeconds.init -> void -AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.SlotVocabularyConfiguration() -> void AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.$() -> AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.Equals(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? other) -> bool @@ -757,8 +749,6 @@ AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Type.get -> Ag AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Type.init -> void AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Value.get -> System.Text.Json.Nodes.JsonNode? AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Value.init -> void -AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Vocabulary.get -> AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? -AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Vocabulary.init -> void AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Writer.get -> AgentCore.Application.Configuration.Schema.StateWriter AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Writer.init -> void AgentCore.Application.Configuration.Schema.StateSlotType @@ -1018,8 +1008,6 @@ AgentCore.Application.Ports.IEmbeddingGeneratorAdapter AgentCore.Application.Ports.IEmbeddingGeneratorAdapter.CreateGeneratorAsync(AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration! entry, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!>!> AgentCore.Application.Ports.IEvaluationScorePublisher AgentCore.Application.Ports.IEvaluationScorePublisher.PublishAsync(AgentCore.Application.Evaluation.EvaluationScore! score, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask -AgentCore.Application.Ports.IFacetVocabularyPort -AgentCore.Application.Ports.IFacetVocabularyPort.ReadAsync(string! path, int limit, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Ports.IKnowledgeFacetReadPort AgentCore.Application.Ports.IKnowledgeFacetReadPort.ReadByFacetAsync(string! path, string! value, int limit, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> AgentCore.Application.Ports.IKnowledgeRetrievalPort @@ -1118,7 +1106,7 @@ AgentCore.Application.Runtime.CallSession.Stage.get -> string! AgentCore.Application.Runtime.CallSession.State.get -> AgentCore.Application.State.StateDocument! AgentCore.Application.Runtime.CallSession.Transcript.get -> System.Collections.Generic.IReadOnlyList! AgentCore.Application.Runtime.CallSessionFactory -AgentCore.Application.Runtime.CallSessionFactory.CallSessionFactory(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Configuration.Validation.IGuardEvaluator! guards, AgentCore.Application.State.StateExtractor? extractor = null, System.TimeProvider? timeProvider = null, Microsoft.Extensions.Logging.ILogger? logger = null, System.Collections.Generic.IEnumerable? observers = null, AgentCore.Application.State.VocabularyCache? vocabulary = null) -> void +AgentCore.Application.Runtime.CallSessionFactory.CallSessionFactory(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Configuration.Validation.IGuardEvaluator! guards, AgentCore.Application.State.StateExtractor? extractor = null, System.TimeProvider? timeProvider = null, Microsoft.Extensions.Logging.ILogger? logger = null, System.Collections.Generic.IEnumerable? observers = null) -> void AgentCore.Application.Runtime.CallSessionFactory.Create(string? callId = null, AgentCore.Application.Calls.CallSessionState? state = null) -> AgentCore.Application.Runtime.CallSession! AgentCore.Application.Runtime.CallSourceScope AgentCore.Application.Runtime.CallStateScope @@ -1168,26 +1156,6 @@ AgentCore.Application.State.ConstStateWriter AgentCore.Application.State.CounterStateWriter AgentCore.Application.State.CounterStateWriter.Apply(AgentCore.Application.State.StateDocument! state) -> int AgentCore.Application.State.CounterStateWriter.CounterStateWriter(AgentCore.Application.Configuration.Validation.IGuardEvaluator! rules) -> void -AgentCore.Application.State.ExactStateValueLinker -AgentCore.Application.State.ExactStateValueLinker.ExactStateValueLinker() -> void -AgentCore.Application.State.ExactStateValueLinker.Link(string! mention, AgentCore.Application.State.VocabularyView! vocabulary, System.Collections.Generic.IReadOnlySet! lastNamed) -> AgentCore.Application.State.LinkResult! -AgentCore.Application.State.ExactStateValueLinker.Name.get -> string! -AgentCore.Application.State.IStateValueLinker -AgentCore.Application.State.IStateValueLinker.Link(string! mention, AgentCore.Application.State.VocabularyView! vocabulary, System.Collections.Generic.IReadOnlySet! lastNamed) -> AgentCore.Application.State.LinkResult! -AgentCore.Application.State.IStateValueLinker.Name.get -> string! -AgentCore.Application.State.LinkOutcome -AgentCore.Application.State.LinkOutcome.Ambiguous = 2 -> AgentCore.Application.State.LinkOutcome -AgentCore.Application.State.LinkOutcome.Linked = 1 -> AgentCore.Application.State.LinkOutcome -AgentCore.Application.State.LinkOutcome.NoMatch = 0 -> AgentCore.Application.State.LinkOutcome -AgentCore.Application.State.LinkResult -AgentCore.Application.State.LinkResult.$() -> AgentCore.Application.State.LinkResult! -AgentCore.Application.State.LinkResult.Candidates.get -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.State.LinkResult.Candidates.init -> void -AgentCore.Application.State.LinkResult.Deconstruct(out AgentCore.Application.State.LinkOutcome Outcome, out System.Collections.Generic.IReadOnlyList! Candidates) -> void -AgentCore.Application.State.LinkResult.Equals(AgentCore.Application.State.LinkResult? other) -> bool -AgentCore.Application.State.LinkResult.LinkResult(AgentCore.Application.State.LinkOutcome Outcome, System.Collections.Generic.IReadOnlyList! Candidates) -> void -AgentCore.Application.State.LinkResult.Outcome.get -> AgentCore.Application.State.LinkOutcome -AgentCore.Application.State.LinkResult.Outcome.init -> void AgentCore.Application.State.StateDocument AgentCore.Application.State.StateDocument.CallDurationSeconds.get -> double AgentCore.Application.State.StateDocument.CallDurationSeconds.set -> void @@ -1198,7 +1166,7 @@ AgentCore.Application.State.StateDocument.SlotNames.get -> System.Collections.Ge AgentCore.Application.State.StateDocument.Snapshot() -> System.Collections.Generic.IReadOnlyDictionary! AgentCore.Application.State.StateDocument.Stage.get -> string! AgentCore.Application.State.StateDocument.Stage.set -> void -AgentCore.Application.State.StateDocument.StateDocument(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, string? stage = null, System.Collections.Generic.IReadOnlyDictionary? vocabulary = null) -> void +AgentCore.Application.State.StateDocument.StateDocument(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, string? stage = null) -> void AgentCore.Application.State.StateDocument.TryWrite(string! slot, System.Text.Json.Nodes.JsonNode? value) -> bool AgentCore.Application.State.StateDocument.TurnIndex.get -> int AgentCore.Application.State.StateDocument.TurnIndex.set -> void @@ -1228,24 +1196,6 @@ AgentCore.Application.State.StateExtractor.Write(AgentCore.Application.State.Sta AgentCore.Application.State.StateValueCoercion AgentCore.Application.State.ToolStateWriter AgentCore.Application.State.UnfilledSlotReminder -AgentCore.Application.State.VocabularyCache -AgentCore.Application.State.VocabularyCache.LastGoodAt(string! slot) -> System.DateTimeOffset? -AgentCore.Application.State.VocabularyCache.Replace(string! slot, System.Collections.Generic.IReadOnlyList! values, int maxValues, string? wildcardValue = null) -> void -AgentCore.Application.State.VocabularyCache.Snapshot() -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.State.VocabularyCache.VocabularyCache(System.TimeProvider? timeProvider = null) -> void -AgentCore.Application.State.VocabularyException -AgentCore.Application.State.VocabularyException.Slot.get -> string! -AgentCore.Application.State.VocabularyException.VocabularyException() -> void -AgentCore.Application.State.VocabularyException.VocabularyException(string! message) -> void -AgentCore.Application.State.VocabularyException.VocabularyException(string! message, System.Exception? innerException) -> void -AgentCore.Application.State.VocabularyView -AgentCore.Application.State.VocabularyView.$() -> AgentCore.Application.State.VocabularyView! -AgentCore.Application.State.VocabularyView.Equals(AgentCore.Application.State.VocabularyView? other) -> bool -AgentCore.Application.State.VocabularyView.NormalisedToOriginal.get -> System.Collections.Generic.IReadOnlyDictionary! -AgentCore.Application.State.VocabularyView.NormalisedToOriginal.init -> void -AgentCore.Application.State.VocabularyView.Originals.get -> System.Collections.Generic.IReadOnlyList! -AgentCore.Application.State.VocabularyView.Originals.init -> void -AgentCore.Application.State.VocabularyView.VocabularyView() -> void AgentCore.Application.Tools.Binding.BindingToolSource AgentCore.Application.Tools.Binding.BindingToolSource.BindingToolSource(AgentCore.Application.Tools.Binding.ToolBindingRegistry! registry) -> void AgentCore.Application.Tools.Binding.BindingToolSource.ProvideAsync(AgentCore.Application.Tools.Registry.ToolSourceContext! context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask!> @@ -1342,12 +1292,6 @@ AgentCore.Application.Transcript.SourceContent.SourceContent() -> void AgentCore.Application.Transcript.TranscriptJson abstract AgentCore.Application.Call.CallInput.$() -> AgentCore.Application.Call.CallInput! abstract AgentCore.Application.Tools.DeclaredTool.CallAsync(Microsoft.Extensions.AI.AIFunctionArguments! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask -virtual AgentCore.Application.Call.CallInput.EqualityContract.get -> System.Type! -virtual AgentCore.Application.Call.CallInput.Equals(AgentCore.Application.Call.CallInput? other) -> bool -virtual AgentCore.Application.Call.CallInput.PrintMembers(System.Text.StringBuilder! builder) -> bool -virtual AgentCore.Application.Tools.Binding.ToolBinding.Invoke(System.Text.Json.Nodes.JsonObject! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask -~override AgentCore.Application.Providers.VendorSeam.Equals(object obj) -> bool -~override AgentCore.Application.Providers.VendorSeam.ToString() -> string const AgentCore.Application.Audit.AuditSinkFactory.MemoryKind = "memory" -> string! const AgentCore.Application.Audit.QueuedAuditSink.DefaultBatchSize = 100 -> int const AgentCore.Application.Audit.QueuedAuditSink.DefaultCapacity = 10000 -> int @@ -1381,9 +1325,6 @@ const AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration. const AgentCore.Application.Configuration.Schema.ReservedStateSlots.CallDurationSeconds = "callDurationSeconds" -> string! const AgentCore.Application.Configuration.Schema.ReservedStateSlots.Stage = "stage" -> string! const AgentCore.Application.Configuration.Schema.ReservedStateSlots.TurnIndex = "turnIndex" -> string! -const AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.DefaultLinker = "exact" -> string! -const AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.DefaultMaxValues = 2000 -> int -const AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.DefaultRefreshSeconds = 0 -> int const AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.DefaultExportIntervalMilliseconds = 60000 -> int const AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.DefaultServiceName = "agentcore" -> string! const AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.MinimumExportIntervalMilliseconds = 60000 -> int @@ -1422,6 +1363,221 @@ const AgentCore.Application.Tools.Builtin.BuiltinToolNames.WebSearch = "web.sear const AgentCore.Application.Tools.ToolErrorResult.ErrorProperty = "error" -> string! const AgentCore.Application.Tools.ToolErrorResult.MessageProperty = "message" -> string! const AgentCore.Application.Tools.ToolErrorResult.ToolProperty = "tool" -> string! +override AgentCore.Application.Call.CallChannel.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallChannel.GetHashCode() -> int +override AgentCore.Application.Call.CallChannel.ToString() -> string! +override AgentCore.Application.Call.CallChannelContext.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallChannelContext.GetHashCode() -> int +override AgentCore.Application.Call.CallChannelContext.ToString() -> string! +override AgentCore.Application.Call.CallInput.Barge.$() -> AgentCore.Application.Call.CallInput.Barge! +override AgentCore.Application.Call.CallInput.Barge.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallInput.Barge.GetHashCode() -> int +override AgentCore.Application.Call.CallInput.Barge.ToString() -> string! +override AgentCore.Application.Call.CallInput.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallInput.GetHashCode() -> int +override AgentCore.Application.Call.CallInput.Keypress.$() -> AgentCore.Application.Call.CallInput.Keypress! +override AgentCore.Application.Call.CallInput.Keypress.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallInput.Keypress.GetHashCode() -> int +override AgentCore.Application.Call.CallInput.Keypress.ToString() -> string! +override AgentCore.Application.Call.CallInput.ToString() -> string! +override AgentCore.Application.Call.CallInput.Utterance.$() -> AgentCore.Application.Call.CallInput.Utterance! +override AgentCore.Application.Call.CallInput.Utterance.Equals(object? obj) -> bool +override AgentCore.Application.Call.CallInput.Utterance.GetHashCode() -> int +override AgentCore.Application.Call.CallInput.Utterance.ToString() -> string! +override AgentCore.Application.Calls.CallClarificationState.Equals(object? obj) -> bool +override AgentCore.Application.Calls.CallClarificationState.GetHashCode() -> int +override AgentCore.Application.Calls.CallClarificationState.ToString() -> string! +override AgentCore.Application.Calls.CallPage.Equals(object? obj) -> bool +override AgentCore.Application.Calls.CallPage.GetHashCode() -> int +override AgentCore.Application.Calls.CallPage.ToString() -> string! +override AgentCore.Application.Calls.CallRecord.Equals(object? obj) -> bool +override AgentCore.Application.Calls.CallRecord.GetHashCode() -> int +override AgentCore.Application.Calls.CallRecord.ToString() -> string! +override AgentCore.Application.Calls.CallSessionState.Equals(object? obj) -> bool +override AgentCore.Application.Calls.CallSessionState.GetHashCode() -> int +override AgentCore.Application.Calls.CallSessionState.ToString() -> string! +override AgentCore.Application.Configuration.Compilation.ResolvedClarification.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Compilation.ResolvedClarification.GetHashCode() -> int +override AgentCore.Application.Configuration.Compilation.ResolvedClarification.ToString() -> string! +override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.GetHashCode() -> int +override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.ToString() -> string! +override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.GetHashCode() -> int +override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.ToString() -> string! +override AgentCore.Application.Configuration.Parsing.ConfigurationError.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Parsing.ConfigurationError.GetHashCode() -> int +override AgentCore.Application.Configuration.Parsing.ConfigurationError.ToString() -> string! +override AgentCore.Application.Configuration.Parsing.ScopeTemplate.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Parsing.ScopeTemplate.GetHashCode() -> int +override AgentCore.Application.Configuration.Parsing.ScopeTemplate.ToString() -> string! +override AgentCore.Application.Configuration.Parsing.SecretReference.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Parsing.SecretReference.GetHashCode() -> int +override AgentCore.Application.Configuration.Parsing.SecretReference.ToString() -> string! +override AgentCore.Application.Configuration.Parsing.SecretTemplate.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Parsing.SecretTemplate.GetHashCode() -> int +override AgentCore.Application.Configuration.Parsing.SecretTemplate.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentDefaults.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentDefaults.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentDefaults.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.AgentsConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.AgentsConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.AgentsConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.CompactionConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.CompactionConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.CompactionConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.GraphConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.GraphConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.GraphConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.GuardReference.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.GuardReference.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.GuardReference.ToString() -> string! +override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.McpAllowEntry.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.McpAllowEntry.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.McpAllowEntry.ToString() -> string! +override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.McpServerConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.McpServerConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.McpServerConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ModelReference.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ModelReference.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ModelReference.ToString() -> string! +override AgentCore.Application.Configuration.Schema.PolicyConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.PolicyConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.PolicyConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.StageConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.StageConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.StageConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.StageTransition.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.StageTransition.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.StageTransition.ToString() -> string! +override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.TitlerConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.TitlerConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.TitlerConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ToolConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ToolConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ToolConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Schema.ToolResultReference.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.ToolResultReference.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.ToolResultReference.ToString() -> string! +override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.GetHashCode() -> int +override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.ToString() -> string! +override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.Equals(object? obj) -> bool +override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.GetHashCode() -> int +override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.ToString() -> string! +override AgentCore.Application.Evaluation.EvaluationScore.Equals(object? obj) -> bool +override AgentCore.Application.Evaluation.EvaluationScore.GetHashCode() -> int +override AgentCore.Application.Evaluation.EvaluationScore.ToString() -> string! +override AgentCore.Application.Knowledge.KnowledgePoint.Equals(object? obj) -> bool +override AgentCore.Application.Knowledge.KnowledgePoint.GetHashCode() -> int +override AgentCore.Application.Knowledge.KnowledgePoint.ToString() -> string! +override AgentCore.Application.Providers.VendorSeam.GetHashCode() -> int +override AgentCore.Application.Runtime.AgentCoreAgent.Description.get -> string? +override AgentCore.Application.Runtime.AgentCoreAgent.Name.get -> string? +override AgentCore.Application.Runtime.CallEvent.Equals(object? obj) -> bool +override AgentCore.Application.Runtime.CallEvent.GetHashCode() -> int +override AgentCore.Application.Runtime.CallEvent.ToString() -> string! +override AgentCore.Application.Runtime.CallTurnOrigin.Equals(object? obj) -> bool +override AgentCore.Application.Runtime.CallTurnOrigin.GetHashCode() -> int +override AgentCore.Application.Runtime.CallTurnOrigin.ToString() -> string! +override AgentCore.Application.Secrets.ResolvedSecrets.ToString() -> string! +override AgentCore.Application.Secrets.SecretName.Equals(object? obj) -> bool +override AgentCore.Application.Secrets.SecretName.GetHashCode() -> int +override AgentCore.Application.Secrets.SecretName.ToString() -> string! +override AgentCore.Application.State.StateExtractionResult.Equals(object? obj) -> bool +override AgentCore.Application.State.StateExtractionResult.GetHashCode() -> int +override AgentCore.Application.State.StateExtractionResult.ToString() -> string! +override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Equals(object? obj) -> bool +override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.GetHashCode() -> int +override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.ToString() -> string! +override AgentCore.Application.Tools.DeclaredTool.Description.get -> string! +override AgentCore.Application.Tools.DeclaredTool.JsonSchema.get -> System.Text.Json.JsonElement +override AgentCore.Application.Tools.DeclaredTool.Name.get -> string! +override AgentCore.Application.Tools.Registry.ToolRegistration.Equals(object? obj) -> bool +override AgentCore.Application.Tools.Registry.ToolRegistration.GetHashCode() -> int +override AgentCore.Application.Tools.Registry.ToolRegistration.ToString() -> string! +override AgentCore.Application.Tools.Registry.ToolSourceContext.Equals(object? obj) -> bool +override AgentCore.Application.Tools.Registry.ToolSourceContext.GetHashCode() -> int +override AgentCore.Application.Tools.Registry.ToolSourceContext.ToString() -> string! +override AgentCore.Application.Transcript.CallMessage.Equals(object? obj) -> bool +override AgentCore.Application.Transcript.CallMessage.GetHashCode() -> int +override AgentCore.Application.Transcript.CallMessage.ToString() -> string! +override sealed AgentCore.Application.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput? other) -> bool +override sealed AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput? other) -> bool +override sealed AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput? other) -> bool +override sealed AgentCore.Application.Tools.DeclaredTool.InvokeCoreAsync(Microsoft.Extensions.AI.AIFunctionArguments! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask static AgentCore.Application.Audit.AuditSinkFactory.OpenAsync(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, AgentCore.Application.Ports.ISecretResolverPort? secrets, System.Collections.Generic.IReadOnlyList! adapters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static AgentCore.Application.Call.CallChannel.operator !=(AgentCore.Application.Call.CallChannel? left, AgentCore.Application.Call.CallChannel? right) -> bool static AgentCore.Application.Call.CallChannel.operator ==(AgentCore.Application.Call.CallChannel? left, AgentCore.Application.Call.CallChannel? right) -> bool @@ -1436,10 +1592,10 @@ static AgentCore.Application.Call.CallInput.Utterance.operator ==(AgentCore.Appl static AgentCore.Application.Call.CallInput.operator !=(AgentCore.Application.Call.CallInput? left, AgentCore.Application.Call.CallInput? right) -> bool static AgentCore.Application.Call.CallInput.operator ==(AgentCore.Application.Call.CallInput? left, AgentCore.Application.Call.CallInput? right) -> bool static AgentCore.Application.Call.CallSpeechPairing.Validate(AgentCore.Application.Configuration.Schema.CallProviderConfiguration! call, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration! speech, AgentCore.Application.Ports.ICallAdapter! selectedCall) -> void -static AgentCore.Application.Calls.CallCursor.Encode(System.DateTimeOffset sortAt, string! callId) -> string! -static AgentCore.Application.Calls.CallCursor.TryDecode(string? cursor, out System.DateTimeOffset sortAt, out string! callId) -> bool static AgentCore.Application.Calls.CallClarificationState.operator !=(AgentCore.Application.Calls.CallClarificationState? left, AgentCore.Application.Calls.CallClarificationState? right) -> bool static AgentCore.Application.Calls.CallClarificationState.operator ==(AgentCore.Application.Calls.CallClarificationState? left, AgentCore.Application.Calls.CallClarificationState? right) -> bool +static AgentCore.Application.Calls.CallCursor.Encode(System.DateTimeOffset sortAt, string! callId) -> string! +static AgentCore.Application.Calls.CallCursor.TryDecode(string? cursor, out System.DateTimeOffset sortAt, out string! callId) -> bool static AgentCore.Application.Calls.CallPage.operator !=(AgentCore.Application.Calls.CallPage? left, AgentCore.Application.Calls.CallPage? right) -> bool static AgentCore.Application.Calls.CallPage.operator ==(AgentCore.Application.Calls.CallPage? left, AgentCore.Application.Calls.CallPage? right) -> bool static AgentCore.Application.Calls.CallRecord.operator !=(AgentCore.Application.Calls.CallRecord? left, AgentCore.Application.Calls.CallRecord? right) -> bool @@ -1523,6 +1679,8 @@ static AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguratio static AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.operator ==(AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.operator !=(AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.operator ==(AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.operator !=(AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration? right) -> bool +static AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration.operator ==(AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeFilterableFacetConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.operator !=(AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.operator ==(AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration? left, AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration? right) -> bool @@ -1547,8 +1705,6 @@ static AgentCore.Application.Configuration.Schema.ProvidersConfiguration.operato static AgentCore.Application.Configuration.Schema.ProvidersConfiguration.operator ==(AgentCore.Application.Configuration.Schema.ProvidersConfiguration? left, AgentCore.Application.Configuration.Schema.ProvidersConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.ReservedStateSlots.All.get -> System.Collections.Generic.IReadOnlyList! static AgentCore.Application.Configuration.Schema.ReservedStateSlots.Contains(string! name) -> bool -static AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.operator !=(AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? left, AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? right) -> bool -static AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.operator ==(AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? left, AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.operator !=(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? left, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.operator ==(AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? left, AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration? right) -> bool static AgentCore.Application.Configuration.Schema.StageConfiguration.operator !=(AgentCore.Application.Configuration.Schema.StageConfiguration? left, AgentCore.Application.Configuration.Schema.StageConfiguration? right) -> bool @@ -1574,7 +1730,6 @@ static AgentCore.Application.Configuration.Validation.ConfigurationValidationRes static AgentCore.Application.Configuration.Validation.ConfigurationValidator.Evaluate(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration) -> AgentCore.Application.Configuration.Validation.ConfigurationValidationResult! static AgentCore.Application.Configuration.Validation.ConfigurationValidator.EvaluateStructure(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration) -> AgentCore.Application.Configuration.Validation.ConfigurationValidationResult! static AgentCore.Application.Configuration.Validation.ConfigurationValidator.Validate(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration) -> AgentCore.Application.Configuration.Validation.ConfigurationValidationResult! -static AgentCore.Application.Configuration.Validation.ConfigurationValidator.ValidateLinkerNames(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, System.Collections.Generic.IReadOnlySet! registered) -> void static AgentCore.Application.Configuration.Validation.ConfigurationValidator.ValidateSkillReferences(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, System.Collections.Generic.IReadOnlySet! servedSkillNames) -> void static AgentCore.Application.Configuration.Validation.ConfigurationValidator.ValidateSkillToolNames(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration) -> void static AgentCore.Application.Configuration.Validation.ConfigurationValidator.ValidateStructure(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration) -> AgentCore.Application.Configuration.Validation.ConfigurationValidationResult! @@ -1609,7 +1764,6 @@ static AgentCore.Application.Runtime.CallEvent.operator ==(AgentCore.Application static AgentCore.Application.Runtime.CallObservers.Standard(AgentCore.Application.Ports.IAuditSinkPort! auditSink, Microsoft.Extensions.Logging.ILogger? logger, System.Collections.Generic.IEnumerable? hostObservers = null) -> System.Collections.Generic.IReadOnlyList! static AgentCore.Application.Runtime.CallRenderScope.Current.get -> AgentCore.Application.Ports.IRenderPort? static AgentCore.Application.Runtime.CallSessionFactory.CreateExtractor(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Ports.IChatClientFactory! chatClients) -> AgentCore.Application.State.StateExtractor? -static AgentCore.Application.Runtime.CallSessionFactory.CreateExtractor(AgentCore.Application.Configuration.Compilation.CompiledAgent! compiled, AgentCore.Application.Ports.IChatClientFactory! chatClients, System.Collections.Generic.IEnumerable? linkers) -> AgentCore.Application.State.StateExtractor? static AgentCore.Application.Runtime.CallSourceScope.Current.get -> AgentCore.Application.Ports.ISourcePort? static AgentCore.Application.Runtime.CallStateScope.Enter(AgentCore.Application.State.StateDocument! state) -> System.IDisposable! static AgentCore.Application.Runtime.CallStateScope.Snapshot() -> System.Collections.Generic.IReadOnlyDictionary! @@ -1626,8 +1780,6 @@ static AgentCore.Application.Secrets.SecretResolutionException.Unresolved(string static AgentCore.Application.Secrets.SecretResolverExtensions.RequireAsync(this AgentCore.Application.Ports.ISecretResolverPort? secrets, AgentCore.Application.Secrets.SecretName! secret, string? because = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static AgentCore.Application.Secrets.SecretResolverExtensions.TryReadAsync(this AgentCore.Application.Ports.ISecretResolverPort? secrets, AgentCore.Application.Secrets.SecretName! secret, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.ValueTask static AgentCore.Application.State.ConstStateWriter.Apply(AgentCore.Application.State.StateDocument! state) -> int -static AgentCore.Application.State.LinkResult.operator !=(AgentCore.Application.State.LinkResult? left, AgentCore.Application.State.LinkResult? right) -> bool -static AgentCore.Application.State.LinkResult.operator ==(AgentCore.Application.State.LinkResult? left, AgentCore.Application.State.LinkResult? right) -> bool static AgentCore.Application.State.StateExtractionResult.Failed(string! failure) -> AgentCore.Application.State.StateExtractionResult! static AgentCore.Application.State.StateExtractionResult.operator !=(AgentCore.Application.State.StateExtractionResult? left, AgentCore.Application.State.StateExtractionResult? right) -> bool static AgentCore.Application.State.StateExtractionResult.operator ==(AgentCore.Application.State.StateExtractionResult? left, AgentCore.Application.State.StateExtractionResult? right) -> bool @@ -1637,12 +1789,6 @@ static AgentCore.Application.State.ToolStateWriter.Apply(AgentCore.Application.S static AgentCore.Application.State.UnfilledSlotReminder.Build(AgentCore.Application.Configuration.Schema.AgentCoreConfiguration! configuration, System.Collections.Generic.IReadOnlyList! slots) -> string? static AgentCore.Application.State.UnfilledSlotReminder.Build(AgentCore.Application.State.StateDocument! state, AgentCore.Application.Configuration.Schema.StageConfiguration! stage) -> string? static AgentCore.Application.State.UnfilledSlotReminder.UnfilledSlots(AgentCore.Application.State.StateDocument! state, AgentCore.Application.Configuration.Schema.StageConfiguration! stage) -> System.Collections.Generic.IReadOnlyList! -static AgentCore.Application.State.VocabularyException.FoldingCollision(string! slot, string! first, string! second, string! normalised) -> AgentCore.Application.State.VocabularyException! -static AgentCore.Application.State.VocabularyException.FoldsToEmpty(string! slot, string! value) -> AgentCore.Application.State.VocabularyException! -static AgentCore.Application.State.VocabularyException.NoValues(string! slot) -> AgentCore.Application.State.VocabularyException! -static AgentCore.Application.State.VocabularyException.Truncated(string! slot, int maxValues) -> AgentCore.Application.State.VocabularyException! -static AgentCore.Application.State.VocabularyView.operator !=(AgentCore.Application.State.VocabularyView? left, AgentCore.Application.State.VocabularyView? right) -> bool -static AgentCore.Application.State.VocabularyView.operator ==(AgentCore.Application.State.VocabularyView? left, AgentCore.Application.State.VocabularyView? right) -> bool static AgentCore.Application.Tools.Builtin.BuiltinToolPorts.operator !=(AgentCore.Application.Tools.Builtin.BuiltinToolPorts? left, AgentCore.Application.Tools.Builtin.BuiltinToolPorts? right) -> bool static AgentCore.Application.Tools.Builtin.BuiltinToolPorts.operator ==(AgentCore.Application.Tools.Builtin.BuiltinToolPorts? left, AgentCore.Application.Tools.Builtin.BuiltinToolPorts? right) -> bool static AgentCore.Application.Tools.DeclaredTool.ArgumentText(Microsoft.Extensions.AI.AIFunctionArguments! arguments, string! name) -> string? @@ -1669,224 +1815,9 @@ static readonly AgentCore.Application.Secrets.KnownSecrets.OpenAi -> AgentCore.A static readonly AgentCore.Application.Secrets.KnownSecrets.PostgresConnectionString -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Secrets.KnownSecrets.Qdrant -> AgentCore.Application.Secrets.SecretName! static readonly AgentCore.Application.Sessions.Memory.InMemoryCallSessions.DefaultIdleTimeout -> System.TimeSpan -override AgentCore.Application.Call.CallChannel.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallChannel.GetHashCode() -> int -override AgentCore.Application.Call.CallChannel.ToString() -> string! -override AgentCore.Application.Call.CallChannelContext.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallChannelContext.GetHashCode() -> int -override AgentCore.Application.Call.CallChannelContext.ToString() -> string! -override AgentCore.Application.Call.CallInput.Barge.$() -> AgentCore.Application.Call.CallInput.Barge! -override AgentCore.Application.Call.CallInput.Barge.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Barge.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Barge.ToString() -> string! -override AgentCore.Application.Call.CallInput.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Keypress.$() -> AgentCore.Application.Call.CallInput.Keypress! -override AgentCore.Application.Call.CallInput.Keypress.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Keypress.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Keypress.ToString() -> string! -override AgentCore.Application.Call.CallInput.ToString() -> string! -override AgentCore.Application.Call.CallInput.Utterance.$() -> AgentCore.Application.Call.CallInput.Utterance! -override AgentCore.Application.Call.CallInput.Utterance.Equals(object? obj) -> bool -override AgentCore.Application.Call.CallInput.Utterance.GetHashCode() -> int -override AgentCore.Application.Call.CallInput.Utterance.ToString() -> string! -override AgentCore.Application.Calls.CallClarificationState.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallClarificationState.GetHashCode() -> int -override AgentCore.Application.Calls.CallClarificationState.ToString() -> string! -override AgentCore.Application.Calls.CallPage.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallPage.GetHashCode() -> int -override AgentCore.Application.Calls.CallPage.ToString() -> string! -override AgentCore.Application.Calls.CallRecord.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallRecord.GetHashCode() -> int -override AgentCore.Application.Calls.CallRecord.ToString() -> string! -override AgentCore.Application.Calls.CallSessionState.Equals(object? obj) -> bool -override AgentCore.Application.Calls.CallSessionState.GetHashCode() -> int -override AgentCore.Application.Calls.CallSessionState.ToString() -> string! -override AgentCore.Application.Configuration.Compilation.ResolvedClarification.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Compilation.ResolvedClarification.GetHashCode() -> int -override AgentCore.Application.Configuration.Compilation.ResolvedClarification.ToString() -> string! -override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.GetHashCode() -> int -override AgentCore.Application.Configuration.Compilation.ResolvedCompaction.ToString() -> string! -override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.GetHashCode() -> int -override AgentCore.Application.Configuration.Compilation.ResolvedKnowledge.ToString() -> string! -override AgentCore.Application.Configuration.Parsing.ConfigurationError.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Parsing.ConfigurationError.GetHashCode() -> int -override AgentCore.Application.Configuration.Parsing.ConfigurationError.ToString() -> string! -override AgentCore.Application.Configuration.Parsing.ScopeTemplate.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Parsing.ScopeTemplate.GetHashCode() -> int -override AgentCore.Application.Configuration.Parsing.ScopeTemplate.ToString() -> string! -override AgentCore.Application.Configuration.Parsing.SecretReference.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Parsing.SecretReference.GetHashCode() -> int -override AgentCore.Application.Configuration.Parsing.SecretReference.ToString() -> string! -override AgentCore.Application.Configuration.Parsing.SecretTemplate.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Parsing.SecretTemplate.GetHashCode() -> int -override AgentCore.Application.Configuration.Parsing.SecretTemplate.ToString() -> string! -override AgentCore.Application.Configuration.Schema.AgentConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.AgentConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.AgentConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.AgentCoreConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.AgentDefaults.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.AgentDefaults.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.AgentDefaults.ToString() -> string! -override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.AgentKnowledgeConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.AgentsConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.AgentsConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.AgentsConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.CallProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.CompactionConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.CompactionConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.CompactionConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.CompactionTriggerConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.EmbeddingProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.EvaluationConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.ExtractorConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.GraphConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.GraphConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.GraphConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.GraphEdgeConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.GraphNodeConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.GuardReference.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.GuardReference.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.GuardReference.ToString() -> string! -override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.HttpRequestConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeAmbiguityConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeFieldsConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeLinksConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeScopeConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.KnowledgeWildcardConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.LlmProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.McpAllowEntry.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.McpAllowEntry.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.McpAllowEntry.ToString() -> string! -override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.McpRetryConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.McpServerConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.McpServerConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.McpServerConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.ModelReference.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.ModelReference.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.ModelReference.ToString() -> string! -override AgentCore.Application.Configuration.Schema.PolicyConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.PolicyConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.PolicyConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.ProvidersConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.SlotVocabularyConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.SpeechProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.StageConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.StageConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.StageConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.StageTransition.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.StageTransition.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.StageTransition.ToString() -> string! -override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.StateSlotConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.TelemetryProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.TitlerConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.TitlerConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.TitlerConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.ToolConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.ToolConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.ToolConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Schema.ToolResultReference.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.ToolResultReference.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.ToolResultReference.ToString() -> string! -override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.GetHashCode() -> int -override AgentCore.Application.Configuration.Schema.VendorProviderConfiguration.ToString() -> string! -override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.Equals(object? obj) -> bool -override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.GetHashCode() -> int -override AgentCore.Application.Configuration.Validation.ConfigurationValidationResult.ToString() -> string! -override AgentCore.Application.Evaluation.EvaluationScore.Equals(object? obj) -> bool -override AgentCore.Application.Evaluation.EvaluationScore.GetHashCode() -> int -override AgentCore.Application.Evaluation.EvaluationScore.ToString() -> string! -override AgentCore.Application.Knowledge.KnowledgePoint.Equals(object? obj) -> bool -override AgentCore.Application.Knowledge.KnowledgePoint.GetHashCode() -> int -override AgentCore.Application.Knowledge.KnowledgePoint.ToString() -> string! -override AgentCore.Application.Providers.VendorSeam.GetHashCode() -> int -override AgentCore.Application.Runtime.AgentCoreAgent.Description.get -> string? -override AgentCore.Application.Runtime.AgentCoreAgent.Name.get -> string? -override AgentCore.Application.Runtime.CallEvent.Equals(object? obj) -> bool -override AgentCore.Application.Runtime.CallEvent.GetHashCode() -> int -override AgentCore.Application.Runtime.CallEvent.ToString() -> string! -override AgentCore.Application.Runtime.CallTurnOrigin.Equals(object? obj) -> bool -override AgentCore.Application.Runtime.CallTurnOrigin.GetHashCode() -> int -override AgentCore.Application.Runtime.CallTurnOrigin.ToString() -> string! -override AgentCore.Application.Secrets.ResolvedSecrets.ToString() -> string! -override AgentCore.Application.Secrets.SecretName.Equals(object? obj) -> bool -override AgentCore.Application.Secrets.SecretName.GetHashCode() -> int -override AgentCore.Application.Secrets.SecretName.ToString() -> string! -override AgentCore.Application.State.LinkResult.Equals(object? obj) -> bool -override AgentCore.Application.State.LinkResult.GetHashCode() -> int -override AgentCore.Application.State.LinkResult.ToString() -> string! -override AgentCore.Application.State.StateExtractionResult.Equals(object? obj) -> bool -override AgentCore.Application.State.StateExtractionResult.GetHashCode() -> int -override AgentCore.Application.State.StateExtractionResult.ToString() -> string! -override AgentCore.Application.State.VocabularyView.Equals(object? obj) -> bool -override AgentCore.Application.State.VocabularyView.GetHashCode() -> int -override AgentCore.Application.State.VocabularyView.ToString() -> string! -override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.Equals(object? obj) -> bool -override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.GetHashCode() -> int -override AgentCore.Application.Tools.Builtin.BuiltinToolPorts.ToString() -> string! -override AgentCore.Application.Tools.DeclaredTool.Description.get -> string! -override AgentCore.Application.Tools.DeclaredTool.JsonSchema.get -> System.Text.Json.JsonElement -override AgentCore.Application.Tools.DeclaredTool.Name.get -> string! -override AgentCore.Application.Tools.Registry.ToolRegistration.Equals(object? obj) -> bool -override AgentCore.Application.Tools.Registry.ToolRegistration.GetHashCode() -> int -override AgentCore.Application.Tools.Registry.ToolRegistration.ToString() -> string! -override AgentCore.Application.Tools.Registry.ToolSourceContext.Equals(object? obj) -> bool -override AgentCore.Application.Tools.Registry.ToolSourceContext.GetHashCode() -> int -override AgentCore.Application.Tools.Registry.ToolSourceContext.ToString() -> string! -override AgentCore.Application.Transcript.CallMessage.Equals(object? obj) -> bool -override AgentCore.Application.Transcript.CallMessage.GetHashCode() -> int -override AgentCore.Application.Transcript.CallMessage.ToString() -> string! -override sealed AgentCore.Application.Call.CallInput.Barge.Equals(AgentCore.Application.Call.CallInput? other) -> bool -override sealed AgentCore.Application.Call.CallInput.Keypress.Equals(AgentCore.Application.Call.CallInput? other) -> bool -override sealed AgentCore.Application.Call.CallInput.Utterance.Equals(AgentCore.Application.Call.CallInput? other) -> bool -override sealed AgentCore.Application.Tools.DeclaredTool.InvokeCoreAsync(Microsoft.Extensions.AI.AIFunctionArguments! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +virtual AgentCore.Application.Call.CallInput.EqualityContract.get -> System.Type! +virtual AgentCore.Application.Call.CallInput.Equals(AgentCore.Application.Call.CallInput? other) -> bool +virtual AgentCore.Application.Call.CallInput.PrintMembers(System.Text.StringBuilder! builder) -> bool +virtual AgentCore.Application.Tools.Binding.ToolBinding.Invoke(System.Text.Json.Nodes.JsonObject! arguments, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.ValueTask +~override AgentCore.Application.Providers.VendorSeam.Equals(object obj) -> bool +~override AgentCore.Application.Providers.VendorSeam.ToString() -> string diff --git a/src/AgentCore.Application/Runtime/CallSession.cs b/src/AgentCore.Application/Runtime/CallSession.cs index a59087b0..33d8bfcc 100644 --- a/src/AgentCore.Application/Runtime/CallSession.cs +++ b/src/AgentCore.Application/Runtime/CallSession.cs @@ -98,8 +98,6 @@ public sealed class CallSession : IConversationPort private readonly Clarifications _clarifications = new(); - private readonly IReadOnlyDictionary _vocabulary; - // Whether the running turn has already handed the host something to speak. One rule for both // run shapes: a run that has handed the host nothing cannot be the turn the caller was hearing, // so a barge-in in that window belongs to the turn that finished before it. A streaming turn @@ -124,8 +122,7 @@ internal CallSession( StateExtractor? extractor, TimeProvider timeProvider, CallObserverDispatcher? observers = null, - ILogger? logger = null, - VocabularyCache? vocabulary = null) + ILogger? logger = null) { ArgumentException.ThrowIfNullOrEmpty(callId); ArgumentNullException.ThrowIfNull(compiled); @@ -158,11 +155,7 @@ internal CallSession( // read that way, and neither of them ever ends a call by itself. _policy = compiled.Configuration.Policy is null ? null : compiled.CreatePolicy(guards); - // Sampled once, here, and handed to both the gate and the linker (K40): a refresh landing - // mid-call must not let the two sides of one write disagree about what the vocabulary was. - _vocabulary = vocabulary?.Snapshot() ?? new Dictionary(StringComparer.Ordinal); - - State = new StateDocument(compiled.Configuration, _policy?.Stage, _vocabulary); + State = new StateDocument(compiled.Configuration, _policy?.Stage); // The writers run in a fixed order, and this is its only record: const slots land before // any turn, then each turn applies tool results, the extractor, the clock fields and the @@ -669,9 +662,8 @@ private void Restore(CallSessionState stored) } // TryWrite answers false for two kinds of reason that cost an operator different things - // to fix — a slot the document no longer declares, and a value its type, enum: or - // vocabulary: gate now refuses — so the reason says which one happened rather than - // making them guess. + // to fix — a slot the document no longer declares, and a value its type or enum: gate + // now refuses — so the reason says which one happened rather than making them guess. Dropped( State.Configuration.State.ContainsKey(slot.Key) ? $"the slot '{slot.Key}' no longer takes the value it was stored with." @@ -782,10 +774,10 @@ private Turn BeginTurn(string userInput, AgentSession session, CallTurnOrigin? o Activity? activity = null; try { - // After both guards: a turn refused as terminal or already-running must not clear the - // per-turn mark out from under the turn actually in flight. Runs exactly once here, and - // never in EnterAmbients, which reopens per streaming step and would clear the mark - // several times inside one streaming turn (K41). + // After both guards: a turn refused as terminal or already-running must not drop the + // probe latch out from under the turn actually in flight. Runs exactly once here, and + // never in EnterAmbients, which reopens per streaming step and would drop the latch + // several times inside one streaming turn. _clarifications.BeginTurn(); // Behind both guards, because the withdrawal deletes: a turn refused for a terminal call or @@ -862,11 +854,10 @@ private void WithdrawSuperseded(AgentSession session, CallTurnOrigin? origin) return; } - // Without this, lastNamed and the pending list would survive a withdrawal that deleted the - // very turns they recorded, and silence both ambiguity channels forever about a question the - // caller edited away. The ask counters are deliberately untouched here: what the caller - // heard, they still heard, and clearing them would let the withdrawn segment buy a fresh - // maxAsks budget. + // Without this, lastNamed would survive a withdrawal that deleted the very turns it recorded, + // and silence the probe forever about a question the caller edited away. The ask counter is + // deliberately untouched here: what the caller heard, they still heard, and clearing it + // would let the withdrawn segment buy a fresh maxAsks budget. _clarifications.Withdraw(); // The turn index the event is filed under is the one about to run; the payload is what says @@ -1055,11 +1046,6 @@ private async Task CompleteTurnAsync( _events.RaiseDiagnostic(CallEventKind.EmptyReply, _time.GetUtcNow(), turn.Index); } - if (failure is null && !refused) - { - _clarifications.CommitAsks(reply); - } - // What this turn adds to the transcript. It is built here and written at the end of the // method, in one lock with the rest of what a late barge-in may still amend: the transcript // span, the ordinal the amendment must reference, and LastTurn itself. Nothing between here diff --git a/src/AgentCore.Application/Runtime/CallSessionFactory.cs b/src/AgentCore.Application/Runtime/CallSessionFactory.cs index 45ee76fe..abb04a49 100644 --- a/src/AgentCore.Application/Runtime/CallSessionFactory.cs +++ b/src/AgentCore.Application/Runtime/CallSessionFactory.cs @@ -25,8 +25,6 @@ public sealed class CallSessionFactory : ICallSessionFactory private readonly ILogger? _logger; - private readonly VocabularyCache? _vocabulary; - /// Creates the factory. public CallSessionFactory( CompiledAgent compiled, @@ -34,8 +32,7 @@ public CallSessionFactory( StateExtractor? extractor = null, TimeProvider? timeProvider = null, ILogger? logger = null, - IEnumerable? observers = null, - VocabularyCache? vocabulary = null) + IEnumerable? observers = null) { ArgumentNullException.ThrowIfNull(compiled); ArgumentNullException.ThrowIfNull(guards); @@ -45,7 +42,6 @@ public CallSessionFactory( _extractor = extractor; _time = timeProvider ?? TimeProvider.System; _logger = logger; - _vocabulary = vocabulary; // Copied, not held: the list is the caller's, and a caller that keeps adding to it after this // must not change what a session already built. The order is the caller's too — see @@ -58,34 +54,9 @@ public CallSessionFactory( /// The seam that resolves extractor.model. /// The extractor, or when the document declares none. public static StateExtractor? CreateExtractor(CompiledAgent compiled, IChatClientFactory chatClients) - => CreateExtractor(compiled, chatClients, new StateValueLinkers([])); - - /// Builds the extractor one document declares, over the linkers a host bound with UseStateValueLinkers. - /// The compiled agent. - /// The seam that resolves extractor.model. - /// - /// The linkers to resolve each vocabulary: slot's vocabulary.linker name against, - /// beyond the built-in exact, or for none. StateValueLinkers, - /// the registry type this builds, is to this assembly — this overload - /// is the public seam a host-facing project such as AspNetCore reaches it through, mirroring how - /// 's own constructor already takes the vocabulary cache by its - /// public type rather than an internal one. - /// - /// The extractor, or when the document declares none. - public static StateExtractor? CreateExtractor( - CompiledAgent compiled, IChatClientFactory chatClients, IEnumerable? linkers) - => CreateExtractor(compiled, chatClients, new StateValueLinkers(linkers ?? [])); - - /// Builds the extractor one document declares, over a vocabulary.linker registry (K12). - /// The compiled agent. - /// The seam that resolves extractor.model. - /// The registry the extractor resolves each vocabulary: slot's linker against. - /// The extractor, or when the document declares none. - internal static StateExtractor? CreateExtractor(CompiledAgent compiled, IChatClientFactory chatClients, StateValueLinkers linkers) { ArgumentNullException.ThrowIfNull(compiled); ArgumentNullException.ThrowIfNull(chatClients); - ArgumentNullException.ThrowIfNull(linkers); return compiled.Configuration.Extractor is { } declared ? new StateExtractor( @@ -94,8 +65,7 @@ public CallSessionFactory( .AsBuilder() .UseOpenTelemetry(configure: static client => client.EnableSensitiveData = false) .Use(static innerClient => new ModelFacingChatClient(innerClient)) - .Build(), - linkers) + .Build()) : null; } @@ -109,8 +79,7 @@ public CallSession Create(string? callId = null, CallSessionState? state = null) _extractor, _time, new CallObserverDispatcher(_observers, _logger), - _logger, - _vocabulary); + _logger); // Named, not applied. The session resumes on its first turn, where store 0's own copy // outranks this one — see the remarks on CallSession.Resume. diff --git a/src/AgentCore.Application/Runtime/ClarificationProvider.cs b/src/AgentCore.Application/Runtime/ClarificationProvider.cs deleted file mode 100644 index 305773a7..00000000 --- a/src/AgentCore.Application/Runtime/ClarificationProvider.cs +++ /dev/null @@ -1,134 +0,0 @@ -using AgentCore.Application.Configuration.Schema; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; - -namespace AgentCore.Application.Runtime; - -/// -/// Channel 1 of the ambiguity design (§7): the clarification, riding as a turn instruction. Bound -/// beside on every compiled agent whose document declares -/// providers.knowledge.ambiguity. -/// -/// -/// Uses the same session guard as : when -/// returns for the run's own session, this -/// is not the caller's own turn — a delegated kind: agent run, or a participant of a -/// graph: row whose session never carries the call's own history — and the channel emits -/// nothing and counts nothing (K29, K39). Because s run once per -/// RunAsync, above the framework's tool-call loop, this also means a nested tool call never -/// reaches this type at all; the K42 strip that hides from a nested -/// search exists for the probe, not for this provider. -/// -internal sealed class ClarificationProvider : AIContextProvider -{ - private readonly KnowledgeAmbiguityConfiguration _ambiguity; - - private readonly IReadOnlyList _fromState; - - private readonly IReadOnlyDictionary _slotDescriptions; - - /// Creates the provider for one document's providers.knowledge block. - /// How many candidates and how many asks the document allows. - /// - /// The scope's fromState slots, in declaration order — the same order §8 step 4 walks, so - /// a deployer reads one ordering rather than two. - /// - /// - /// Each slot's description, or for a - /// slot the document describes with nothing but its own name. - /// - internal ClarificationProvider( - KnowledgeAmbiguityConfiguration ambiguity, - IReadOnlyList fromState, - IReadOnlyDictionary slotDescriptions) - { - ArgumentNullException.ThrowIfNull(ambiguity); - ArgumentNullException.ThrowIfNull(fromState); - ArgumentNullException.ThrowIfNull(slotDescriptions); - - _ambiguity = ambiguity; - _fromState = fromState; - _slotDescriptions = slotDescriptions; - } - - /// - protected override ValueTask ProvideAIContextAsync( - InvokingContext context, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(context); - - // K38: a deployment that configured itself never to ask must never reach the loop below — - // at maxAsks 0 or below, step 2's namedAsks < maxAsks test is false on the very first slot, - // which would otherwise let step 3's reset ask exactly one question in the one deployment - // that asked for none. - if (_ambiguity.MaxAsks <= 0 || TurnContextScope.For(context.Session) is null) - { - return new(new AIContext()); - } - - var ambients = TurnAmbients.Current; - if (ambients?.Clarifications is not { } clarifications || ambients.State is not { } state) - { - return new(new AIContext()); - } - - List messages = []; - - foreach (var slot in _fromState) - { - if (!state.IsUnfilled(slot)) - { - continue; - } - - var snapshot = clarifications.Read(slot); - if (snapshot.Pending is not { Count: > 0 } pending) - { - continue; - } - - if (Speak(clarifications, slot, pending, snapshot, first: messages.Count == 0) is { } text) - { - messages.Add(new ChatMessage(ChatRole.System, text)); - } - } - - return new(new AIContext { Messages = messages.Count > 0 ? messages : null }); - } - - /// §7's four-step evaluation for one pending slot. - /// The sentence to speak, or when this slot stays silent. - private string? Speak( - Clarifications clarifications, - string slot, - IReadOnlyList pending, - Clarifications.SlotSnapshot snapshot, - bool first) - { - var wouldName = Clarifications.LastNamed.For(pending, _ambiguity.MaxCandidates); - - // §7 step 1 (K37): the caller has already been asked exactly this. - if (wouldName.Names(snapshot.LastNamed)) - { - return null; - } - - var description = ClarificationText.DescriptionOf(slot, _slotDescriptions); - - if (snapshot.NamedAsks < _ambiguity.MaxAsks) - { - clarifications.Ask(slot, wouldName, spendsReset: false); - return ClarificationText.Instruction(description, pending, _ambiguity.MaxCandidates, first); - } - - // §7 step 3: namedAsks is at the cap and, having failed step 1, what would be named has - // changed. The one reset is spent here. - if (!snapshot.ResetSpent) - { - clarifications.Ask(slot, wouldName, spendsReset: true); - return ClarificationText.Instruction(description, pending, _ambiguity.MaxCandidates, first); - } - - return null; - } -} diff --git a/src/AgentCore.Application/Runtime/ClarificationText.cs b/src/AgentCore.Application/Runtime/ClarificationText.cs index 903333ea..0249506a 100644 --- a/src/AgentCore.Application/Runtime/ClarificationText.cs +++ b/src/AgentCore.Application/Runtime/ClarificationText.cs @@ -1,19 +1,17 @@ namespace AgentCore.Application.Runtime; /// -/// The sentences §7 specifies for both ambiguity channels. One rule, two wordings: channel 1 rides a -/// standing turn instruction and must never claim to suppress a card the search already returned; -/// channel 2 rides an empty search result and may say so plainly. +/// The sentence §8 specifies for the knowledge probe's note. It rides an empty search result, so it +/// may say plainly that the answer is not yet known. /// internal static class ClarificationText { - /// Reads the wording a slot is described by, for either channel's sentence. + /// Reads the wording a slot is described by. /// The slot's name. /// Each slot's configured description, by name. /// /// The configured description, or the slot's own name when the document describes it with - /// nothing else. Both channels resolve through here, so the two sentences never disagree about - /// what the caller is being asked about. + /// nothing else. /// internal static string DescriptionOf(string slot, IReadOnlyDictionary descriptions) { @@ -25,52 +23,13 @@ internal static string DescriptionOf(string slot, IReadOnlyDictionaryRenders channel 1's sentence: the clarification, as a turn instruction (K29). + /// Renders the probe's note, as a search result. /// /// The slot's description, or the slot name when the caller has none — used as an /// apposition, because a deployer's description is a whole sentence. /// /// The slot's pending candidate set. /// Above this many candidates, the list is omitted. - /// - /// Whether this is the first such message the turn speaks. A second opens "Another thing…" rather - /// than repeating "One thing…", so two pending slots do not read as the same question twice. - /// - /// The sentence. - internal static string Instruction( - string description, IReadOnlyList candidates, int maxCandidates, bool first) - { - ArgumentNullException.ThrowIfNull(description); - ArgumentNullException.ThrowIfNull(candidates); - - if (candidates.Count == 1) - { - var confirm = first ? "One thing is not yet confirmed" : "Another thing is not yet confirmed"; - return $"{confirm}: {description} Everything found is for {candidates[0]}. " - + "Answer what the caller just said; where that calls for advice specific to it, ask the " - + "caller first whether that is what they have."; - } - - var known = first ? "One thing is not yet known" : "Another thing is not yet known"; - - if (candidates.Count > maxCandidates) - { - return $"{known}: {description} Answer what the caller just said; where that calls for advice " - + "specific to one, ask the caller first."; - } - - return $"{known}: {description} It is one of {JoinAlternatives(candidates)}. Answer what the caller " - + "just said; where that calls for advice specific to one, ask the caller which first. Anything " - + "that applies to all of them is still fair game."; - } - - /// Renders channel 2's sentence: the probe's note, as a search result. - /// - /// The slot's description, or the slot name when the caller has none — an apposition, for - /// the same reason 's does. - /// - /// The slot's pending candidate set. - /// Above this many candidates, the list is omitted. /// The sentence. internal static string Note(string description, IReadOnlyList candidates, int maxCandidates) { @@ -88,9 +47,7 @@ internal static string Note(string description, IReadOnlyList candidates if (candidates.Count > maxCandidates) { - // "which" needs the list as its antecedent, the same way channel 1's over-cap form drops - // "Anything that applies to all of them" rather than leave "them" pointing at a list that - // is no longer there. + // "which" needs the list as its antecedent, so the over-cap form drops it. return $"{decides}: {description} Ask the caller, and do not answer from the knowledge base " + "about it until they say."; } @@ -98,14 +55,4 @@ internal static string Note(string description, IReadOnlyList candidates return $"{decides}: {description} It could be: {string.Join(", ", candidates)}. Ask the caller " + "which, and do not answer from the knowledge base about it until they say."; } - - /// - /// Joins candidates as alternatives — "X or Y", or "X, Y, or Z" — the phrasing channel 1's "It is - /// one of" reads as. Channel 2's "It could be:" is a plain list instead (see ), - /// which is why the two channels do not share this helper. - /// - private static string JoinAlternatives(IReadOnlyList candidates) - => candidates.Count == 2 - ? $"{candidates[0]} or {candidates[1]}" - : string.Join(", ", candidates.Take(candidates.Count - 1)) + ", or " + candidates[^1]; } diff --git a/src/AgentCore.Application/Runtime/Clarifications.cs b/src/AgentCore.Application/Runtime/Clarifications.cs index ef005ad2..28aefa18 100644 --- a/src/AgentCore.Application/Runtime/Clarifications.cs +++ b/src/AgentCore.Application/Runtime/Clarifications.cs @@ -4,8 +4,8 @@ namespace AgentCore.Application.Runtime; /// -/// One call's memory of what its ambiguity channels have asked and named, and the per-turn latch -/// that lets several search-tool calls in one turn share a single probe (K36, K41, K43). +/// One call's memory of what the knowledge probe has asked and named, and the per-turn latch that +/// lets several search-tool calls in one turn share a single probe (K36, K43). /// /// /// Constructed once by and put on as the same @@ -14,7 +14,7 @@ namespace AgentCore.Application.Runtime; /// instance at once, so every read and every write takes — there is no member on /// this type that touches a field without it. Reads go through and writes through /// , each taking the lock once for the whole snapshot or transition, so a -/// concurrent participant can never observe a slot half way through §7 or §8's compound updates. +/// concurrent participant can never observe a slot half way through §8's compound updates. /// internal sealed class Clarifications { @@ -24,13 +24,12 @@ internal sealed class Clarifications private Probe? _probe; - /// Reads a consistent snapshot of one slot's six fields, as of one lock acquisition. + /// Reads a consistent snapshot of one slot's two fields, as of one lock acquisition. /// The slot's name. /// - /// The snapshot, with this turn's staged ask folded over what is committed (see - /// ). Every field in it was read under the same lock acquisition, so a - /// concurrent is either fully before it or fully after it — never half of - /// one and half of the other. + /// The snapshot. Every field in it was read under the same lock acquisition, so a concurrent + /// is either fully before it or fully after it — never half of one and half + /// of the other. /// internal SlotSnapshot Read(string name) { @@ -65,70 +64,6 @@ internal void Update(string name, Action mutate) } } - /// - /// Records channel 1's §7 transition for one slot, to be kept only once the turn it belongs to - /// has actually answered the caller. - /// - /// The slot's name. - /// What this ask names to the caller (K37). - /// - /// Whether this is §7 step 3's one reset. A reset returns namedAsks to 1 rather than 0, - /// because 0 would buy an extra ask and make the bound 2 x maxAsks + 1. - /// - /// - /// shows the ask at once, because §7 step 1 and the probe's K41 skip both - /// have to act on it inside this same turn. It becomes permanent only at - /// , which the turn calls once it knows the caller heard the agent's own - /// words. A turn that ended in the fallback reply never put the question, so the next - /// drops the ask instead: charging it would silence that slot for the - /// rest of the call over a question nobody was asked. - /// - internal void Ask(string name, LastNamed named, bool spendsReset) - { - ArgumentNullException.ThrowIfNull(name); - - lock (_gate) - { - var state = GetOrAdd(name); - var current = Snapshot(state); - - state.StagedAsk = new StagedAsk( - named, - spendsReset ? 1 : current.NamedAsks + 1, - current.ResetSpent || spendsReset); - - state.AskedThisTurn = true; - } - } - - /// Makes the asks this turn staged and put permanent (see ). - /// The words the caller heard, which decide which staged asks were put. - internal void CommitAsks(string reply) - { - ArgumentNullException.ThrowIfNull(reply); - - lock (_gate) - { - foreach (var state in _slots.Values) - { - if (state.StagedAsk is not { } ask) - { - continue; - } - - if (!SpokenAsk.NamedIn(reply, ask.Named)) - { - continue; - } - - state.LastNamed = ask.Named; - state.NamedAsks = ask.NamedAsks; - state.ResetSpent = ask.ResetSpent; - state.StagedAsk = null; - } - } - } - /// /// Claims this turn's one probe search. Several search-tool calls in one turn, or several graph /// participants sharing this call, race here, and exactly one wins. @@ -161,33 +96,25 @@ internal Probe ClaimProbe() } /// - /// Opens a new turn: clears K41's per-turn mark and any uncommitted ask on every slot, and drops - /// the turn's probe latch, so a fresh turn claims and replays its own probe rather than the turn - /// before it. + /// Opens a new turn: drops the turn's probe latch, so a fresh turn claims and replays its own + /// probe rather than the turn before it. /// /// /// Must run exactly once per turn, from CallSession.BeginTurn and nowhere else. - /// CallSession.EnterAmbients reopens its ambient scope once per streaming step, and - /// clearing there instead would void K41's mark several times inside one streaming turn. + /// CallSession.EnterAmbients reopens its ambient scope once per streaming step. /// internal void BeginTurn() { lock (_gate) { - foreach (var state in _slots.Values) - { - state.AskedThisTurn = false; - state.StagedAsk = null; - } - _probe = null; } } /// - /// Takes back what an edit-and-resend withdrew: every slot's pending list and its record of what - /// was last named to the caller. The ask counters are left alone — the caller heard what they - /// heard, and clearing them would let the withdrawn segment buy a fresh maxAsks budget. + /// Takes back what an edit-and-resend withdrew: every slot's record of what was last named to + /// the caller. The ask counter is left alone — the caller heard what they heard, and clearing it + /// would let the withdrawn segment buy a fresh maxAsks budget. /// internal void Withdraw() { @@ -195,7 +122,6 @@ internal void Withdraw() { foreach (var state in _slots.Values) { - state.Pending = null; state.LastNamed = LastNamed.None; } } @@ -214,19 +140,12 @@ internal IReadOnlyDictionary Spent() foreach (var (name, state) in _slots) { - // Committed only. A staged ask belongs to a turn that has not yet answered the - // caller, and a snapshot taken mid-turn must not carry a charge that turn may drop. - if (state.ProbeAsks == 0 && state.NamedAsks == 0 && !state.ResetSpent) + if (state.ProbeAsks == 0) { continue; } - spent[name] = new CallClarificationState - { - ProbeAsks = state.ProbeAsks, - NamedAsks = state.NamedAsks, - ResetSpent = state.ResetSpent, - }; + spent[name] = new CallClarificationState { ProbeAsks = state.ProbeAsks }; } return spent; @@ -236,10 +155,10 @@ internal IReadOnlyDictionary Spent() /// Puts back what an earlier session of this call spent of its ask budget. /// What read from that session. /// - /// The pending lists and the record of what was last named are deliberately not restored: they - /// belong to a turn the reconnected caller is no longer in. Only the budget has to survive, and - /// for the reason gives — a caller who drops and comes back must not buy - /// a fresh maxAsks and hear the same question all over again. + /// The record of what was last named is deliberately not restored: it belongs to a turn the + /// reconnected caller is no longer in. Only the budget has to survive, and for the reason + /// gives — a caller who drops and comes back must not buy a fresh + /// maxAsks and hear the same question all over again. /// internal void RestoreSpent(IReadOnlyDictionary spent) { @@ -249,10 +168,7 @@ internal void RestoreSpent(IReadOnlyDictionary s { foreach (var (name, stored) in spent) { - var state = GetOrAdd(name); - state.ProbeAsks = stored.ProbeAsks; - state.NamedAsks = stored.NamedAsks; - state.ResetSpent = stored.ResetSpent; + GetOrAdd(name).ProbeAsks = stored.ProbeAsks; } } } @@ -269,18 +185,7 @@ private SlotState GetOrAdd(string name) return state; } - private static SlotSnapshot Snapshot(SlotState state) - { - var ask = state.StagedAsk; - - return new( - state.Pending, - state.EffectiveLastNamed, - state.ProbeAsks, - ask?.NamedAsks ?? state.NamedAsks, - ask?.ResetSpent ?? state.ResetSpent, - state.AskedThisTurn); - } + private static SlotSnapshot Snapshot(SlotState state) => new(state.LastNamed, state.ProbeAsks); /// What decided the wildcard a slot's last named record holds. internal enum LastNamedKind @@ -295,9 +200,6 @@ internal enum LastNamedKind TooMany, } - /// One turn's channel-1 ask, staged until the turn answers the caller (see ). - internal sealed record StagedAsk(LastNamed Named, int NamedAsks, bool ResetSpent); - /// /// One turn's probe latch, held by the caller that claimed it. /// @@ -369,14 +271,12 @@ internal static LastNamed Of(IReadOnlySet values) return new LastNamed(LastNamedKind.Set, values); } - /// What a channel would record for one candidate set (K37). - /// The candidates that channel is about to name. + /// What the probe would record for one candidate set (K37). + /// The candidates the probe is about to name. /// The document's maxCandidates. /// /// when the set is over the cap, so no list is spoken; otherwise the - /// exact set. Both ambiguity channels record through here rather than each deciding the cap - /// for itself, so channel 1's record and the probe's are always comparable — including the - /// ordinal comparer relies on. + /// exact set, under the ordinal comparer relies on. /// internal static LastNamed For(IReadOnlyCollection candidates, int maxCandidates) { @@ -399,14 +299,8 @@ internal bool Names(LastNamed other) => Kind == other.Kind && (Kind != LastNamedKind.Set || Values!.SetEquals(other.Values!)); } - /// A consistent, point-in-time copy of one slot's six fields (see ). - internal readonly record struct SlotSnapshot( - IReadOnlyList? Pending, - LastNamed LastNamed, - int ProbeAsks, - int NamedAsks, - bool ResetSpent, - bool AskedThisTurn); + /// A consistent, point-in-time copy of one slot's two fields (see ). + internal readonly record struct SlotSnapshot(LastNamed LastNamed, int ProbeAsks); /// /// One slot's mutable ambiguity state. Read through and written through @@ -415,29 +309,8 @@ internal readonly record struct SlotSnapshot( /// internal sealed class SlotState { - internal IReadOnlyList? Pending; - internal LastNamed LastNamed = LastNamed.None; internal int ProbeAsks; - - internal int NamedAsks; - - internal bool ResetSpent; - - internal bool AskedThisTurn; - - /// This turn's uncommitted channel-1 ask, or null when it has not asked. - internal StagedAsk? StagedAsk; - - /// - /// What the caller has most recently been told, this turn's uncommitted ask included. - /// - /// - /// The field alone is the committed record and lags a turn that has asked but not yet - /// answered. A writer inside an callback that has to compare against what - /// the caller would hear must read this, not . - /// - internal LastNamed EffectiveLastNamed => StagedAsk is { } ask ? ask.Named : LastNamed; } } diff --git a/src/AgentCore.Application/Runtime/SpokenAsk.cs b/src/AgentCore.Application/Runtime/SpokenAsk.cs deleted file mode 100644 index f359b393..00000000 --- a/src/AgentCore.Application/Runtime/SpokenAsk.cs +++ /dev/null @@ -1,41 +0,0 @@ -using AgentCore.Application.State; - -namespace AgentCore.Application.Runtime; - -/// -/// Whether a turn's own reply actually put the question channel 1 staged for it. -/// -internal static class SpokenAsk -{ - /// Whether put the question staged. - /// The words the caller heard. - /// What the staged ask offered. - /// - /// where the reply names one of the offered values. A record naming no - /// values — the over-cap form, whose instruction lists none — carries nothing to look for, so it - /// counts as asked rather than being dropped on every turn alike. - /// - internal static bool NamedIn(string reply, Clarifications.LastNamed named) - { - ArgumentNullException.ThrowIfNull(reply); - - if (named.Kind != Clarifications.LastNamedKind.Set || named.Values is not { } values) - { - return true; - } - - var folded = VocabularyFold.Fold(reply); - - foreach (var value in values) - { - var candidate = VocabularyFold.Fold(value); - - if (candidate.Length > 0 && folded.Contains(candidate, StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } -} diff --git a/src/AgentCore.Application/State/ExactStateValueLinker.cs b/src/AgentCore.Application/State/ExactStateValueLinker.cs deleted file mode 100644 index f22680c6..00000000 --- a/src/AgentCore.Application/State/ExactStateValueLinker.cs +++ /dev/null @@ -1,343 +0,0 @@ -using System.Globalization; -using System.Runtime.CompilerServices; -using System.Text; - -namespace AgentCore.Application.State; - -/// -/// The exact linker (K9): fold, bounded join, exact match, span resolution. There is no -/// trigram or embedding fallback — a near-tie leaves the slot unfilled and names the candidates -/// (K11) rather than guessing. -/// -/// -/// Tokenising is rather than a second copy of K31's -/// predicate; the vocabulary's fold-to-original map is built once at boot by -/// , so this type never folds a vocabulary value or checks it -/// for a collision itself. -/// -public sealed class ExactStateValueLinker : IStateValueLinker -{ - /// The longest run of tokens one candidate spelling may join. - private const int MaxRun = 4; - - /// - /// Separator runes that always break a join, regardless of whitespace. An enumerated list, not - /// a Unicode class: Po contains . and /, which §6 needs to join. - /// - private static readonly HashSet PhraseBreaks = [.. ",;:!?".EnumerateRunes()]; - - /// - /// One ordinally sorted copy of each view's normalised keys, memoised for as long as the view - /// itself lives. A view is immutable and a refresh swaps the reference (section 5), so an entry - /// can never describe a vocabulary that has since changed. - /// - private static readonly ConditionalWeakTable KeysInOrder = new(); - - /// - public string Name => "exact"; - - /// - public LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet lastNamed) - { - ArgumentNullException.ThrowIfNull(mention); - ArgumentNullException.ThrowIfNull(vocabulary); - ArgumentNullException.ThrowIfNull(lastNamed); - - var (tokens, separators) = VocabularyFold.Tokenize(mention); - var candidates = BuildCandidates(tokens, separators); - var table = vocabulary.NormalisedToOriginal; - - // Driven by the candidates, not by the vocabulary: a mention yields at most four spellings - // per token, where the vocabulary may hold thousands of values. The intersection is the same - // either way round. - Dictionary> hits = new(StringComparer.Ordinal); - foreach (var (key, spans) in candidates) - { - if (table.ContainsKey(key)) - { - hits[key] = spans; - } - } - - var kept = Resolve(hits); - - if (kept.Count == 0) - { - return new LinkResult(LinkOutcome.NoMatch, []); - } - - if (kept.Count > 1) - { - return new LinkResult( - LinkOutcome.Ambiguous, - kept.Select(key => table[key]).Order(StringComparer.Ordinal).ToList()); - } - - var only = kept[0]; - var original = table[only]; - - if (lastNamed.Contains(original)) - { - return new LinkResult(LinkOutcome.Linked, [original]); - } - - var prefixedBy = PrefixedSiblings(vocabulary, only, Extensions(candidates, hits[only])); - - if (prefixedBy.Count == 0) - { - return new LinkResult(LinkOutcome.Linked, [original]); - } - - prefixedBy.Add(original); - prefixedBy.Sort(StringComparer.Ordinal); - return new LinkResult(LinkOutcome.Ambiguous, prefixedBy); - } - - /// - /// Every value whose normalised key has as a strict prefix and that - /// does not rule out, in the collection's own spelling. - /// - private static List PrefixedSiblings( - VocabularyView vocabulary, string key, IReadOnlyList extensions) - { - var ordered = KeysInOrder.GetValue( - vocabulary, - view => [.. view.NormalisedToOriginal.Keys.Order(StringComparer.Ordinal)]); - - var found = Array.BinarySearch(ordered, key, StringComparer.Ordinal); - var scan = found < 0 ? ~found : found + 1; - - List siblings = []; - for (; scan < ordered.Length && ordered[scan].StartsWith(key, StringComparison.Ordinal); scan++) - { - if (!RuledOut(ordered[scan], key, extensions)) - { - siblings.Add(vocabulary.NormalisedToOriginal[ordered[scan]]); - } - } - - return siblings; - } - - /// - /// Every candidate spelling the mention offers that begins where the matched value begins and - /// runs past its end — what the caller spelled around the hit, rather than what the collection - /// holds. - /// - /// Every spelling the mention admits, from . - /// The token spans the matched value was read from. - /// The extended spellings, each carrying the matched key as a strict prefix. - private static List Extensions( - Dictionary> candidates, - HashSet<(int Start, int End)> matched) - { - List extensions = []; - - foreach (var (key, spans) in candidates) - { - if (spans.Any(span => matched.Any(hit => hit.Start == span.Start && span.End > hit.End))) - { - extensions.Add(key); - } - } - - return extensions; - } - - /// - /// Whether the caller's own spelling rules this sibling out: they spelled a peer of the - /// sibling's own tail — as long, and of the same character class — that is not it. - /// - /// The sibling's normalised key. - /// The matched value's normalised key, a strict prefix of both sides. - /// What the caller spelled past the match. - /// to drop the sibling. - private static bool RuledOut(string sibling, string key, IReadOnlyList extensions) - { - var tail = sibling[key.Length..]; - var ruledOut = false; - - foreach (var extension in extensions) - { - // The caller is still spelling toward this sibling, so nothing they said rules it out — - // and no other extension of the same mention can overturn that. - if (sibling.StartsWith(extension, StringComparison.Ordinal)) - { - return false; - } - - ruledOut = ruledOut || IsPeer(extension[key.Length..], tail); - } - - return ruledOut; - } - - /// Whether two tails are alternatives: the same length, and both all numbers or both all letters. - private static bool IsPeer(string left, string right) - => left.Length == right.Length - && ((All(left, IsNumber) && All(right, IsNumber)) || (All(left, Rune.IsLetter) && All(right, Rune.IsLetter))); - - private static bool All(string text, Func predicate) - { - if (text.Length == 0) - { - return false; - } - - foreach (var rune in text.EnumerateRunes()) - { - if (!predicate(rune)) - { - return false; - } - } - - return true; - } - - /// - /// Discards a hit whose every span sits inside a span of some longer hit (K10) — tested per - /// span, so different spans of one hit may be swallowed by different longer hits, and no longer - /// hit need begin with the shorter one. - /// - private static List Resolve(Dictionary> hits) - { - List kept = []; - - foreach (var (hit, spans) in hits) - { - var longer = hits.Keys.Where(other => other.Length > hit.Length).ToList(); - var swallowed = longer.Count > 0 - && spans.All(span => longer.Any(other => hits[other].Any(outer => Contains(outer, span)))); - - if (!swallowed) - { - kept.Add(hit); - } - } - - return kept; - } - - private static bool Contains((int Start, int End) outer, (int Start, int End) inner) - => outer.Start <= inner.Start && inner.End <= outer.End; - - /// - /// Builds every candidate spelling §6 step 2 admits: every single token, and every contiguous - /// run of up to tokens whose separators are all joinable. Each run is tested - /// on its own — a run that fails does not stop a longer run starting at the same token. - /// - /// The mention's tokens, in order. - /// The runs between adjacent tokens — one fewer entry than . - /// The map from candidate spelling to every token span that produced it. - internal static Dictionary> BuildCandidates( - IReadOnlyList tokens, IReadOnlyList separators) - { - Dictionary> candidates = new(StringComparer.Ordinal); - - for (var start = 0; start < tokens.Count; start++) - { - var limit = Math.Min(start + MaxRun, tokens.Count); - - for (var end = start; end < limit; end++) - { - var run = new List(end - start + 1); - for (var index = start; index <= end; index++) - { - run.Add(tokens[index]); - } - - // Each run is tested on its own, against its own full token list — never by - // extending a shorter run's verdict. A separator's joinability can depend on a - // token elsewhere in the run (the digit rule), so a run of 3 can join where its - // own 2-token prefix would not. - if (end > start && !IsJoinable(separators, start, end, run)) - { - continue; - } - - var key = string.Concat(run); - if (!candidates.TryGetValue(key, out var spans)) - { - candidates[key] = spans = []; - } - - spans.Add((start, end)); - } - } - - return candidates; - } - - /// - /// Whether every separator inside [start, end) joins the whole run, by §6 step 2's three - /// rules in order: a phrase-breaking rune never joins; otherwise a separator with no whitespace - /// always joins; otherwise the run joins only when - /// allows it. - /// - private static bool IsJoinable(IReadOnlyList separators, int start, int end, IReadOnlyList run) - { - // The third rule reads the run and not the separator, so its verdict is the same for every - // separator here: taken at most once, and only once a separator actually needs it. - bool? runJoins = null; - - for (var index = start; index < end; index++) - { - var hasWhitespace = false; - - foreach (var rune in separators[index].EnumerateRunes()) - { - if (PhraseBreaks.Contains(rune) || Rune.IsControl(rune)) - { - return false; - } - - hasWhitespace = hasWhitespace || Rune.IsWhiteSpace(rune); - } - - if (!hasWhitespace) - { - continue; - } - - runJoins ??= RunJoinsAcrossWhitespace(run); - if (!runJoins.Value) - { - return false; - } - } - - return true; - } - - /// - /// §6 step 2's third rule: a whitespace separator joins the run only when the run carries a - /// digit, or every token in it is at least three runes long. - /// - private static bool RunJoinsAcrossWhitespace(IReadOnlyList run) - { - var allLongEnough = true; - - foreach (var token in run) - { - var runes = 0; - - foreach (var rune in token.EnumerateRunes()) - { - if (IsNumber(rune)) - { - return true; - } - - runes++; - } - - allLongEnough = allLongEnough && runes >= 3; - } - - return allLongEnough; - } - - private static bool IsNumber(Rune rune) => Rune.GetUnicodeCategory(rune) is - UnicodeCategory.DecimalDigitNumber or UnicodeCategory.LetterNumber or UnicodeCategory.OtherNumber; -} diff --git a/src/AgentCore.Application/State/IStateValueLinker.cs b/src/AgentCore.Application/State/IStateValueLinker.cs deleted file mode 100644 index 391bce44..00000000 --- a/src/AgentCore.Application/State/IStateValueLinker.cs +++ /dev/null @@ -1,23 +0,0 @@ -namespace AgentCore.Application.State; - -/// -/// Turns a caller's loose mention of a vocabulary: slot's value into the collection's own -/// spelling, or reports that it cannot be resolved without asking (K11, K12). -/// -public interface IStateValueLinker -{ - /// Gets the name a slot's vocabulary.linker resolves this linker by. - string Name { get; } - - /// Links one extractor mention against one slot's vocabulary. - /// The extractor's raw mention text. - /// The slot's vocabulary, sampled once at call open (K40). - /// - /// The candidate set actually spoken to the caller for this slot in this call — K37's record, - /// in the collection's own spelling — empty when nothing has been. Never a pending list a - /// channel installed but stayed silent about. A set, not a list: both ambiguity channels record - /// one under , and a linker only ever asks it for membership. - /// - /// The verdict. - LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet lastNamed); -} diff --git a/src/AgentCore.Application/State/LinkResult.cs b/src/AgentCore.Application/State/LinkResult.cs deleted file mode 100644 index e7a9a959..00000000 --- a/src/AgentCore.Application/State/LinkResult.cs +++ /dev/null @@ -1,55 +0,0 @@ -namespace AgentCore.Application.State; - -/// The three outcomes an can return (§6 step 4). -public enum LinkOutcome -{ - /// Nothing in the vocabulary matched. The slot stays unfilled. - NoMatch, - - /// Exactly one value matched, with no unresolved tie. - Linked, - - /// More than one value is a plausible match, and none can be preferred (K11). - Ambiguous, -} - -/// One linker verdict. -/// Which of the three outcomes this is. -/// -/// The matching values, in the collection's own spelling, sorted with -/// . -/// -/// -/// The candidate count does not match the outcome. is public, so a -/// host linker is arbitrary code; checking here makes the count an invariant the extractor can -/// index on rather than a promise it has to re-test. -/// -public sealed record LinkResult(LinkOutcome Outcome, IReadOnlyList Candidates) -{ - /// - /// Gets the matching values, in the collection's own spelling, sorted with - /// . carries none, - /// exactly one, and at - /// least two. - /// - public IReadOnlyList Candidates { get; init; } = Checked(Outcome, Candidates); - - private static IReadOnlyList Checked(LinkOutcome outcome, IReadOnlyList candidates) - { - ArgumentNullException.ThrowIfNull(candidates); - - var holds = outcome switch - { - LinkOutcome.NoMatch => candidates.Count == 0, - LinkOutcome.Linked => candidates.Count == 1, - LinkOutcome.Ambiguous => candidates.Count > 1, - _ => false, - }; - - return holds - ? candidates - : throw new ArgumentException( - $"a {outcome} verdict cannot carry {candidates.Count} candidates.", - nameof(candidates)); - } -} diff --git a/src/AgentCore.Application/State/StateDocument.cs b/src/AgentCore.Application/State/StateDocument.cs index c5d34041..424c8eed 100644 --- a/src/AgentCore.Application/State/StateDocument.cs +++ b/src/AgentCore.Application/State/StateDocument.cs @@ -30,43 +30,22 @@ namespace AgentCore.Application.State; /// public sealed class StateDocument { - private static readonly IReadOnlyDictionary EmptyVocabulary = - new Dictionary(StringComparer.Ordinal); - private readonly ConcurrentDictionary _written = new(StringComparer.Ordinal); - private readonly IReadOnlyDictionary _vocabulary; - /// Creates the state of one call from the declared slots. /// The loaded document. /// The stage the call starts in, or when there is no policy. - /// - /// Every vocabulary: slot's domain, sampled once at call open (K40), or - /// when the caller has none to give. A slot missing from this map - /// refuses every write, the same as a slot missing from an enum:. - /// - public StateDocument( - AgentCoreConfiguration configuration, - string? stage = null, - IReadOnlyDictionary? vocabulary = null) + public StateDocument(AgentCoreConfiguration configuration, string? stage = null) { ArgumentNullException.ThrowIfNull(configuration); Configuration = configuration; Stage = stage ?? configuration.Policy?.Initial ?? string.Empty; - _vocabulary = vocabulary ?? EmptyVocabulary; } /// Gets the document this state was declared by. public AgentCoreConfiguration Configuration { get; } - /// - /// Gets every vocabulary: slot's domain, as it was sampled at call open (K40). The gate - /// below and 's linker read this one map, so neither can hold a - /// domain the other does not. - /// - internal IReadOnlyDictionary Vocabulary => _vocabulary; - /// Gets or sets the reserved stage slot. The policy runtime owns it. public string Stage { get; set; } @@ -146,15 +125,6 @@ public bool TryWrite(string slot, JsonNode? value) return false; } - // K1/K8: vocabulary: is enum:'s large-domain sibling, read from a provider instead of - // hand-written. The gate is the same shape — a slot missing from the snapshot (never - // sampled, or a refresh that never landed) refuses every value, exactly as an enum: slot - // with no members would. - if (declared.Vocabulary is not null && !IsVocabularyMember(slot, coerced)) - { - return false; - } - _written[slot] = coerced; return true; } @@ -176,17 +146,6 @@ private static bool IsMember(IReadOnlyList members, JsonNode? value) return false; } - // Through the fold map rather than a walk of Originals: a value is a member exactly when it - // folds to a key the collection stores and that key maps back to this same spelling, which is - // one dictionary probe instead of a scan of up to maxValues entries per write. It also reads - // the one map the linker reads, so the gate and the linker cannot disagree about the domain. - private bool IsVocabularyMember(string slot, JsonNode? value) - => _vocabulary.TryGetValue(slot, out var view) - && value is JsonValue text - && text.TryGetValue(out var written) - && view.NormalisedToOriginal.TryGetValue(VocabularyFold.Fold(written), out var original) - && string.Equals(original, written, StringComparison.Ordinal); - /// Takes a snapshot the guards read. It holds every declared slot and the three reserved slots. /// The snapshot. It does not change when the document changes. public IReadOnlyDictionary Snapshot() diff --git a/src/AgentCore.Application/State/StateExtractor.cs b/src/AgentCore.Application/State/StateExtractor.cs index a0f58f9a..777b8b81 100644 --- a/src/AgentCore.Application/State/StateExtractor.cs +++ b/src/AgentCore.Application/State/StateExtractor.cs @@ -38,31 +38,17 @@ public sealed class StateExtractor + "Leave every other field null. Null means you did not answer, and it keeps the earlier value. " + "Never guess, and never speak to the caller."; - private static readonly IReadOnlySet NothingNamed = new HashSet(StringComparer.Ordinal); - private readonly IChatClient _chatClient; private readonly ChatOptions _options; - private readonly StateValueLinkers _linkers; /// Creates the extractor for one loaded document. /// The loaded document. /// The model named by extractor.model. /// The document declares no extractor: section. public StateExtractor(AgentCoreConfiguration configuration, IChatClient chatClient) - : this(configuration, chatClient, new StateValueLinkers([])) - { - } - - /// Creates the extractor with a linker registry (K12) for its vocabulary: slots. - /// The loaded document. - /// The model named by extractor.model. - /// The registry StateExtractor.Write resolves each slot's vocabulary.linker against. - /// The document declares no extractor: section. - internal StateExtractor(AgentCoreConfiguration configuration, IChatClient chatClient, StateValueLinkers linkers) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(chatClient); - ArgumentNullException.ThrowIfNull(linkers); if (configuration.Extractor is null) { @@ -72,7 +58,6 @@ internal StateExtractor(AgentCoreConfiguration configuration, IChatClient chatCl Configuration = configuration; _chatClient = chatClient; - _linkers = linkers; SlotNames = [.. configuration.State .Where(entry => entry.Value.Writer == StateWriter.Extractor) .Select(entry => entry.Key)]; @@ -171,11 +156,8 @@ public Task ExtractAsync( return ExtractAsync(state, transcript, new Clarifications(), cancellationToken); } - /// - /// Runs one extractor call against the finished turn, then writes what it answered — the linker's - /// path over a vocabulary: slot's free text included (§6). - /// - /// The state of one call, which carries the vocabulary the linker resolves against. + /// Runs one extractor call against the finished turn, then writes what it answered. + /// The state of one call. /// The finished turn, newest last. /// The call's ambiguity holder. reads and writes it. /// Cancels the model call. @@ -222,16 +204,12 @@ public StateExtractionResult Write(StateDocument state, string? replyText) return Write(state, replyText, new Clarifications()); } - /// - /// Writes one extractor reply into the state, running §6's linker over every vocabulary: - /// slot's free-text answer first. - /// - /// The state of one call, which carries the vocabulary the linker resolves against. + /// Writes one extractor reply into the state. + /// The state of one call. /// The raw JSON the model returned. /// - /// The call's ambiguity holder (K36). A Linked outcome that writes clears the slot's - /// pending list and its lastNamed record (K30); an Ambiguous outcome replaces the - /// pending list, stale or not; a NoMatch outcome touches neither. + /// The call's ambiguity holder (K36). A write that lands clears the slot's lastNamed + /// record (K30); a refused write leaves it alone. /// /// What the reply did to the state. internal StateExtractionResult Write( @@ -272,17 +250,7 @@ internal StateExtractionResult Write( continue; } - var declared = Configuration.State[name]; - - // Every answer to a vocabulary: slot goes through the linker, whatever JSON shape it - // arrived in. The schema asks for a string, but a model can answer 900 for a value - // spelled "900ENT", and letting that reach the gate directly would coerce it to "900" - // and skip §6's near-tie check entirely. - var wrote = declared.Vocabulary is { } vocabularyConfig - ? WriteLinked(state, name, value, vocabularyConfig, clarifications) - : WritePlain(state, name, value, clarifications); - - if (wrote) + if (WriteSlot(state, name, value, clarifications)) { filled++; } @@ -295,8 +263,8 @@ internal StateExtractionResult Write( return new StateExtractionResult(true, filled, left, rejected, null); } - /// The non-vocabulary: path: coerce and gate through as before. - private static bool WritePlain(StateDocument state, string slot, JsonNode value, Clarifications clarifications) + /// Coerces and gates one answer through . + private static bool WriteSlot(StateDocument state, string slot, JsonNode value, Clarifications clarifications) { if (!state.TryWrite(slot, value.DeepClone())) { @@ -307,80 +275,9 @@ private static bool WritePlain(StateDocument state, string slot, JsonNode value, return true; } - /// §6's table: link the mention, then act on the outcome. - private bool WriteLinked( - StateDocument state, - string slot, - JsonNode value, - SlotVocabularyConfiguration vocabularyConfig, - Clarifications clarifications) - { - if (!state.Vocabulary.TryGetValue(slot, out var view)) - { - // No domain was sampled for this slot this call. The gate would refuse anything - // anyway, so there is nothing here for the linker to resolve against. - return false; - } - - if (!StateValueCoercion.TryCoerce(value, StateSlotType.String, out var coerced) - || coerced is not JsonValue text - || !text.TryGetValue(out var mention)) - { - return false; - } - - LinkResult result; - try - { - var linker = _linkers.Resolve(vocabularyConfig.Linker); - result = linker.Link(mention, view, SpokenCandidates(clarifications.Read(slot).LastNamed)); - } - catch (Exception exception) when (exception is not OperationCanceledException) - { - // State extraction must never drop a call. Section 8.7. A host linker is arbitrary - // code and an unregistered linker name throws from Resolve, so this refuses the one - // slot rather than letting either unwind the turn. - return false; - } - - switch (result.Outcome) - { - case LinkOutcome.Linked: - if (!state.TryWrite(slot, JsonValue.Create(result.Candidates[0]))) - { - return false; - } - - ClearAmbiguity(clarifications, slot); - return true; - - case LinkOutcome.Ambiguous: - var candidates = result.Candidates; - - // Overwrites whatever pending list was there, including a stale one channel 1 has - // already asked about. §7's own recovery path needs this: a caller who near-ties a - // second, different pair mid-conversation must not be silently dropped because the - // first pair is still sitting unresolved. Extraction runs after_reply, so this is - // the caller's own words beating a guess made earlier from search results. K41's - // fill-only-if-empty guard belongs to the probe, not the linker. - clarifications.Update(slot, s => s.Pending = candidates); - return false; - - default: - return false; - } - } - - /// K30: a successful write clears the slot's pending list and its lastNamed record together. + /// K30: a successful write clears the slot's lastNamed record. private static void ClearAmbiguity(Clarifications clarifications, string slot) - => clarifications.Update(slot, s => - { - s.Pending = null; - s.LastNamed = Clarifications.LastNamed.None; - }); - - private static IReadOnlySet SpokenCandidates(Clarifications.LastNamed lastNamed) - => lastNamed.Kind == Clarifications.LastNamedKind.Set ? lastNamed.Values! : NothingNamed; + => clarifications.Update(slot, s => s.LastNamed = Clarifications.LastNamed.None); private static string TypeName(StateSlotType slotType) => slotType switch { diff --git a/src/AgentCore.Application/State/StateValueLinkers.cs b/src/AgentCore.Application/State/StateValueLinkers.cs deleted file mode 100644 index 27604fca..00000000 --- a/src/AgentCore.Application/State/StateValueLinkers.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace AgentCore.Application.State; - -/// -/// The map from a vocabulary.linker name to the behind it -/// (K12). Always seeded with exact (K9) — the only linker that ships — so a host that binds -/// none still has a working registry. -/// -internal sealed class StateValueLinkers -{ - private readonly Dictionary _byName = new(StringComparer.Ordinal); - - /// Seeds the registry with exact and every linker a host registered. - /// The linkers a host bound with UseStateValueLinkers. - /// Two linkers, built-in or host-supplied, share a name. - internal StateValueLinkers(IEnumerable linkers) - { - ArgumentNullException.ThrowIfNull(linkers); - - Add(new ExactStateValueLinker()); - foreach (var linker in linkers) - { - Add(linker); - } - } - - /// Gets every name registered, for . - internal IReadOnlySet Names => _byName.Keys.ToHashSet(StringComparer.Ordinal); - - /// Resolves the linker one name points at. - /// A slot's vocabulary.linker value. - /// The linker. - /// No linker is registered under that name. - internal IStateValueLinker Resolve(string name) - { - ArgumentNullException.ThrowIfNull(name); - - return _byName.TryGetValue(name, out var linker) - ? linker - : throw new KeyNotFoundException($"no linker is registered under the name '{name}'."); - } - - private void Add(IStateValueLinker linker) - { - ArgumentNullException.ThrowIfNull(linker); - - if (!_byName.TryAdd(linker.Name, linker)) - { - throw new ArgumentException($"the linker name '{linker.Name}' is already registered.", nameof(linker)); - } - } -} diff --git a/src/AgentCore.Application/State/VocabularyCache.cs b/src/AgentCore.Application/State/VocabularyCache.cs deleted file mode 100644 index 308dc265..00000000 --- a/src/AgentCore.Application/State/VocabularyCache.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System.Collections.Concurrent; -using System.Collections.Immutable; - -namespace AgentCore.Application.State; - -/// -/// One immutable per vocabulary: slot, behind a reference a -/// refresh swaps rather than mutates. -/// -/// -/// Section 5: a refresh builds a whole new view and replaces the reference, never mutating one in -/// place. That is what makes free to call once at call open and safe to -/// hold for the rest of the call — the dictionary a caller already read never changes under it, -/// and a live refresh on another slot cannot make that reader tear or throw. -/// -public sealed class VocabularyCache -{ - private readonly Lock _gate = new(); - private readonly TimeProvider _time; - private readonly ConcurrentDictionary _lastGoodAt = new(StringComparer.Ordinal); - private volatile ImmutableDictionary _views = ImmutableDictionary.Empty; - - /// Creates an empty cache. - /// Where comes from, or for the system clock. - public VocabularyCache(TimeProvider? timeProvider = null) => _time = timeProvider ?? TimeProvider.System; - - /// Reads every slot's current vocabulary. The result does not change as later refreshes land. - /// The map from slot name to its view. A slot has never been called for is absent. - public IReadOnlyDictionary Snapshot() => _views; - - /// Reads when a slot's vocabulary was last successfully built. - /// The slot name. - /// The time of the last successful , or when there has been none. - public DateTimeOffset? LastGoodAt(string slot) - { - ArgumentNullException.ThrowIfNull(slot); - return _lastGoodAt.TryGetValue(slot, out var at) ? at : null; - } - - /// Builds one slot's vocabulary from a facet read and installs it, or leaves the slot as it was. - /// The slot the values were read for. - /// The distinct values the facet read returned, before the wildcard sentinel is stripped. - /// The limit the read was made with — the same value passed as the read's own limit. - /// - /// The wildcard sentinel to strip before folding (K6), or when this slot carries none. - /// - /// - /// is below 2, which is the same floor - /// ConfigurationValidator holds the document to: a read of fewer than two values could - /// never be told apart from a truncated one, so every call would throw. - /// - /// - /// fails one of section 10's four degenerate-read checks: its raw count - /// reaches ; it is empty once is - /// stripped; two surviving values fold to the same string; or one folds to the empty string. The - /// slot is left unchanged. - /// - public void Replace(string slot, IReadOnlyList values, int maxValues, string? wildcardValue = null) - { - ArgumentNullException.ThrowIfNull(slot); - ArgumentNullException.ThrowIfNull(values); - ArgumentOutOfRangeException.ThrowIfLessThan(maxValues, 2); - - // The raw count, before the sentinel is stripped: this answers "did the read hit its own - // limit", which is a fact about what Qdrant returned, not about which of those values - // happens to be the wildcard. K6 only orders the strip ahead of the collision checks. - if (values.Count >= maxValues) - { - throw VocabularyException.Truncated(slot, maxValues); - } - - var survivors = wildcardValue is null - ? values - : values.Where(value => !string.Equals(value, wildcardValue, StringComparison.Ordinal)).ToList(); - - if (survivors.Count == 0) - { - throw VocabularyException.NoValues(slot); - } - - Dictionary normalisedToOriginal = new(survivors.Count, StringComparer.Ordinal); - - foreach (var original in survivors) - { - var normalised = VocabularyFold.Fold(original); - - if (normalised.Length == 0) - { - throw VocabularyException.FoldsToEmpty(slot, original); - } - - if (normalisedToOriginal.TryGetValue(normalised, out var existing)) - { - throw VocabularyException.FoldingCollision(slot, existing, original, normalised); - } - - normalisedToOriginal[normalised] = original; - } - - VocabularyView view = new() - { - NormalisedToOriginal = normalisedToOriginal, - Originals = [.. survivors], - }; - - lock (_gate) - { - _views = _views.SetItem(slot, view); - _lastGoodAt[slot] = _time.GetUtcNow(); - } - } -} diff --git a/src/AgentCore.Application/State/VocabularyException.cs b/src/AgentCore.Application/State/VocabularyException.cs deleted file mode 100644 index f59e00c7..00000000 --- a/src/AgentCore.Application/State/VocabularyException.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Globalization; - -namespace AgentCore.Application.State; - -/// -/// The one exception throws for each of section 10's four -/// degenerate reads. -/// -/// -/// Boot fails a slot's read rather than starting an agent whose vocabulary can never work: a read -/// that hit its own limit cannot be told from a complete one, two ids that fold alike could never -/// be told apart by a caller who says either, and an id that folds to nothing could never be -/// linked or gated at all. Turning this into a configuration error with the slot's resolved -/// document pointer belongs to the startup wiring that knows that path, not to the cache. -/// -public sealed class VocabularyException : Exception -{ - private const string DefaultMessage = "A slot's vocabulary could not be built."; - - /// Creates an exception that names no slot. - public VocabularyException() - : base(DefaultMessage) => Slot = string.Empty; - - /// Creates an exception with a plain message. - /// The message a human reads. - public VocabularyException(string message) - : base(message) => Slot = string.Empty; - - /// Creates an exception with a plain message and an inner cause. - /// The message a human reads. - /// The cause. - public VocabularyException(string message, Exception? innerException) - : base(message, innerException) => Slot = string.Empty; - - private VocabularyException(string slot, string message) - : base(message) => Slot = slot; - - /// Gets the slot the failed vocabulary belongs to, or an empty string. - public string Slot { get; } - - /// Builds the failure for a read with no candidate values once the wildcard sentinel is stripped. - /// The slot the vocabulary belongs to. - /// The failure. - public static VocabularyException NoValues(string slot) - { - ArgumentNullException.ThrowIfNull(slot); - return new VocabularyException( - slot, - $"the vocabulary for slot '{slot}' has no values once the wildcard sentinel is stripped. " - + "A slot with no candidates can never be gated or linked."); - } - - /// Builds the failure for a read whose count reached or passed the limit it was read with. - /// The slot the vocabulary belongs to. - /// The limit the read was made with. - /// The failure. - public static VocabularyException Truncated(string slot, int maxValues) - { - ArgumentNullException.ThrowIfNull(slot); - return new VocabularyException( - slot, - $"the vocabulary for slot '{slot}' returned at least {maxValues.ToString(CultureInfo.InvariantCulture)} " - + "values, its configured maxValues. That count cannot be told apart from a truncated read."); - } - - /// Builds the failure for two values that normalise to the same string. - /// The slot the vocabulary belongs to. - /// The value already in the map. - /// The value that collided with it. - /// The normalised form both values share. - /// The failure. - public static VocabularyException FoldingCollision(string slot, string first, string second, string normalised) - { - ArgumentNullException.ThrowIfNull(slot); - ArgumentNullException.ThrowIfNull(first); - ArgumentNullException.ThrowIfNull(second); - ArgumentNullException.ThrowIfNull(normalised); - return new VocabularyException( - slot, - $"the vocabulary for slot '{slot}' has two values that normalise alike: '{first}' and '{second}' " - + $"both fold to '{normalised}'. A caller who says either could never be told apart."); - } - - /// Builds the failure for a value that normalises to the empty string. - /// The slot the vocabulary belongs to. - /// The value that folded away. - /// The failure. - public static VocabularyException FoldsToEmpty(string slot, string value) - { - ArgumentNullException.ThrowIfNull(slot); - ArgumentNullException.ThrowIfNull(value); - return new VocabularyException( - slot, - $"the vocabulary for slot '{slot}' has a value that normalises to the empty string: '{value}'. " - + "It could never be linked or gated."); - } -} diff --git a/src/AgentCore.Application/State/VocabularyFold.cs b/src/AgentCore.Application/State/VocabularyFold.cs deleted file mode 100644 index 03ce0026..00000000 --- a/src/AgentCore.Application/State/VocabularyFold.cs +++ /dev/null @@ -1,103 +0,0 @@ -using System.Globalization; -using System.Text; - -namespace AgentCore.Application.State; - -/// -/// The K31 fold: NFC, invariant lower case, then keep only letters, numbers and marks. One -/// predicate drives both the vocabulary's fold and the mention's tokeniser, so a caller can never -/// see a class the vocabulary was not also normalised by. -/// -/// -/// throughout, never : an astral codepoint is a surrogate -/// pair, and classifying each half separately reads both as -/// — not a kept category — which would silently drop the codepoint instead of keeping it whole. -/// -internal static class VocabularyFold -{ - /// Normalises one vocabulary value or mention span to its comparable form. - /// The original string. - /// NFC, lower-invariant, letters/numbers/marks only. Empty when nothing survives. - internal static string Fold(string value) - { - ArgumentNullException.ThrowIfNull(value); - - var composed = value.Normalize(NormalizationForm.FormC).ToLowerInvariant(); - StringBuilder folded = new(composed.Length); - Span utf16 = stackalloc char[2]; - - foreach (var rune in composed.EnumerateRunes()) - { - if (Keep(rune)) - { - folded.Append(utf16[..rune.EncodeToUtf16(utf16)]); - } - } - - return folded.ToString(); - } - - /// Splits a mention into the runs would keep, and the runs between them it would drop. - /// The extractor's raw mention text. - /// - /// Tokens: the maximal runs of kept runes, each already folded, in order. - /// Separators: the runs of dropped runes strictly between two tokens — one fewer than - /// the token count. A leading or trailing run of dropped runes bounds nothing, so it is not - /// reported. - /// - internal static (IReadOnlyList Tokens, IReadOnlyList Separators) Tokenize(string mention) - { - ArgumentNullException.ThrowIfNull(mention); - - var composed = mention.Normalize(NormalizationForm.FormC).ToLowerInvariant(); - List tokens = []; - List separators = []; - StringBuilder buffer = new(); - Span utf16 = stackalloc char[2]; - var inToken = false; - var sawToken = false; - - foreach (var rune in composed.EnumerateRunes()) - { - var kept = Keep(rune); - if (kept != inToken) - { - if (inToken) - { - tokens.Add(buffer.ToString()); - sawToken = true; - } - else if (sawToken) - { - // A leading run of dropped runes bounds no token on its left, so only a run - // that follows one is a separator. - separators.Add(buffer.ToString()); - } - - buffer.Clear(); - inToken = kept; - } - - buffer.Append(utf16[..rune.EncodeToUtf16(utf16)]); - } - - if (inToken) - { - tokens.Add(buffer.ToString()); - } - - return (tokens, separators); - } - - private static bool Keep(Rune rune) => Rune.GetUnicodeCategory(rune) is - UnicodeCategory.UppercaseLetter or - UnicodeCategory.LowercaseLetter or - UnicodeCategory.TitlecaseLetter or - UnicodeCategory.ModifierLetter or - UnicodeCategory.OtherLetter or - UnicodeCategory.DecimalDigitNumber or - UnicodeCategory.LetterNumber or - UnicodeCategory.OtherNumber or - UnicodeCategory.NonSpacingMark or - UnicodeCategory.SpacingCombiningMark; -} diff --git a/src/AgentCore.Application/State/VocabularyView.cs b/src/AgentCore.Application/State/VocabularyView.cs deleted file mode 100644 index a1fd1f9b..00000000 --- a/src/AgentCore.Application/State/VocabularyView.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace AgentCore.Application.State; - -/// -/// One slot's vocabulary: every original value the collection stores, and the map from each -/// value's normalised form back to that original. -/// -/// -/// Immutable, so a snapshot taken once at call open never changes under the call that holds it — -/// section 5's requirement that a refresh landing mid-call cannot make the gate and the linker -/// disagree, because both read the one reference handed out. -/// -public sealed record VocabularyView -{ - /// Gets the map from a value's normalised form (the VocabularyFold.Fold result) back to the original string. - public required IReadOnlyDictionary NormalisedToOriginal { get; init; } - - /// Gets every original value, in the order the read returned them, with the wildcard sentinel already stripped. - public required IReadOnlyList Originals { get; init; } -} diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs index 949de46c..ded79520 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreBoot.cs @@ -8,7 +8,6 @@ using AgentCore.Application.Ports; using AgentCore.Application.Runtime; using AgentCore.Application.Secrets; -using AgentCore.Application.State; using AgentCore.Application.Tools.Binding; using AgentCore.Application.Tools.Registry; using AgentCore.AspNetCore.DependencyInjection.Startup; @@ -82,9 +81,6 @@ public AgentCoreBoot(IOptions options, ILoggerFactory loggers) /// Gets the factory that builds one session per call. internal ICallSessionFactory Sessions => Started.Sessions; - /// Gets the vocabulary every call session reads, and every refresh installs into. - internal VocabularyCache Vocabulary => Started.Vocabulary; - /// Gets the knowledge base, or when no agent reads one. internal IKnowledgeRetrievalPort? Knowledge => Started.Knowledge; @@ -157,10 +153,6 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) { var (configuration, configurationWarnings) = ConfigurationStartup.Load(_options); - HashSet registeredLinkers = new(StringComparer.Ordinal) { SlotVocabularyConfiguration.DefaultLinker }; - registeredLinkers.UnionWith(_options.StateValueLinkers.Select(static linker => linker.Name)); - ConfigurationValidator.ValidateLinkerNames(configuration, registeredLinkers); - var telemetry = Track(await TelemetryStartup .StartAsync(configuration, _options, _loggers, cancellationToken) .ConfigureAwait(false)); @@ -194,15 +186,6 @@ internal async ValueTask BootAsync(CancellationToken cancellationToken) cancellationToken) .ConfigureAwait(false)); - VocabularyCache vocabulary = new(_options.TimeProvider); - - await KnowledgeStartup - .ApplyVocabularyAsync( - configuration, knowledge, vocabulary, _loggers.CreateLogger(typeof(KnowledgeStartup)), cancellationToken) - .ConfigureAwait(false); - - StartVocabularyRefresh(configuration, knowledge, vocabulary, cancellationToken); - var chatClients = Track(await ChatClientStartup .BuildAsync(_options, startup, cancellationToken) .ConfigureAwait(false)); @@ -249,7 +232,7 @@ await KnowledgeStartup var seams = CallSeamStartup.Build(configuration, _options); var call = await CallSessionStartup - .OpenAsync(this, configuration, _options, graph, vocabulary, _loggers, cancellationToken) + .OpenAsync(this, configuration, _options, graph, _loggers, cancellationToken) .ConfigureAwait(false); _state = new BootState( @@ -263,7 +246,6 @@ await KnowledgeStartup call.Sessions, call.Agent, call.Queue, - vocabulary, knowledge, seams.Call, seams.Speech, @@ -317,65 +299,6 @@ private async ValueTask CloseAsync() } } - /// - /// Starts one per vocabulary: slot that declares a - /// refreshSeconds above zero. 0 means boot only (§4), so those slots start none. - /// - /// The loaded document. - /// The port built, or . - /// The cache every refresh installs into — the same one every call session reads. - /// Passed to each service's own StartAsync. - private void StartVocabularyRefresh( - AgentCoreConfiguration configuration, - IKnowledgeRetrievalPort? knowledge, - VocabularyCache vocabulary, - CancellationToken cancellationToken) - { - if (knowledge?.GetService() is not { } port) - { - return; - } - - var scope = configuration.Providers?.Knowledge?.Scope; - if (scope is null || ScopeTemplate.Parse(scope.Template) is not { } template) - { - return; - } - - var wildcard = scope.Wildcard; - - foreach (var (slotName, slot) in configuration.State) - { - if (slot.Vocabulary is not { RefreshSeconds: > 0 } vocab) - { - continue; - } - - var path = template.Resolve(slotName); - - // Stripped for every declared wildcard, on the same reasoning as the boot read in - // KnowledgeStartup.ApplyVocabularyAsync: the sentinel is stored in the collection, so a - // refresh reads it back at any facet path, scoped or not. - var wildcardValue = wildcard?.Value; - - var service = Track(new VocabularyRefreshService( - slotName, - path, - vocab.MaxValues, - wildcardValue, - vocab.RefreshSeconds, - port, - vocabulary, - _options.TimeProvider ?? TimeProvider.System, - _loggers.CreateLogger())); - - // BackgroundService.StartAsync only arms the loop — it runs ExecuteAsync through - // Task.Run and returns immediately, so awaiting it here would not wait for a single - // refresh, only for the arm itself. - _ = service.StartAsync(cancellationToken); - } - } - private static InvalidOperationException NotStarted() => new( "AgentCore has not booted: the document is loaded, and every adapter it names is opened, " @@ -393,7 +316,6 @@ private sealed record BootState( ICallSessionFactory Sessions, AgentCoreAgent Agent, QueuedAuditSink AuditQueue, - VocabularyCache Vocabulary, IKnowledgeRetrievalPort? Knowledge, IReadOnlyList? CallAdapters, IReadOnlyList? SpeechAdapters, diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs index 4aa6c5c3..1fa28c7e 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreOptions.cs @@ -2,7 +2,6 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Llm; using AgentCore.Application.Ports; -using AgentCore.Application.State; using AgentCore.Application.Tools.Binding; using Microsoft.Agents.AI; using Microsoft.Extensions.Logging; @@ -72,9 +71,6 @@ public sealed class AgentCoreOptions /// Gets the speech vendors the host registered, or . internal IReadOnlyList? Speech { get; private set; } - /// Gets the linkers a slot's vocabulary.linker may name, beyond the built-in exact. - internal IReadOnlyList StateValueLinkers { get; private set; } = []; - /// Gets the folder that holds the SKILL.md directories, or . internal string? SkillsPath { get; private set; } @@ -240,16 +236,6 @@ public AgentCoreOptions UseSpeech(params ISpeechAdapter[] adapters) return this; } - /// Binds the state value linkers, and a slot's vocabulary.linker names one by its . - /// The linkers this host adds beyond the built-in exact. - /// These options, so a host chains its calls. - public AgentCoreOptions UseStateValueLinkers(params IStateValueLinker[] linkers) - { - ArgumentNullException.ThrowIfNull(linkers); - StateValueLinkers = linkers; - return this; - } - /// Binds the folder that holds this host's SKILL.md directories. public AgentCoreOptions UseSkills(string path) { diff --git a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs index d2e22a71..c7dc1a48 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/AgentCoreServiceCollectionExtensions.cs @@ -47,7 +47,6 @@ public static IServiceCollection AddAgentCore( services.AddSingleton(Boot(boot => boot.Tools)); services.AddSingleton(Boot(boot => boot.Calls)); services.AddSingleton(Boot(boot => boot.Sessions)); - services.AddSingleton(Boot(boot => boot.Vocabulary)); services.AddSingleton(Boot(boot => boot.Agent)); services.AddSingleton(Boot(boot => boot.AuditQueue)); diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs index 0ca801f2..9ff41f1e 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/CallSessionStartup.cs @@ -3,7 +3,6 @@ using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.State; using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection.Startup; @@ -23,7 +22,6 @@ internal static class CallSessionStartup /// The loaded document. It carries providers.audit. /// The options the host filled. It carries the audit vendors, the clock, and any observer. /// The compiled graph and the seams step 5 made. - /// The cache KnowledgeStartup.ApplyVocabularyAsync filled. /// The factory the session and the audit queue take their loggers from. /// Cancels the store open. /// The session factory, the agent shim, and the queue in front of the store. @@ -32,7 +30,6 @@ internal static async ValueTask OpenAsync( AgentCoreConfiguration configuration, AgentCoreOptions options, CompiledGraph graph, - VocabularyCache vocabulary, ILoggerFactory loggers, CancellationToken cancellationToken) { @@ -56,11 +53,10 @@ internal static async ValueTask OpenAsync( CallSessionFactory sessions = new( graph.Compiled, graph.Guards, - CallSessionFactory.CreateExtractor(graph.Compiled, graph.ChatClients, options.StateValueLinkers), + CallSessionFactory.CreateExtractor(graph.Compiled, graph.ChatClients), options.TimeProvider, sessionLogger, - CallObservers.Standard(auditSink, sessionLogger, options.Observers), - vocabulary); + CallObservers.Standard(auditSink, sessionLogger, options.Observers)); return new CallSessionSeam(sessions, new AgentCoreAgent(sessions, configuration.Name), auditSink); } diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConfigurationStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConfigurationStartup.cs index 0c0a4ecd..5c872acf 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConfigurationStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/ConfigurationStartup.cs @@ -7,8 +7,7 @@ namespace AgentCore.AspNetCore.DependencyInjection; /// What hands back: the document, and the warnings its validation carried. /// The loaded document. See for what it has already passed. /// -/// Every partial-coverage warning check 5 raises, and section 10's two ambiguity-and-vocabulary -/// warnings (K33, K39). no longer discards these — a caller logs +/// Every partial-coverage warning check 5 raises, and section 10's ambiguity warning (K33). no longer discards these — a caller logs /// them once a logger exists. /// internal readonly record struct ConfigurationLoadResult( diff --git a/src/AgentCore.AspNetCore/DependencyInjection/Startup/KnowledgeStartup.cs b/src/AgentCore.AspNetCore/DependencyInjection/Startup/KnowledgeStartup.cs index ccb5574f..342d3579 100644 --- a/src/AgentCore.AspNetCore/DependencyInjection/Startup/KnowledgeStartup.cs +++ b/src/AgentCore.AspNetCore/DependencyInjection/Startup/KnowledgeStartup.cs @@ -1,12 +1,8 @@ -using System.Text; using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; using AgentCore.Application.Configuration.Schema; using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; -using AgentCore.Application.State; using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging; namespace AgentCore.AspNetCore.DependencyInjection; @@ -60,218 +56,4 @@ internal static class KnowledgeStartup /// when at least one agent reads the knowledge base. private static bool AnyAgentDeclares(AgentCoreConfiguration configuration) => configuration.Agents is { } agents && AgentKnowledge.AnyDeclared(agents); - - /// - /// Section 10: reads every vocabulary: slot's domain into , - /// K44's Unicode probe ahead of those reads, and K48's per-wildcard.facets member check. - /// - /// The loaded document. Already past checks 2 to 8. - /// The port built, or . - /// The cache every successful read is installed into. - /// Where K28's and K48's warnings go. - /// Cancels every read. - /// - /// K44's probe, or for the real one (). A - /// test drives the outcome through this seam: the AspNetCore test host already runs under - /// InvariantGlobalization=true, which makes the non-composing case the ambient default and - /// the composing case unreachable without one. - /// - /// - /// A vocabulary: slot is declared and is not an - /// (K27); the runtime cannot compose Unicode and a slot does - /// not declare assumeNormalized: true (K44); or a slot's read is degenerate (K4, K31). - /// - internal static async ValueTask ApplyVocabularyAsync( - AgentCoreConfiguration configuration, - IKnowledgeRetrievalPort? knowledge, - VocabularyCache vocabulary, - ILogger logger, - CancellationToken cancellationToken, - Func? composesUnicode = null) - { - ArgumentNullException.ThrowIfNull(configuration); - ArgumentNullException.ThrowIfNull(vocabulary); - ArgumentNullException.ThrowIfNull(logger); - - var vocabularySlots = configuration.State - .Where(entry => entry.Value.Vocabulary is not null) - .ToList(); - - var wildcard = configuration.Providers?.Knowledge?.Scope.Wildcard; - var wildcardFacets = wildcard?.Facets ?? []; - - if (vocabularySlots.Count == 0 && wildcardFacets.Count == 0) - { - return; - } - - if (knowledge?.GetService() is not { } port) - { - if (vocabularySlots.Count == 0) - { - // A wildcard-only document predates this design (the 2026-09-01 wildcard plan), and - // K27's refusal is scoped to a document that declares vocabulary:. Forcing every such - // deployment to also implement IFacetVocabularyPort would break K19's byte-identity - // promise for a feature this design never touches. - return; - } - - var reason = knowledge is null - ? "no knowledge port was built, so there is nothing to read a facet vocabulary from" - : $"the built port ({knowledge.GetType().Name}) does not serve {nameof(IFacetVocabularyPort)}"; - - throw FailSlots( - vocabularySlots.Select(entry => entry.Key), - $"declares vocabulary:, and {reason}. A vocabulary: read needs " - + $"{nameof(IFacetVocabularyPort)}.{nameof(IFacetVocabularyPort.ReadAsync)}, which a " - + "host-bound port (UseKnowledgeRetrieval), the composite CompositeKnowledgeStoreFactory " - + "builds from providers.knowledge.kind, and a document with no registered store adapter " - + "can each fail to serve."); - } - - var template = ScopeTemplate.Parse(configuration.Providers?.Knowledge?.Scope.Template) - ?? throw new InvalidOperationException( - "a vocabulary: or wildcard.facets read needs providers.knowledge.scope.template, and " - + "this document names none. Check 5 of section 8.5 should have refused this document " - + "before boot ever reached this read."); - - if (vocabularySlots.Count > 0) - { - if (!(composesUnicode ?? ComposesUnicode)()) - { - var offending = vocabularySlots - .Where(entry => !entry.Value.Vocabulary!.AssumeNormalized) - .Select(entry => entry.Key) - .ToList(); - - if (offending.Count > 0) - { - throw FailSlots( - offending, - "declares vocabulary:, and this runtime cannot compose Unicode: " - + "InvariantGlobalization is enabled and string.Normalize is a no-op, so two " - + "spellings of one id that only differ by composition would never fold alike " - + "and section 10's collision check would never fire. Set InvariantGlobalization " - + "to false to gain ICU, or declare vocabulary.assumeNormalized: true if every id " - + "in the collection and every mention the extractor emits is already NFC."); - } - } - - foreach (var (slotName, slot) in vocabularySlots) - { - var vocab = slot.Vocabulary!; - - var path = template.Resolve(slotName); - - var values = await port.ReadAsync(path, vocab.MaxValues, cancellationToken).ConfigureAwait(false); - - var wildcardValue = wildcard?.Value; - - try - { - vocabulary.Replace(slotName, values, vocab.MaxValues, wildcardValue); - } - catch (VocabularyException degenerate) - { - throw Fail( - ConfigurationError.AppendPointer(StatePointer(slotName), "vocabulary"), - $"{degenerate.Message} Read at path '{path}'.", - degenerate); - } - - if (vocabulary.Snapshot().TryGetValue(slotName, out var view) && view.Originals.Count == 1) - { - KnowledgeStartupLog.SingleValueVocabulary(logger, slotName, view.Originals[0]); - } - } - } - - foreach (var facet in wildcardFacets) - { - var path = template.Resolve(facet); - - IReadOnlyList sample; - try - { - sample = await port.ReadAsync(path, 2, cancellationToken).ConfigureAwait(false); - } - catch (Exception fault) when (fault is not OperationCanceledException) - { - // K48 sits under "warned, not refused": a facet whose store cannot serve this small - // sample read (for example, no keyword payload index at this path) must not turn a - // deployment that was booting into one that cannot. - KnowledgeStartupLog.WildcardFacetCheckFailed(logger, facet, path, fault); - continue; - } - - if (!sample.Contains(wildcard!.Value, StringComparer.Ordinal)) - { - KnowledgeStartupLog.WildcardFacetMissingStar(logger, facet, path); - } - } - } - - /// - /// K44's probe: whether this runtime can compose Unicode. Built from escape sequences, never - /// typed characters — a typed version reads identically and silently reports a false pass, - /// because the source file reaches disk already pre-composed (section 10). - /// - /// when actually composes. - internal static bool ComposesUnicode() => "\u0041\u030A".Normalize(NormalizationForm.FormC) == "\u00C5"; - - private static string StatePointer(string slot) => ConfigurationError.AppendPointer("/state", slot); - - private static ConfigurationLoadException Fail(string pointer, string message, Exception? inner = null) - => new( - new ConfigurationError { Pointer = pointer, Message = message, Check = ConfigurationCheck.ReferenceResolution }, - inner); - - private static ConfigurationLoadException FailSlots(IEnumerable slots, string reasonAfterSlotName) - => new(slots.Select(slot => new ConfigurationError - { - Pointer = ConfigurationError.AppendPointer(StatePointer(slot), "vocabulary"), - Message = $"the slot '{slot}' {reasonAfterSlotName}", - Check = ConfigurationCheck.ReferenceResolution, - }).ToList()); -} - -/// Every warning writes. -internal static partial class KnowledgeStartupLog -{ - /// A slot's vocabulary read back exactly one value (K28). - /// The boot logger. - /// The slot the vocabulary belongs to. - /// The one value. - [LoggerMessage( - EventId = 1, - Level = LogLevel.Warning, - Message = "the vocabulary for slot '{Slot}' has exactly one value: '{Value}'. The gate and " - + "the linker still work; only the ambiguity half is inert, because one value can never " - + "produce more than a confirm question.")] - public static partial void SingleValueVocabulary(ILogger logger, string slot, string value); - - /// A wildcard.facets member's collection holds no * value (K48). - /// The boot logger. - /// The facet key. - /// The resolved payload path the read used. - [LoggerMessage( - EventId = 2, - Level = LogLevel.Warning, - Message = "the wildcard facet '{Facet}' has no '*' value in the collection at '{Path}'. While " - + "it is unfilled, its own wildcard condition matches nothing, so no search and no probe " - + "of another facet can return a card. Fill it from a writer: const slot, or take " - + "'{Facet}' out of wildcard.facets.")] - public static partial void WildcardFacetMissingStar(ILogger logger, string facet, string path); - - /// A wildcard.facets member's own K48 read faulted (warned, not refused). - /// The boot logger. - /// The facet key. - /// The resolved payload path the read used. - /// The cause. - [LoggerMessage( - EventId = 3, - Level = LogLevel.Warning, - Message = "the K48 check for wildcard facet '{Facet}' could not run: the read at '{Path}' " - + "failed. Boot continues; the missing-'*'-value check is skipped for this facet only.")] - public static partial void WildcardFacetCheckFailed(ILogger logger, string facet, string path, Exception exception); } diff --git a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt index 7684ad40..84e44e34 100644 --- a/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/AgentCore.AspNetCore/PublicAPI.Unshipped.txt @@ -40,7 +40,6 @@ AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseObservers(params Ag AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSkills(Microsoft.Agents.AI.AgentSkillsSource! source) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSkills(string! path) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseSpeech(params AgentCore.Application.Ports.ISpeechAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! -AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseStateValueLinkers(params AgentCore.Application.State.IStateValueLinker![]! linkers) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions.UseTelemetry(params AgentCore.Application.Ports.ITelemetryAdapter![]! adapters) -> AgentCore.AspNetCore.DependencyInjection.AgentCoreOptions! AgentCore.AspNetCore.DependencyInjection.AgentCoreServiceCollectionExtensions AgentCore.AspNetCore.DependencyInjection.AgentCoreStartup diff --git a/src/AgentCore.AspNetCore/Sessions/VocabularyRefreshService.cs b/src/AgentCore.AspNetCore/Sessions/VocabularyRefreshService.cs deleted file mode 100644 index cfe4fc25..00000000 --- a/src/AgentCore.AspNetCore/Sessions/VocabularyRefreshService.cs +++ /dev/null @@ -1,102 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Application.State; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace AgentCore.AspNetCore.Sessions; - -/// -/// Re-reads one vocabulary: slot's domain on its own refreshSeconds interval, for as -/// long as the host is up. -/// -/// -/// One instance per slot, following 's -/// idiom. Section 11: a refresh that fails, or that succeeds but is degenerate (K46), keeps the -/// cache's last good view and logs — already leaves the slot -/// unchanged when it throws, so this type only has to keep the loop alive and report what happened. -/// -/// The slot this instance refreshes. -/// The resolved payload path, already through scope.template. -/// The slot's vocabulary.maxValues, passed as the read's own limit. -/// The scope's wildcard sentinel to strip (K6), or . -/// The slot's vocabulary.refreshSeconds. Always greater than zero. -/// The facet read. -/// The cache this instance's reads are installed into. -/// Where the ticks from. -/// Where a failed or degenerate refresh is reported. -internal sealed class VocabularyRefreshService( - string slot, - string path, - int maxValues, - string? wildcardValue, - int refreshSeconds, - IFacetVocabularyPort port, - VocabularyCache cache, - TimeProvider timeProvider, - ILogger logger) : BackgroundService -{ - /// - protected override async Task ExecuteAsync(CancellationToken stoppingToken) - { - using PeriodicTimer timer = new(TimeSpan.FromSeconds(refreshSeconds), timeProvider); - - while (await timer.WaitForNextTickAsync(stoppingToken).ConfigureAwait(false)) - { - await RefreshAsync(stoppingToken).ConfigureAwait(false); - } - } - - /// Runs one refresh: a read and an attempted install. - /// Cancels the read. - /// - /// Exposed so a test can drive one tick directly, without fighting the - /// . - /// - internal async ValueTask RefreshAsync(CancellationToken cancellationToken) - { - IReadOnlyList values; - try - { - values = await port.ReadAsync(path, maxValues, cancellationToken).ConfigureAwait(false); - } - catch (Exception fault) when (fault is not OperationCanceledException) - { - VocabularyRefreshServiceLog.RefreshFailed(logger, slot, fault); - return; - } - - try - { - cache.Replace(slot, values, maxValues, wildcardValue); - } - catch (VocabularyException degenerate) - { - VocabularyRefreshServiceLog.RefreshDegenerate(logger, slot, degenerate); - } - } -} - -/// Every line a writes. -internal static partial class VocabularyRefreshServiceLog -{ - /// A refresh's own read threw. The last good vocabulary is kept. - /// The service's own logger. - /// The slot the refresh was for. - /// The cause. - [LoggerMessage( - EventId = 1, - Level = LogLevel.Warning, - Message = "the vocabulary refresh for slot '{Slot}' failed. The last good vocabulary is kept.")] - public static partial void RefreshFailed(ILogger logger, string slot, Exception exception); - - /// A refresh's read succeeded but failed one of section 10's four boot tests (K46). - /// The service's own logger. - /// The slot the refresh was for. - /// The naming which test failed. - [LoggerMessage( - EventId = 2, - Level = LogLevel.Warning, - Message = "the vocabulary refresh for slot '{Slot}' returned a degenerate read. The last good " - + "vocabulary is kept.")] - public static partial void RefreshDegenerate(ILogger logger, string slot, Exception exception); -} diff --git a/src/AgentCore.Domain/Cases/.gitkeep b/src/AgentCore.Domain/Cases/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/AgentCore.Domain/Conversation/.gitkeep b/src/AgentCore.Domain/Conversation/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/AgentCore.Domain/Flow/.gitkeep b/src/AgentCore.Domain/Flow/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/src/AgentCore.Domain/Knowledge/KnowledgeScope.cs b/src/AgentCore.Domain/Knowledge/KnowledgeScope.cs index 6506a42f..d77d4525 100644 --- a/src/AgentCore.Domain/Knowledge/KnowledgeScope.cs +++ b/src/AgentCore.Domain/Knowledge/KnowledgeScope.cs @@ -11,6 +11,9 @@ public enum KnowledgeFacetOrigin /// Nothing knew it, so the facet holds the wildcard and narrows nothing. Wildcard, + + /// The search tool's filters argument carried it. + Tool, } /// diff --git a/src/AgentCore.Domain/PublicAPI.Unshipped.txt b/src/AgentCore.Domain/PublicAPI.Unshipped.txt index b5d456b1..8bf613ae 100644 --- a/src/AgentCore.Domain/PublicAPI.Unshipped.txt +++ b/src/AgentCore.Domain/PublicAPI.Unshipped.txt @@ -65,6 +65,7 @@ AgentCore.Domain.Knowledge.KnowledgeCard.ViaLink.init -> void AgentCore.Domain.Knowledge.KnowledgeFacetOrigin AgentCore.Domain.Knowledge.KnowledgeFacetOrigin.Extractor = 1 -> AgentCore.Domain.Knowledge.KnowledgeFacetOrigin AgentCore.Domain.Knowledge.KnowledgeFacetOrigin.Host = 0 -> AgentCore.Domain.Knowledge.KnowledgeFacetOrigin +AgentCore.Domain.Knowledge.KnowledgeFacetOrigin.Tool = 3 -> AgentCore.Domain.Knowledge.KnowledgeFacetOrigin AgentCore.Domain.Knowledge.KnowledgeFacetOrigin.Wildcard = 2 -> AgentCore.Domain.Knowledge.KnowledgeFacetOrigin AgentCore.Domain.Knowledge.KnowledgeScope AgentCore.Domain.Knowledge.KnowledgeScope.$() -> AgentCore.Domain.Knowledge.KnowledgeScope! diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs index 4480e14e..f49b6271 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/IQdrantSearchChannel.cs @@ -38,13 +38,4 @@ Task> RetrieveAsync( /// The points that matched. An empty result is not an error. Task> ScrollAsync( string collection, Filter filter, uint limit, CancellationToken cancellationToken); - - /// Reads the distinct values stored at one payload path. - /// The collection. - /// The payload path. - /// The most values to return. - /// Cancels the call. - /// The distinct values, in the order Qdrant returns them. - Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken); } diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs index 108f03a6..a803c854 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantKnowledgeStore.cs @@ -14,7 +14,7 @@ namespace AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; /// The whole knowledge base over one Qdrant collection. /// internal sealed class QdrantKnowledgeStore - : IKnowledgeRetrievalPort, IFacetVocabularyPort, IKnowledgeFacetReadPort, IDisposable + : IKnowledgeRetrievalPort, IKnowledgeFacetReadPort, IDisposable { private readonly IQdrantSearchChannel _channel; private readonly IEmbeddingGenerator> _embeddings; @@ -154,22 +154,6 @@ public async ValueTask> SearchAsync( return cards; } - /// - /// - /// is resolved verbatim: the caller has already applied - /// scope.template, so this never prefixes or rewrites it. - /// - public async ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(path); - ArgumentOutOfRangeException.ThrowIfNegative(limit); - - return await _channel - .FacetAsync(_options.Collection, path, (ulong)limit, cancellationToken) - .ConfigureAwait(false); - } - /// /// /// The value is matched exactly, and never widened by scope.wildcard the way a scoped diff --git a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs index 564c6dd5..f891f41b 100644 --- a/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs +++ b/src/AgentCore.Infrastructure/Knowledge/VectorData/Qdrant/QdrantSearchChannel.cs @@ -72,19 +72,6 @@ public async Task> ScrollAsync( return response.Result; } - /// - public async Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken) - { - // exact: true always. Measured equal to exact: false on 2- and 8-segment collections - // (P4); the guarantee is the caller's and the measured cost was 6 ms. - var response = await RunAsync( - () => _client.FacetAsync(collection, key, limit: limit, exact: true, cancellationToken: cancellationToken), - cancellationToken).ConfigureAwait(false); - - return [.. response.Hits.Select(hit => hit.Value.StringValue)]; - } - /// /// Runs one gRPC call and converts a client-side cancellation into . /// diff --git a/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs b/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs index 89786d50..b23015af 100644 --- a/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Compilation/ClarificationWiringBindingTests.cs @@ -61,64 +61,6 @@ public sealed class ClarificationWiringBindingTests knowledge: { mode: tool, scoped: true } """; - private const string TwoAgentYaml = - """ - apiVersion: agentcore/v1 - name: clarification-wiring-two-agents - state: - model: - type: string - writer: extractor - description: "The model, as printed on the machine." - audience: - type: string - writer: const - value: everyone - enum: [everyone] - policy: - initial: greeting - stages: - - { id: greeting, agent: greeter } - - { id: answering, agent: reader } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [model, audience] - wildcard: { value: "*", facets: [model] } - ambiguity: { maxCandidates: 3, maxAsks: 2 } - agents: - items: - - { id: greeter, instructions: "I say hello" } - - { id: reader, instructions: "I read the bank", knowledge: { mode: tool, scoped: true } } - """; - - [Fact] - public void EveryAgentInOneDocument_SharesTheOneClarificationProvider() - { - // The provider's three fields are the document's wiring and it keeps nothing per agent, so a - // second instance would be a second copy of the same thing. Channel 1 is bound to agents that - // declare no knowledge: block of their own, so this is every agent in the document, not just - // the ones that search. - using SequencedChatClient reply = new("hello there."); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(TwoAgentYaml), - new AgentCompilationContext(new FakeChatClientFactory(reply)) { Knowledge = new ScopedFakePort() }); - - var greeter = Assert.Single(Providers(compiled.Agents["greeter"]).OfType()); - var reader = Assert.Single(Providers(compiled.Agents["reader"]).OfType()); - - Assert.Same(greeter, reader); - } - [Fact] public async Task TheDocumentsAmbiguityWiring_ReachesTheAgentsOwnBoundSearch() { diff --git a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs b/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs index 4c758ac0..6dee8d76 100644 --- a/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs +++ b/tests/AgentCore.Application.Tests/Compilation/KnowledgeProviderBindingTests.cs @@ -7,6 +7,7 @@ using AgentCore.Application.Tests.Knowledge.Fakes; using AgentCore.Application.Tests.Runtime; using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; using Xunit; namespace AgentCore.Application.Tests.Compilation; @@ -41,6 +42,29 @@ public sealed class KnowledgeProviderBindingTests - { id: quiet, instructions: "I answer from my own instructions" } """; + private const string FilterableYaml = + """ + apiVersion: agentcore/v1 + name: knowledge-binding-filterable + providers: + call: { kind: telnyx-relay } + speech: + stt: { kind: telnyx-relay } + tts: { kind: telnyx-relay } + knowledge: + kind: qdrant + collection: kb + fields: { body: text } + scope: + template: "facets.{key}" + filterable: + - key: model + description: "The machine and the year, as one tag, such as lcr-2023." + agents: + items: + - { id: only, instructions: "I read the bank", knowledge: { mode: tool, scoped: false } } + """; + private const string NoKnowledgeYaml = """ apiVersion: agentcore/v1 @@ -124,6 +148,36 @@ public void AKnowledgeBlockOverAHostThatBoundNoPort_FailsTheStart() Assert.Equal("/agents/items/0/knowledge", Assert.Single(failure.Errors).Pointer); } + [Fact] + public async Task AFilterableFacet_ReachesTheSearchToolTheAgentIsGiven() + { + // The declaration crosses four layers before the model sees it: the document schema has to + // allow the block, the record has to bind it, the compiler has to carry it to the factory, + // and the factory has to wrap the function. Every one of those is silent when it drops it, + // and the agent then searches the whole corpus and nobody is told. + var agent = CompileOne(FilterableYaml, new StubKnowledgePort([])); + + List offered = []; + foreach (var provider in Providers(agent)) + { +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + AIContextProvider.InvokingContext context = new(agent, null, new AIContext()); +#pragma warning restore MAAI001 + var result = await provider.InvokingAsync(context, TestContext.Current.CancellationToken); + offered.AddRange((result.Tools ?? []).OfType()); + } + + var tool = Assert.Single(offered); + var keys = tool.JsonSchema + .GetProperty("properties").GetProperty("filters") + .GetProperty("items").GetProperty("properties").GetProperty("key") + .GetProperty("enum") + .EnumerateArray() + .Select(value => value.GetString()); + + Assert.Equal(["model"], keys); + } + private static AIAgent CompileOne(string yaml, IKnowledgeRetrievalPort? port) { using SequencedChatClient reply = new("hello there."); diff --git a/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs b/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs index 650d4aac..1117df6f 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ConfigurationBinderTests.cs @@ -259,103 +259,6 @@ public void Bind_KnowledgeScopeWildcardAndFromState_ReadsBoth() Assert.Equal(["brand", "applies_to"], scope.FromState); } - [Fact] - public void Bind_VocabularySlot_ReadsFromAndDefaults() - { - const string Document = """ - apiVersion: agentcore/v1 - name: doc - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge } } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - """; - - var configuration = ConfigurationLoader.LoadYaml(Document); - var vocabulary = configuration.State["applies_to"].Vocabulary; - - Assert.NotNull(vocabulary); - Assert.Equal("knowledge", vocabulary!.From); - Assert.Equal(SlotVocabularyConfiguration.DefaultLinker, vocabulary.Linker); - Assert.Equal(SlotVocabularyConfiguration.DefaultRefreshSeconds, vocabulary.RefreshSeconds); - Assert.Equal(SlotVocabularyConfiguration.DefaultMaxValues, vocabulary.MaxValues); - Assert.False(vocabulary.AssumeNormalized); - } - - [Fact] - public void Bind_VocabularySlot_ReadsEveryField() - { - const string Document = """ - apiVersion: agentcore/v1 - name: doc - state: - applies_to: - type: string - writer: extractor - vocabulary: { from: knowledge, linker: exact, refreshSeconds: 900, maxValues: 500, assumeNormalized: true } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - """; - - var configuration = ConfigurationLoader.LoadYaml(Document); - var vocabulary = configuration.State["applies_to"].Vocabulary!; - - Assert.Equal("knowledge", vocabulary.From); - Assert.Equal("exact", vocabulary.Linker); - Assert.Equal(900, vocabulary.RefreshSeconds); - Assert.Equal(500, vocabulary.MaxValues); - Assert.True(vocabulary.AssumeNormalized); - } - - /// from: is the one member the design allows, so the schema declares it as an enum of one. - [Fact] - public void Bind_VocabularyFromOtherThanKnowledge_FailsCheckOne() - { - const string Document = """ - apiVersion: agentcore/v1 - name: doc - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: somewhere_else } } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - """; - - var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(Document)); - - Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); - Assert.Contains(failure.Errors, error => error.Pointer == "/state/applies_to/vocabulary/from"); - } - - /// additionalProperties: false on the nested object, not only on stateSlot itself. - [Fact] - public void Bind_AnUnknownVocabularyKey_FailsCheckOne() - { - const string Document = """ - apiVersion: agentcore/v1 - name: doc - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge, bogus: 1 } } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - """; - - var failure = Assert.Throws(() => ConfigurationLoader.LoadYaml(Document)); - - Assert.Equal(ConfigurationCheck.DocumentSchema, failure.Check); - } - [Fact] public void Bind_AmbiguityBlock_ReadsDefaults() { diff --git a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs index 7b0ead7b..3407e134 100644 --- a/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs +++ b/tests/AgentCore.Application.Tests/Configuration/ExampleDocument.cs @@ -183,6 +183,9 @@ internal static class ExampleDocument value: "*" facets: [brand, applies_to] fromState: [brand, applies_to] + filterable: + - key: applies_to + description: "The machine the question is about, as one tag, such as ct900 or f63-2019." links: field: see_also lookup: uuid5 @@ -627,6 +630,12 @@ internal static class ExampleDocument "fromState": [ "brand", "applies_to" + ], + "filterable": [ + { + "key": "applies_to", + "description": "The machine the question is about, as one tag, such as ct900 or f63-2019." + } ] }, "links": { diff --git a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs index 0f0e696d..52aa9bb9 100644 --- a/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs +++ b/tests/AgentCore.Application.Tests/Configuration/Validation/ConfigurationValidatorTests.cs @@ -370,13 +370,6 @@ private static AgentCoreConfiguration Scoped( EnumValues = [JsonValue.Create("f63")!], }; - private static StateSlotConfiguration VocabSlot(SlotVocabularyConfiguration? vocabulary = null) => new() - { - Type = StateSlotType.String, - Writer = StateWriter.Extractor, - Vocabulary = vocabulary ?? new SlotVocabularyConfiguration { From = "knowledge" }, - }; - private static KnowledgeAmbiguityConfiguration AnAmbiguity() => new(); private static readonly KnowledgeWildcardConfiguration Star = @@ -397,19 +390,6 @@ private static AgentCoreConfiguration OneFacetScope( ambiguity, mapper); - /// with a vocabulary slot in place of the facet slot. - private static AgentCoreConfiguration OneVocabularyScope( - StateSlotConfiguration slot, - KnowledgeAmbiguityConfiguration? ambiguity = null, - string? mapper = null) => - Scoped( - ["applies_to"], - Star, - new Dictionary { ["applies_to"] = slot }, - AnExtractor(), - ambiguity, - mapper); - /// /// Two facet slots. This is the smallest scope that keeps the single-facet ambiguity warning /// (K33) silent, so it is the base for every test that asserts no warning. @@ -600,121 +580,15 @@ public void Evaluate_FacetWildcardDeclaresNoFacets_Fails() Assert.Single(result.Errors, e => e.Pointer == "/providers/knowledge/scope/wildcard/facets"); } - [Fact] - public void Evaluate_FacetSlotDeclaresVocabularyInsteadOfEnum_PassesTheEnumRow() - { - var slot = FacetSlot() with { EnumValues = null, Vocabulary = new SlotVocabularyConfiguration { From = "knowledge" } }; - - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(slot, AnAmbiguity())); - - Assert.Empty(result.Errors); - } - // --------------------------------------------------------------------------------------------- - // Check 2, vocabulary and ambiguity: section 10 of the ambiguity-and-vocabulary design. + // Check 2, ambiguity: section 10 of the ambiguity design. // // Every fixture below keeps fromState and wildcard.facets in lockstep (both naming exactly the - // facets the test declares slots for) so the row-8 and enum-or-vocabulary checks stay silent, - // and sets ambiguity: and wildcard: wherever their absence would otherwise trip rows 5 or 6. + // facets the test declares slots for) so the row-8 and enum checks stay silent, and sets + // ambiguity: and wildcard: wherever their absence would otherwise trip rows 5 or 6. // Each refusal test asserts the *total* error count, not just a filtered pointer match, so a // fixture that quietly grows a second error cannot hide behind the assertion. // --------------------------------------------------------------------------------------------- - [Fact] - public void Evaluate_SlotDeclaresBothEnumAndVocabulary_Fails() - { - var slot = VocabSlot() with { EnumValues = [JsonValue.Create("f63")!] }; - - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(slot, AnAmbiguity())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/state/applies_to/vocabulary", error.Pointer); - Assert.Contains("applies_to", error.Message, StringComparison.Ordinal); - } - - [Fact] - public void Evaluate_SlotDeclaresBothValueAndVocabulary_Fails() - { - var slot = VocabSlot() with { Writer = StateWriter.Const, Value = JsonValue.Create("f63") }; - var wildcard = new KnowledgeWildcardConfiguration { Value = "*", Facets = ["brand"] }; - - var result = ConfigurationValidator.EvaluateStructure( - Scoped( - ["brand"], - wildcard, - new Dictionary - { - ["applies_to"] = slot, - ["brand"] = FacetSlot(), - }, - AnExtractor(), - ambiguity: AnAmbiguity())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/state/applies_to/value", error.Pointer); - } - - /// - /// A slot may take its domain from the knowledge base and never be scoped by. - /// - /// - /// The gate still holds the extractor to values the provider published, and the linker still - /// folds a mention onto one of them. A host may also read the domain for itself — requiring a - /// knowledge search to carry a product name the manuals use, say — which needs the vocabulary - /// and would be actively harmed by narrowing every search to it. - /// - [Fact] - public void Evaluate_VocabularySlotAbsentFromFromState_Passes() - { - var wildcard = new KnowledgeWildcardConfiguration { Value = "*", Facets = ["brand"] }; - - var result = ConfigurationValidator.EvaluateStructure( - Scoped( - ["brand"], - wildcard, - new Dictionary - { - ["applies_to"] = VocabSlot(), - ["brand"] = FacetSlot(), - }, - AnExtractor(), - ambiguity: AnAmbiguity())); - - Assert.Empty(result.Errors); - } - - [Fact] - public void Evaluate_VocabularyMaxValuesBelowTwo_Fails() - { - var slot = VocabSlot(new SlotVocabularyConfiguration { From = "knowledge", MaxValues = 1 }); - - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(slot, AnAmbiguity())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/state/applies_to/vocabulary/maxValues", error.Pointer); - Assert.Contains("applies_to", error.Message, StringComparison.Ordinal); - } - - [Fact] - public void Evaluate_VocabularyRefreshSecondsNegative_Fails() - { - var slot = VocabSlot(new SlotVocabularyConfiguration { From = "knowledge", RefreshSeconds = -5 }); - - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(slot, AnAmbiguity())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/state/applies_to/vocabulary/refreshSeconds", error.Pointer); - Assert.Contains("applies_to", error.Message, StringComparison.Ordinal); - } - - [Fact] - public void Evaluate_VocabularyWithNoAmbiguity_Fails() - { - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(VocabSlot())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/providers/knowledge/ambiguity", error.Pointer); - } - [Fact] public void Evaluate_AmbiguityWithNoWildcard_Fails() { @@ -781,20 +655,9 @@ public void Evaluate_AmbiguityProbeWaitMarginSecondsBelowOne_Fails() } [Fact] - public void Evaluate_VocabularyWithCustomMapper_Fails() + public void Evaluate_AmbiguityWithCustomMapper_Fails() { - var result = ConfigurationValidator.EvaluateStructure( - OneVocabularyScope(VocabSlot(), AnAmbiguity(), mapper: "custom-mapper")); - - var error = Assert.Single(result.Errors); - Assert.Equal("/providers/knowledge/mapper", error.Pointer); - } - - [Fact] - public void Evaluate_AmbiguityWithCustomMapperAndNoVocabulary_Fails() - { - // The probe reads Extras, and nothing about vocabulary puts it there. A document that declares - // ambiguity without vocabulary must still be refused a mapper that leaves Extras empty. + // The probe reads Extras, which only the built-in field mapper fills. var result = ConfigurationValidator.EvaluateStructure( TwoFacetScope(AnAmbiguity(), mapper: "custom-mapper")); @@ -826,19 +689,6 @@ public void Evaluate_AmbiguityProbeWaitMarginSecondsAboveTheTimerCeiling_Fails() Assert.Equal("/providers/knowledge/ambiguity/probeWaitMarginSeconds", error.Pointer); } - [Fact] - public void Evaluate_VocabularyRefreshSecondsAboveTheTimerCeiling_Fails() - { - // PeriodicTimer throws above uint.MaxValue - 1 milliseconds, inside BootAsync. - var slot = VocabSlot(new SlotVocabularyConfiguration { From = "knowledge", RefreshSeconds = 86_400_000 }); - - var result = ConfigurationValidator.EvaluateStructure(OneVocabularyScope(slot, AnAmbiguity())); - - var error = Assert.Single(result.Errors); - Assert.Equal("/state/applies_to/vocabulary/refreshSeconds", error.Pointer); - Assert.Equal(ConfigurationCheck.ValueRange, error.Check); - } - [Fact] public void Evaluate_AmbiguityWithEmptyFromState_Warns() { @@ -871,37 +721,10 @@ public void Evaluate_AmbiguityWithTwoFacetsFromState_DoesNotWarn() } [Fact] - public void Evaluate_AmbiguityOnAGraphDocument_Warns() - { - var configuration = TwoFacetScope(AnAmbiguity()) with { Graph = new GraphConfiguration() }; - - var result = ConfigurationValidator.EvaluateStructure(configuration); - - Assert.Empty(result.Errors); - var warning = Assert.Single(result.Warnings); - Assert.Equal("/providers/knowledge/ambiguity", warning.Pointer); - } - - /// - /// Same two-facet base as , minus - /// graph: — the direct control for it, and incidentally the same witness that proves - /// the two-facet count keeps the single-facet warning (K33) silent too. - /// - [Fact] - public void Evaluate_AmbiguityOnANonGraphDocument_DoesNotWarnAboutGraph() - { - var result = ConfigurationValidator.EvaluateStructure(TwoFacetScope(AnAmbiguity())); - - Assert.Empty(result.Errors); - Assert.Empty(result.Warnings); - } - - [Fact] - public void Evaluate_NoVocabularyAndNoAmbiguity_BindsNullAndAddsNothing() + public void Evaluate_NoAmbiguity_BindsNullAndAddsNothing() { var configuration = ConfigurationLoader.LoadYaml(ExampleDocument.Yaml); - Assert.All(configuration.State.Values, slot => Assert.Null(slot.Vocabulary)); Assert.Null(configuration.Providers?.Knowledge?.Ambiguity); var result = ConfigurationValidator.Evaluate(configuration); @@ -1611,51 +1434,6 @@ public void ValidateToolReferences_AnIdOnlyDiscoveryServes_Passes() Assert.Null(exception); } - [Fact] - public void ValidateLinkerNames_ANameNothingRegistered_FailsNamingItAndThePointer() - { - const string document = $$""" - apiVersion: agentcore/v1 - name: broken-linker - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge, linker: bogus } } - {{SpeechOnlyProviders}} - """; - - var configuration = ConfigurationLoader.LoadYaml(document); - var registered = new HashSet(["exact"], StringComparer.Ordinal); - - var failure = Assert.Throws( - () => ConfigurationValidator.ValidateLinkerNames(configuration, registered)); - - var error = Assert.Single(failure.Errors); - Assert.Equal("/state/applies_to/vocabulary/linker", error.Pointer); - Assert.Equal( - "the slot 'applies_to' declares vocabulary.linker: 'bogus', which nothing registered. " - + "Register it with UseStateValueLinkers, or use 'exact'.", - error.Message); - Assert.Equal(ConfigurationCheck.ReferenceResolution, error.Check); - } - - [Fact] - public void ValidateLinkerNames_ARegisteredName_DoesNotThrow() - { - const string document = $$""" - apiVersion: agentcore/v1 - name: fine-linker - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge, linker: exact } } - {{SpeechOnlyProviders}} - """; - - var configuration = ConfigurationLoader.LoadYaml(document); - var registered = new HashSet(["exact"], StringComparer.Ordinal); - - var exception = Record.Exception(() => ConfigurationValidator.ValidateLinkerNames(configuration, registered)); - - Assert.Null(exception); - } - [Fact] public void ValidateSkillReferences_ANameTheFolderDoesNotServe_FailsNamingItAndWhatIsServed() { diff --git a/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs new file mode 100644 index 00000000..39b5f73c --- /dev/null +++ b/tests/AgentCore.Application.Tests/Knowledge/FacetFilterTests.cs @@ -0,0 +1,246 @@ +using System.Text.Json; + +using AgentCore.Application.Configuration.Compilation; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Knowledge; +using AgentCore.Application.Ports; +using AgentCore.Application.Tests.Knowledge.Fakes; +using AgentCore.Domain.Knowledge; +using AgentCore.TestSupport; + +using Microsoft.Agents.AI; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; + +using Xunit; + +namespace AgentCore.Application.Tests.Knowledge; + +/// +/// The filters argument a tool-mode agent narrows its own search with. +/// +public sealed class FacetFilterTests +{ + private static readonly KnowledgeScopeConfiguration Declared = new() + { + Template = "facets.{key}", + Filterable = + [ + new() { Key = "model", Description = "The machine and the year, as one tag." }, + new() { Key = "section", Description = "Which part of the manual." }, + ], + }; + + [Fact] + public async Task ToolMode_NothingFilterable_OffersThePlainSearch() + { + var tool = await SearchToolAsync(new StubKnowledgePort([]), scope: null); + + Assert.False(tool.JsonSchema.GetProperty("properties").TryGetProperty("filters", out _)); + } + + [Fact] + public async Task ToolMode_FilterableDeclared_PutsEveryKeyInTheEnum() + { + var tool = await SearchToolAsync(new StubKnowledgePort([]), Declared); + + var keys = tool.JsonSchema + .GetProperty("properties").GetProperty("filters") + .GetProperty("items").GetProperty("properties").GetProperty("key") + .GetProperty("enum") + .EnumerateArray() + .Select(value => value.GetString()) + .ToList(); + + Assert.Equal(["model", "section"], keys); + } + + [Fact] + public async Task ToolMode_FilterableDeclared_TellsTheModelWhatEachKeyMeans() + { + var tool = await SearchToolAsync(new StubKnowledgePort([]), Declared); + + var wording = tool.JsonSchema + .GetProperty("properties").GetProperty("filters") + .GetProperty("description") + .GetString(); + + Assert.Contains("model: The machine and the year, as one tag.", wording, StringComparison.Ordinal); + Assert.Contains("section: Which part of the manual.", wording, StringComparison.Ordinal); + } + + [Fact] + public async Task Filters_NarrowTheScopeTheStoreSees() + { + StubKnowledgePort port = new([Card("a")]); + var tool = await SearchToolAsync(port, Declared); + + await CallAsync(tool, "what belt fits it?", ("model", "lcr-2023")); + + Assert.Equal("lcr-2023", port.ScopeAtTheStore!.Facets["model"]); + Assert.Equal(KnowledgeFacetOrigin.Tool, port.ScopeAtTheStore.Origins["model"]); + } + + [Fact] + public async Task Filters_AreNotForwardedToTheInnerFunction() + { + StubKnowledgePort port = new([Card("a")]); + var tool = await SearchToolAsync(port, Declared); + + await CallAsync(tool, "what belt fits it?", ("model", "lcr-2023")); + + Assert.Equal("what belt fits it?", port.LastQuery); + } + + [Fact] + public async Task Filters_AKeyNobodyDeclared_IsIgnored() + { + StubKnowledgePort port = new([Card("a")]); + var tool = await SearchToolAsync(port, Declared); + + await CallAsync(tool, "anything", ("customer", "globex")); + + Assert.Empty(port.ScopeAtTheStore!.Facets); + } + + [Fact] + public async Task Filters_ClearNoCard_TheSearchRunsAgainWithoutThem() + { + // The whole point of the safety net: a filter is the model's guess at the subject, and a + // guess that matches nothing must not become "nothing is documented". + ScopeFilteringKnowledgePort port = new( + (Card("belt"), new Dictionary(StringComparer.Ordinal) { ["model"] = "lcr-2019" })); + + var tool = await SearchToolAsync(port, Declared); + + var answer = await CallAsync(tool, "what belt fits it?", ("model", "lcr-2023")); + + Assert.Contains("card belt", answer, StringComparison.Ordinal); + } + + [Fact] + public async Task Filters_ClearNoCardAndNothingElseDoesEither_StaysEmpty() + { + ScopeFilteringKnowledgePort port = new(); + + var tool = await SearchToolAsync(port, Declared); + + var answer = await CallAsync(tool, "what belt fits it?", ("model", "lcr-2023")); + + Assert.DoesNotContain("card ", answer, StringComparison.Ordinal); + } + + [Fact] + public async Task Filters_AreNamedInTheRecordAnOperatorDebugsFrom() + { + // The record reads the LIVE scope ambient, so it has to be written while the search's own + // scope is still open. Built a line later, it names whatever the turn composed instead -- + // and the one thing an operator opens this record to see, which facet narrowed the search + // that found nothing, is exactly the part that goes missing. + RecordingLoggerFactory loggers = new(); + + var tool = await SearchToolAsync(new StubKnowledgePort([Card("a")]), Declared, loggers: loggers); + await CallAsync(tool, "what belt fits it?", ("model", "lcr-2023")); + + var line = Assert.Single(loggers.Of(11)); + var record = line.Field("Record"); + + Assert.NotNull(record); + Assert.Equal("model=lcr-2023 (Tool)", record!.Scope); + } + + private static async Task SearchToolAsync( + IKnowledgeRetrievalPort port, + KnowledgeScopeConfiguration? scope, + ILoggerFactory? loggers = null) + { + var provider = KnowledgeProviderFactory.Create( + port, + new ResolvedKnowledge(KnowledgeMode.Tool, Limit: 5, Citations: false, Scoped: false), + "agent-under-test", + new SourceLocatorCitationFormatter(), + loggers, + scope); + +#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. + var context = await provider.InvokingAsync( + new AIContextProvider.InvokingContext( + StubAgent.Instance, + null, + new AIContext { Messages = [new ChatMessage(ChatRole.User, "hello")] }), + TestContext.Current.CancellationToken); +#pragma warning restore MAAI001 + + return Assert.IsAssignableFrom(Assert.Single(context.Tools!)); + } + + private static async Task CallAsync( + AIFunction tool, string question, params (string Key, string Value)[] filters) + { + Dictionary arguments = new(StringComparer.Ordinal) + { + ["userQuestion"] = question, + ["filters"] = JsonSerializer.SerializeToElement( + filters.Select(filter => new Dictionary(StringComparer.Ordinal) + { + ["key"] = filter.Key, + ["value"] = filter.Value, + })), + }; + + var answer = await tool.InvokeAsync( + new AIFunctionArguments(arguments), TestContext.Current.CancellationToken); + + return answer?.ToString() ?? string.Empty; + } + + private sealed class StubSession : AgentSession; + + /// Stands in for the agent the framework names on a context. Nothing here runs it. + private sealed class StubAgent : AIAgent + { + public static StubAgent Instance { get; } = new(); + + protected override ValueTask CreateSessionCoreAsync( + CancellationToken cancellationToken = default) + => new(new StubSession()); + + protected override ValueTask SerializeSessionCoreAsync( + AgentSession session, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override ValueTask DeserializeSessionCoreAsync( + JsonElement serializedState, + JsonSerializerOptions? jsonSerializerOptions = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override Task RunCoreAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + + protected override IAsyncEnumerable RunCoreStreamingAsync( + IEnumerable messages, + AgentSession? session = null, + AgentRunOptions? options = null, + CancellationToken cancellationToken = default) + => throw new NotSupportedException(); + } + + private static KnowledgeCard Card(string id) + => new() + { + CardId = id, + Text = "card " + id, + Authority = 3, + SourceRef = "ct900-om", + SourceLocator = "p.27", + Score = 0.87, + ViaLink = false, + }; +} diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs index 34f09f94..ef54db04 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeAuditRecordTests.cs @@ -122,6 +122,50 @@ public void For_CarriesTheScopeOrigins() Assert.Equal(KnowledgeFacetOrigin.Wildcard, record.ScopeOrigins["brand"]); } + [Fact] + public void ForLog_WritesEachFacetWithItsOriginAsText() + { + // The log line prints the view with the record's own ToString, and a dictionary prints as + // its type name there. The one thing an operator opens the line to see, which facet + // narrowed the search, has to be in the text. + KnowledgeScope scope = new() + { + Facets = new Dictionary(StringComparer.Ordinal) + { + ["model"] = "f85-2019", + ["code"] = "*", + }, + Origins = new Dictionary(StringComparer.Ordinal) + { + ["model"] = KnowledgeFacetOrigin.Tool, + ["code"] = KnowledgeFacetOrigin.Wildcard, + }, + }; + + var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", scope, [], 1.0, null) + .ForLog(); + + Assert.Equal("code=* (Wildcard), model=f85-2019 (Tool)", view.Scope); + } + + [Fact] + public void ForLog_FacetWithNoRecordedOrigin_WritesTheValueAlone() + { + var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", Scope(), [], 1.0, null) + .ForLog(); + + Assert.Equal("model=ct900", view.Scope); + } + + [Fact] + public void ForLog_NoScopeWasOpen_WritesAnEmptyString() + { + var view = KnowledgeAuditRecord.For(null, "agent", KnowledgeMode.Tool, "q", scope: null, [], 1.0, null) + .ForLog(); + + Assert.Equal(string.Empty, view.Scope); + } + private static KnowledgeScope Scope() => new() { Facets = new Dictionary { ["model"] = "ct900" } }; diff --git a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs index 96ef04aa..8050e497 100644 --- a/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Knowledge/KnowledgeProbeTests.cs @@ -130,27 +130,6 @@ public async Task Step3_FacetAtItsAskCap_IsSkipped_AndTheNextDroppableFacetIsTri Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); } - [Fact] - public async Task Step3_FacetChannel1AlreadyAskedThisTurn_IsSkipped() - { - // K41: one slot is asked by at most one channel per turn. brand is skipped, so applies_to -- - // the only other droppable facet -- is what the probe's second search actually drops. - var port = new ProbeFakePort((facets, _) => Task.FromResult>( - facets.ContainsKey("applies_to") ? [] : [CardWithFacet("a", "applies_to", "ct900")])); - - var clarificationsObject = new Clarifications(); - clarificationsObject.Update("brand", s => s.AskedThisTurn = true); - using var clarifications = OpenClarifications(clarificationsObject); - using var scope = KnowledgeScopeScope.Open(FullScope("brand", "applies_to")); - - var knowledge = Resolved(["brand", "applies_to"]); - var results = await InvokeSearchAsync(Provider(port, knowledge), "e33"); - - Assert.Contains(results, r => r.Text.Contains("ct900", StringComparison.Ordinal)); - Assert.Equal(0, clarificationsObject.Read("brand").ProbeAsks); - Assert.Equal(1, clarificationsObject.Read("applies_to").ProbeAsks); - } - [Fact] public async Task Step4_DropsTheFirstDroppableFacet_InFromStateDeclarationOrder() { @@ -171,7 +150,7 @@ public async Task Step4_DropsTheFirstDroppableFacet_InFromStateDeclarationOrder( // §8 steps 5-6: reading candidates and choosing the message. [Fact] - public async Task Steps5And6_FindsCandidates_SetsThePendingListAndEmitsTheNote() + public async Task Steps5And6_FindsCandidates_RecordsWhatItNamedAndEmitsTheNote() { var port = new ProbeFakePort((facets, _) => Task.FromResult>( facets.ContainsKey("applies_to") @@ -191,7 +170,6 @@ public async Task Steps5And6_FindsCandidates_SetsThePendingListAndEmitsTheNote() Assert.Single(results).Text); var snapshot = clarificationsObject.Read("applies_to"); - Assert.Equal(["ct900", "ct900ent"], snapshot.Pending); Assert.Equal(Clarifications.LastNamedKind.Set, snapshot.LastNamed.Kind); Assert.Equal( new HashSet(["ct900", "ct900ent"], StringComparer.Ordinal), snapshot.LastNamed.Values); @@ -352,12 +330,9 @@ public async Task K39_AGraphDocumentsProbe_EmitsItsNote_AndRecordsNoLastNamed() Assert.Contains("ct900", Assert.Single(results).Text, StringComparison.Ordinal); - var snapshot = clarificationsObject.Read("applies_to"); - // The pending list is still set: a later turn on the SAME graph row's session may still get - // an answer through the linker. Only the RECORD of what was named is withheld (K21's - // tie-break rests on the caller having heard the list, which AgentCore cannot know here). - Assert.Equal(["ct900"], snapshot.Pending); - Assert.Equal(Clarifications.LastNamedKind.None, snapshot.LastNamed.Kind); + // The record of what was named is withheld: K21's tie-break rests on the caller having heard + // the list, which AgentCore cannot know on a graph row. + Assert.Equal(Clarifications.LastNamedKind.None, clarificationsObject.Read("applies_to").LastNamed.Kind); } // K42: no holder, no probe -- but the notice is still owed to a scoped run. diff --git a/tests/AgentCore.Application.Tests/Knowledge/ToolFacetOverlayTests.cs b/tests/AgentCore.Application.Tests/Knowledge/ToolFacetOverlayTests.cs new file mode 100644 index 00000000..54f906ff --- /dev/null +++ b/tests/AgentCore.Application.Tests/Knowledge/ToolFacetOverlayTests.cs @@ -0,0 +1,107 @@ +using AgentCore.Application.Knowledge; +using AgentCore.Domain.Knowledge; +using Xunit; + +namespace AgentCore.Application.Tests.Knowledge; + +/// +/// What a tool argument is allowed to change about the scope a turn already composed. +/// +/// +/// The rule these hold is an isolation rule, not a retrieval one. A host facet is who is asking and +/// an extractor facet is what they said; a facet off a tool argument is a guess about the subject. A +/// guess that could overwrite either would be an argument that moves the caller into another tenant. +/// +public sealed class ToolFacetOverlayTests +{ + [Fact] + public void Apply_NamedNothing_LeavesTheScopeAlone() + { + var composed = Scope((KnowledgeFacetOrigin.Host, "customer", "acme")); + + var (scope, narrowed) = ToolFacetOverlay.Apply(composed, named: null); + + Assert.Same(composed, scope); + Assert.False(narrowed); + } + + [Fact] + public void Apply_HostFacet_IsNotOverwritten() + { + var composed = Scope((KnowledgeFacetOrigin.Host, "customer", "acme")); + + var (scope, narrowed) = ToolFacetOverlay.Apply(composed, Named(("customer", "globex"))); + + Assert.Equal("acme", scope.Facets["customer"]); + Assert.Equal(KnowledgeFacetOrigin.Host, scope.Origins["customer"]); + Assert.False(narrowed); + } + + [Fact] + public void Apply_ExtractorFacet_IsNotOverwritten() + { + var composed = Scope((KnowledgeFacetOrigin.Extractor, "product_line", "treadmill")); + + var (scope, narrowed) = ToolFacetOverlay.Apply(composed, Named(("product_line", "bike"))); + + Assert.Equal("treadmill", scope.Facets["product_line"]); + Assert.False(narrowed); + } + + [Fact] + public void Apply_WildcardFacet_IsNarrowed() + { + var composed = Scope((KnowledgeFacetOrigin.Wildcard, "model", "*")); + + var (scope, narrowed) = ToolFacetOverlay.Apply(composed, Named(("model", "lcr-2023"))); + + Assert.Equal("lcr-2023", scope.Facets["model"]); + Assert.Equal(KnowledgeFacetOrigin.Tool, scope.Origins["model"]); + Assert.True(narrowed); + } + + [Fact] + public void Apply_FacetTheScopeDoesNotHold_IsAdded() + { + var (scope, narrowed) = ToolFacetOverlay.Apply(Scope(), Named(("model", "lcr-2023"))); + + Assert.Equal("lcr-2023", scope.Facets["model"]); + Assert.Equal(KnowledgeFacetOrigin.Tool, scope.Origins["model"]); + Assert.True(narrowed); + } + + [Fact] + public void Apply_OneNarrowsAndOneIsRefused_KeepsBoth() + { + var composed = Scope( + (KnowledgeFacetOrigin.Host, "customer", "acme"), + (KnowledgeFacetOrigin.Wildcard, "model", "*")); + + var (scope, narrowed) = ToolFacetOverlay.Apply( + composed, Named(("customer", "globex"), ("model", "lcr-2023"))); + + Assert.Equal("acme", scope.Facets["customer"]); + Assert.Equal("lcr-2023", scope.Facets["model"]); + Assert.True(narrowed); + } + + [Fact] + public void Apply_DoesNotMutateTheScopeItWasGiven() + { + var composed = Scope((KnowledgeFacetOrigin.Wildcard, "model", "*")); + + ToolFacetOverlay.Apply(composed, Named(("model", "lcr-2023"))); + + Assert.Equal("*", composed.Facets["model"]); + } + + private static KnowledgeScope Scope(params (KnowledgeFacetOrigin Origin, string Key, string Value)[] facets) + => new() + { + Facets = facets.ToDictionary(f => f.Key, f => f.Value, StringComparer.Ordinal), + Origins = facets.ToDictionary(f => f.Key, f => f.Origin, StringComparer.Ordinal), + }; + + private static Dictionary Named(params (string Key, string Value)[] facets) + => facets.ToDictionary(f => f.Key, f => f.Value, StringComparer.Ordinal); +} diff --git a/tests/AgentCore.Application.Tests/Ports/KnowledgeCapabilityTests.cs b/tests/AgentCore.Application.Tests/Ports/KnowledgeCapabilityTests.cs deleted file mode 100644 index 501354ed..00000000 --- a/tests/AgentCore.Application.Tests/Ports/KnowledgeCapabilityTests.cs +++ /dev/null @@ -1,126 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Domain.Knowledge; - -using Xunit; - -namespace AgentCore.Application.Tests.Ports; - -/// -/// Asking a knowledge store what else it can do. -/// -/// -/// Search is the one thing every store owes. Reading a facet vocabulary, or whole cards by an -/// exact facet value, are capabilities a store may or may not serve, and a caller has to be able -/// to ask. The question goes to the store itself, so one object is the only source of truth and a -/// store cannot claim a capability it does not have. -/// -public sealed class KnowledgeCapabilityTests -{ - [Fact] - public void AStoreServingAnExtension_HandsItBack() - { - IKnowledgeRetrievalPort store = new VocabularyStore(); - - Assert.Same(store, store.GetService(typeof(IFacetVocabularyPort))); - } - - [Fact] - public void AStoreServingNoExtension_AnswersNull() - { - IKnowledgeRetrievalPort store = new SearchOnlyStore(); - - Assert.Null(store.GetService(typeof(IFacetVocabularyPort))); - } - - [Fact] - public void AStoreAskedForItself_HandsItselfBack() - { - IKnowledgeRetrievalPort store = new SearchOnlyStore(); - - Assert.Same(store, store.GetService(typeof(IKnowledgeRetrievalPort))); - } - - [Fact] - public void AKeyedRequest_AnswersNull() - { - // A store that serves no keyed capability answers nothing rather than ignoring the key and - // handing back the unkeyed one, which would be a different object than the caller asked for. - IKnowledgeRetrievalPort store = new VocabularyStore(); - - Assert.Null(store.GetService(typeof(IFacetVocabularyPort), "replica")); - } - - [Fact] - public void ANullType_Throws() - { - IKnowledgeRetrievalPort store = new SearchOnlyStore(); - - Assert.Throws(() => store.GetService(null!)); - } - - [Fact] - public void TheGenericHelper_HandsBackTheTypedExtension() - { - IKnowledgeRetrievalPort store = new VocabularyStore(); - - Assert.Same(store, store.GetService()); - } - - [Fact] - public void TheGenericHelper_AnswersNullWhenTheStoreServesNothing() - { - IKnowledgeRetrievalPort store = new SearchOnlyStore(); - - Assert.Null(store.GetService()); - } - - [Fact] - public void AWrapperThatForwards_FindsTheCapabilityInside() - { - // The whole reason the question goes through a method and not a cast. A wrapper does not - // implement what it wraps, so 'is IFacetVocabularyPort' answers false on one and the - // capability disappears. Forwarding the question finds it. - var inner = new VocabularyStore(); - IKnowledgeRetrievalPort wrapper = new ForwardingStore(inner); - - Assert.False(wrapper is IFacetVocabularyPort); - Assert.Same(inner, wrapper.GetService()); - } - - /// A store that ranks and nothing else. - private sealed class SearchOnlyStore : IKnowledgeRetrievalPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } - - /// A store that also reads a facet vocabulary. - private sealed class VocabularyStore : IKnowledgeRetrievalPort, IFacetVocabularyPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - - public ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } - - /// A store wrapped in another, as a cache or a log would wrap one. - private sealed class ForwardingStore(IKnowledgeRetrievalPort inner) : IKnowledgeRetrievalPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => inner.SearchAsync(query, cancellationToken); - - public object? GetService(Type serviceType, object? serviceKey = null) - { - ArgumentNullException.ThrowIfNull(serviceType); - - return serviceKey is null && serviceType.IsInstanceOfType(this) - ? this - : inner.GetService(serviceType, serviceKey); - } - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionClarificationTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionClarificationTests.cs deleted file mode 100644 index 40060bd8..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionClarificationTests.cs +++ /dev/null @@ -1,363 +0,0 @@ -using System.Runtime.CompilerServices; -using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Tests.Knowledge.Fakes; -using AgentCore.Domain.Knowledge; -using AgentCore.TestSupport; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// Channel 1 (§7), driven through two real turns rather than by seeding the -/// ambient — K35's ordering is the thing under test: a near-tie the linker finds on turn 1 must reach -/// the model only on turn 2's own invocation, and never on a delegated sub-agent's. -/// -public sealed class CallSessionClarificationTests -{ - private const string AppliesToDescription = "The model, as printed on the machine."; - - private const string Yaml = - """ - apiVersion: agentcore/v1 - name: clarification-two-turn - state: - applies_to: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - agents: - items: - - id: only - """; - - private const string PrefetchYaml = - """ - apiVersion: agentcore/v1 - name: clarification-two-turn-prefetch - state: - applies_to: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - agents: - items: - - id: only - knowledge: { mode: prefetch, scoped: false } - """; - - private const string DelegationYaml = - """ - apiVersion: agentcore/v1 - name: clarification-delegation - state: - applies_to: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - tools: - - { id: ask_specialist, kind: agent, agent: specialist, description: Ask the specialist. } - agents: - defaults: - model: { ref: reply } - items: - - id: only - tools: [ ask_specialist ] - - id: specialist - model: { ref: specialist } - policy: - initial: greeting - stages: - - { id: greeting, agent: only } - """; - - [Fact] - public async Task NearTieOnTurn1_TurnTwosInvocationCarriesTheInstruction() - { - using SequencedChatClient reply = new( - "I don't have that on file yet.", - """{"applies_to":"the CT900"}""", - "let me check on that for you.", - "{}"); - - var session = Build(reply); - - await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); - - // Turn 1: nothing was pending before the extractor ran, so the caller's own turn carries no - // clarification. It is the near-tie itself, found by the linker after the model already - // answered — the linker's Ambiguous outcome does not retract what was just said (K16, K29). - Assert.Equal(string.Empty, reply.SystemText(0)); - - await session.RunTurnAsync("okay, thanks", TestContext.Current.CancellationToken); - - Assert.Equal( - ClarificationText.Instruction(AppliesToDescription, ["CT900", "CT900ENT"], 6, first: true), - reply.SystemText(2)); - } - - [Fact] - public async Task SameNearTie_InPrefetchMode_OnATurnWithNoToolCall_TheClarificationStillArrives() - { - // K29: the guard reads TurnContextScope, not the knowledge provider's own mode. Bound with a - // real StubKnowledgePort so this also proves the instruction rides alongside a second real - // provider's own card, rather than replacing it (K16). - using SequencedChatClient reply = new( - "I don't have that on file yet.", - """{"applies_to":"the CT900"}""", - "let me check on that for you.", - "{}"); - - var port = new StubKnowledgePort([Card("a")]); - var session = Build(reply, PrefetchYaml, port); - - await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); - await session.RunTurnAsync("okay, thanks", TestContext.Current.CancellationToken); - - // Prefetch mode means the model never calls a search tool at all, so this is also the "turn - // where the model calls no tool" half of the clause. The prefetch search itself ran (Calls - // is 2, once per turn) with no tool round involved anywhere. - Assert.Equal(2, port.Calls); - - var turn2 = reply.Requests[2]; - Assert.Contains(turn2, message => message.Text.Contains("card a", StringComparison.Ordinal)); - Assert.Contains( - turn2, - message => message.Text.Equals( - ClarificationText.Instruction(AppliesToDescription, ["CT900", "CT900ENT"], 6, first: true), - StringComparison.Ordinal)); - } - - [Fact] - public async Task DelegatedRun_CarriesNoInstruction_AndCountsNothing() - { - // K29: every kind: agent delegation is a fresh RunAsync on a fresh session, so the same - // session guard that protects a graph row protects a sub-agent too. - ScriptedDelegatingChatClient mainAgent = new( - (ToolName: null, Text: "okay, one moment."), - (ToolName: "ask_specialist", Text: string.Empty), - (ToolName: null, Text: "here is what the specialist said.")); - SequencedChatClient specialist = new("the specialist's answer."); - SequencedChatClient extractor = new("""{"applies_to":"the CT900"}""", "{}"); - - RoutingChatClientFactory chatClients = new(mainAgent); - chatClients.Route("reply", mainAgent); - chatClients.Route("specialist", specialist); - chatClients.Route("fill", extractor); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(DelegationYaml), new AgentCompilationContext(chatClients)); - var stateExtractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - VocabularyCache vocabulary = new(); - vocabulary.Replace("applies_to", ["CT900", "CT900ENT"], maxValues: 2000); - - var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), stateExtractor, vocabulary: vocabulary) - .Create("call-delegation"); - - await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); - await session.RunTurnAsync("ask the specialist", TestContext.Current.CancellationToken); - - const string named = "is not yet known"; - - // "one injected message" is a fact about ONE ClarificationProvider.InvokingAsync call, proven - // directly (with real access to the counter) by ClarificationProviderTests. The framework - // resends the base message list on every round of one RunAsync's tool loop, so the same - // injected line legitimately reaches the model more than once here — turn 2 calls the tool - // and then answers, two rounds of the same invocation. What only a real delegated run can - // prove is the other half: the specialist's own nested RunAsync must see none of it, on any - // of its own rounds, even though the same ClarificationProvider is bound to it too. - Assert.Equal(string.Empty, mainAgent.SystemText(0)); - Assert.Contains(named, mainAgent.SystemText(1), StringComparison.Ordinal); - Assert.Contains(named, mainAgent.SystemText(2), StringComparison.Ordinal); - - Assert.NotEmpty(specialist.Requests); - for (var request = 0; request < specialist.Requests.Count; request++) - { - Assert.DoesNotContain(named, specialist.SystemText(request), StringComparison.Ordinal); - } - } - - private static CallSession Build(SequencedChatClient reply, string yaml = Yaml, StubKnowledgePort? port = null) - { - var chatClients = new FakeChatClientFactory(reply); - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(yaml), - new AgentCompilationContext(chatClients) { Knowledge = port }); - - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - VocabularyCache vocabulary = new(); - vocabulary.Replace("applies_to", ["CT900", "CT900ENT"], maxValues: 2000); - - return new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: vocabulary) - .Create("call-1"); - } - - private static KnowledgeCard Card(string id) - => new() - { - CardId = id, - Text = "card " + id, - Authority = 3, - SourceRef = "ct900-om", - SourceLocator = "p.27", - Score = 0.87, - ViaLink = false, - }; - - /// - /// A model that calls a scripted tool name (or none) on each request, and records the full - /// message list of every request it answered — plus - /// 's tool-emitting behaviour, combined, because the delegation - /// row needs both: a deterministic per-call script (turn 1 must not call the tool) and full - /// message visibility (to read the system text a real provider chain produced). - /// - private sealed class ScriptedDelegatingChatClient : IChatClient - { - private readonly (string? ToolName, string Text)[] _script; - private int _calls; - - public ScriptedDelegatingChatClient(params (string? ToolName, string Text)[] script) => _script = script; - - public List> Requests { get; } = []; - - public string SystemText(int request) - { - lock (Requests) - { - return string.Join( - '\n', - Requests[request].Where(message => message.Role == ChatRole.System).Select(message => message.Text)); - } - } - - public async IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(messages); - - var index = Interlocked.Increment(ref _calls) - 1; - lock (Requests) - { - Requests.Add([.. messages]); - } - - await Task.Yield(); - - var (toolName, text) = _script[Math.Min(index, _script.Length - 1)]; - var responseId = Guid.NewGuid().ToString("N"); - - if (toolName is not null) - { - // AgentDelegationTool.Create wraps the inner agent through AsAIFunction(), which - // generates a required string argument named "query". A call with no arguments fails - // schema validation before the specialist is ever reached. - yield return new ChatResponseUpdate( - ChatRole.Assistant, - [new FunctionCallContent( - $"call_{index}", - toolName, - new Dictionary(StringComparer.Ordinal) { ["query"] = "check the model" })]) - { - ResponseId = responseId, - MessageId = responseId, - }; - yield break; - } - - yield return new ChatResponseUpdate(ChatRole.Assistant, text) - { - ResponseId = responseId, - MessageId = responseId, - }; - } - - public async Task GetResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - CancellationToken cancellationToken = default) - { - List updates = []; - await foreach (var update in GetStreamingResponseAsync(messages, options, cancellationToken) - .ConfigureAwait(false)) - { - updates.Add(update); - } - - return updates.ToChatResponse(); - } - - public object? GetService(Type serviceType, object? serviceKey = null) - { - ArgumentNullException.ThrowIfNull(serviceType); - return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; - } - - public void Dispose() - { - // Nothing to release. - } - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs deleted file mode 100644 index 6e955e5e..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionOffTopicTurnTests.cs +++ /dev/null @@ -1,101 +0,0 @@ -using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using AgentCore.Application.Tests.Fakes; -using AgentCore.TestSupport; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// Channel 1 across a turn the caller spent on something else. The instruction rides every turn -/// after the near-tie, whatever that turn says, so the reply — not the injection — is what charges -/// the ask: a turn answered with sympathy rather than the question must leave the slot free to ask -/// on the next turn that calls for it. -/// -public sealed class CallSessionOffTopicTurnTests -{ - private const string AppliesToDescription = "The model, as printed on the machine."; - - private const string Yaml = - """ - apiVersion: agentcore/v1 - name: clarification-off-topic - state: - applies_to: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - agents: - items: - - id: only - """; - - [Fact] - public async Task AnOffTopicTurn_DoesNotSpendTheQuestion() - { - using SequencedChatClient reply = new( - "I can help with that.", - """{"applies_to":"the CT900"}""", - "I'm sorry to hear that. What is going wrong?", - "{}", - "Is it the ct900 or the ct900ent?", - "{}", - "Happy to help.", - "{}"); - - var session = Build(reply); - var instruction = ClarificationText.Instruction( - AppliesToDescription, ["ct900", "ct900ent"], 6, first: true); - - await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); - Assert.Equal(string.Empty, reply.SystemText(0)); - - await session.RunTurnAsync("i hate you", TestContext.Current.CancellationToken); - Assert.Equal(instruction, reply.SystemText(2)); - - // The turn answered the caller instead of putting the question, so the ask went uncharged and - // the same instruction rides the next turn rather than the slot falling silent under K37. - await session.RunTurnAsync("which belt does mine take?", TestContext.Current.CancellationToken); - Assert.Equal(instruction, reply.SystemText(4)); - - // That reply named both candidates, so the ask is charged and K37 suppresses the repeat. - await session.RunTurnAsync("thanks", TestContext.Current.CancellationToken); - Assert.Equal(string.Empty, reply.SystemText(6)); - } - - private static CallSession Build(SequencedChatClient reply) - { - var chatClients = new FakeChatClientFactory(reply); - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(Yaml), new AgentCompilationContext(chatClients)); - - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - VocabularyCache vocabulary = new(); - vocabulary.Replace("applies_to", ["ct900", "ct900ent"], maxValues: 2000); - - return new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: vocabulary) - .Create("call-1"); - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs b/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs index 10e57e3f..e0581d27 100644 --- a/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/CallSessionProbeTests.cs @@ -5,7 +5,6 @@ using AgentCore.Application.Knowledge; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.State; using AgentCore.Application.Tests.Fakes; using AgentCore.Domain.Knowledge; using AgentCore.TestSupport; @@ -15,55 +14,13 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// §8's probe, and §7's channel 1, driven through real turns rather than by -/// seeding the ambient: the genuinely two-turn rows (K43's latch reset against K22's persistent -/// counter) and the genuinely graph-shaped row (K39) — both need the real turn loop's own -/// BeginTurn and row-kind wiring, which KnowledgeProbeTests's ambient-level tests -/// cannot exercise. +/// §8's probe, driven through real turns rather than by seeding the +/// ambient: the genuinely two-turn row (K43's latch reset against K22's persistent counter) needs +/// the real turn loop's own BeginTurn, which KnowledgeProbeTests's ambient-level +/// tests cannot exercise. /// public sealed class CallSessionProbeTests { - private const string AppliesToDescription = "The model, as printed on the machine."; - - private const string BrandDescription = "The brand of the caller's machine."; - - /// Two agents, run in order. Neither is scoped for search; both share channel 1. - private const string GraphYaml = - """ - apiVersion: agentcore/v1 - name: probe-graph - state: - applies_to: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - agents: - items: - - { id: researcher, model: { ref: researcher }, instructions: "look things up" } - - { id: responder, model: { ref: responder }, instructions: "answer the caller" } - graph: - pattern: sequential - agents: [ researcher, responder ] - """; - /// One tool-mode, scoped agent over two droppable facets, so K33 never blocks the drop. private const string ProbeYaml = """ @@ -74,12 +31,12 @@ public sealed class CallSessionProbeTests type: string writer: extractor description: "The model, as printed on the machine." - vocabulary: { from: knowledge } + enum: [CT900, CT900ENT] brand: type: string writer: extractor description: "The brand of the caller's machine." - vocabulary: { from: knowledge } + enum: [sole, spirit] extractor: model: { ref: fill } when: after_reply @@ -105,41 +62,6 @@ public sealed class CallSessionProbeTests knowledge: { mode: tool, scoped: true } """; - [Fact] - public async Task K39_GraphDocument_Channel1SaysNothing_OnEitherTurn() - { - // K39: channel 1's session guard passes only on a row whose session carries history -- rows 1 - // and 2. A graph row's participants each run on a session that is never the call's own, so the - // clarification a near-tie arms on turn 1 must stay silent for both nodes on turn 2 as well, - // where CallSessionClarificationTests proves it speaks on a row 1/2 document. - const string named = "is not yet known"; - - using ScriptedChatClient researcher = new("Let me check the order system."); - using ScriptedChatClient responder = new("Order 41 ships Friday."); - SequencedChatClient extractor = new("""{"applies_to":"the CT900"}""", "{}"); - - RoutingChatClientFactory chatClients = new(researcher); - chatClients.Route("researcher", researcher); - chatClients.Route("responder", responder); - chatClients.Route("fill", extractor); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(GraphYaml), new AgentCompilationContext(chatClients)); - var stateExtractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - VocabularyCache vocabulary = new(); - vocabulary.Replace("applies_to", ["CT900", "CT900ENT"], maxValues: 2000); - - var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), stateExtractor, vocabulary: vocabulary) - .Create("call-graph-probe"); - - await session.RunTurnAsync("I have a CT900 and a CT900ENT", TestContext.Current.CancellationToken); - await session.RunTurnAsync("okay, thanks", TestContext.Current.CancellationToken); - - Assert.DoesNotContain(named, researcher.FullText, StringComparison.Ordinal); - Assert.DoesNotContain(named, responder.FullText, StringComparison.Ordinal); - } - [Fact] public async Task TwoTurns_TheProbeAlwaysThrows_TheSecondTurnStillRunsAFreshProbeSearch() { @@ -166,12 +88,9 @@ public async Task TwoTurns_TheProbeAlwaysThrows_TheSecondTurnStillRunsAFreshProb ConfigurationLoader.LoadYaml(ProbeYaml), new AgentCompilationContext(chatClients) { Knowledge = port }); var stateExtractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - VocabularyCache vocabulary = new(); - vocabulary.Replace("applies_to", ["CT900", "CT900ENT"], maxValues: 2000); - vocabulary.Replace("brand", ["sole", "spirit"], maxValues: 2000); var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), stateExtractor, vocabulary: vocabulary) + compiled, new GuardEvaluator(compiled.Configuration.Guards), stateExtractor) .Create("call-probe-two-turn"); await session.RunTurnAsync("what model is it", TestContext.Current.CancellationToken); diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs deleted file mode 100644 index 8f0b19c6..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationProviderTests.cs +++ /dev/null @@ -1,540 +0,0 @@ -using System.Text.Json; -using AgentCore.Application.Configuration.Compilation; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Knowledge; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using AgentCore.Application.Tests.Fakes; -using AgentCore.Application.Tests.Knowledge.Fakes; -using AgentCore.Domain.Knowledge; -using Microsoft.Agents.AI; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// : §7 channel 1's loop, driven directly against a hand-built -/// and rather than a real turn. The rows that -/// depend on 's own turn ordering (K35) live in -/// instead. -/// -public sealed class ClarificationProviderTests -{ - private const string AppliesToDescription = "The model, as printed on the machine."; - - private const string BrandDescription = "The brand of the caller's machine."; - - private const string AmbiguityYaml = - """ - apiVersion: agentcore/v1 - name: clarification-wiring - state: - applies_to: { type: string, writer: extractor, description: "The model, as printed on the machine.", vocabulary: { from: knowledge } } - extractor: - model: { ref: fill } - when: after_reply - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - fromState: [applies_to] - wildcard: { value: "*", facets: [applies_to] } - ambiguity: { maxCandidates: 6, maxAsks: 2 } - agents: - items: - - id: only - knowledge: { mode: prefetch, scoped: false } - """; - - private const string NoAmbiguityYaml = - """ - apiVersion: agentcore/v1 - name: clarification-wiring-none - agents: - items: - - id: only - """; - - [Fact] - public void CompiledAgent_CarriesTheProvider_BeforeTheKnowledgeProvider_WhenAmbiguityIsDeclared() - { - using SequencedChatClient reply = new("hello there."); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(AmbiguityYaml), - new AgentCompilationContext(new FakeChatClientFactory(reply)) - { - Knowledge = new StubKnowledgePort([]), - }); - - var agent = ChatClientAgentOf(Assert.Single(compiled.Agents.Values)); - var providers = agent.AIContextProviders ?? []; - - var clarificationIndex = providers.ToList().FindIndex(p => p is ClarificationProvider); - var knowledgeIndex = providers.ToList().FindIndex( - p => p.GetType().Name.Contains("TextSearchProvider", StringComparison.Ordinal)); - - Assert.True(clarificationIndex >= 0, "the compiled agent must carry a ClarificationProvider."); - Assert.True(knowledgeIndex >= 0, "the compiled agent must still carry the knowledge provider."); - Assert.True(clarificationIndex < knowledgeIndex, "the clarification must bind before the knowledge provider."); - } - - [Fact] - public void CompiledAgent_CarriesNoProvider_WhenTheDocumentDeclaresNoAmbiguity() - { - // K19: an undeclared ambiguity: must not change what a document without it compiles to. - using SequencedChatClient reply = new("hello there."); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(NoAmbiguityYaml), new AgentCompilationContext(new FakeChatClientFactory(reply))); - - var agent = ChatClientAgentOf(Assert.Single(compiled.Agents.Values)); - var providers = agent.AIContextProviders ?? []; - - Assert.DoesNotContain(providers, p => p is ClarificationProvider); - } - - /// Reads the under whatever the compiler wrapped it in. - private static ChatClientAgent ChatClientAgentOf(AIAgent agent) - { - var inner = agent.GetService(); - Assert.NotNull(inner); - return inner; - } - - [Fact] - public async Task NoTurnIsOpen_EmitsNothing() - { - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - var context = await provider.InvokingAsync(Invoking(new StubSession()), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - } - - [Fact] - public async Task ARunOnAnotherSession_EmitsNothing() - { - // The K29 guard: a delegated kind: agent run's session never matches the caller's own turn. - StubSession callSession = new(); - StubSession delegatedSession = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var turn = TurnContextScope.Enter(new TurnContext { Session = callSession }); - using var ambients = TurnAmbients.Amend( - a => a with { State = State(("applies_to", AppliesToDescription)), Clarifications = clarifications }); - - var context = await provider.InvokingAsync( - Invoking(delegatedSession), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - Assert.Equal(0, clarifications.Read("applies_to").NamedAsks); - } - - [Fact] - public async Task MaxAsksZero_InjectsNothing_EvenWithAPendingSlot() - { - // K38's gate-only mode: the vocabulary and the gate still work, but the channel never speaks. - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var provider = Provider(maxAsks: 0, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, State(("applies_to", AppliesToDescription)), clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - Assert.Equal(0, clarifications.Read("applies_to").NamedAsks); - } - - [Fact] - public async Task NegativeMaxAsks_InjectsNothing_RatherThanLettingTheResetAskOnce() - { - // K38 again, at a maxAsks the schema does not itself bound. An == 0 gate would fall through - // to step 2's failing namedAsks < maxAsks test and let step 3's one reset speak. - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var provider = Provider(maxAsks: -1, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, State(("applies_to", AppliesToDescription)), clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - Assert.Equal(0, clarifications.Read("applies_to").NamedAsks); - Assert.False(clarifications.Read("applies_to").ResetSpent); - } - - [Fact] - public async Task ATurnThatNeverCommits_IsNotCharged_AndAsksAgainNextTurn() - { - // The instruction is injected before the run. A run that ended in the fallback reply never - // put the question, so the next turn must ask it rather than treat the slot as answered. - StubSession session = new(); - var clarifications = new Clarifications(); - var state = State(("applies_to", AppliesToDescription)); - - var provider = Provider(maxAsks: 1, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, state, clarifications); - - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - var turn1 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.NotNull(turn1.Messages); - - // Turn 1 threw or fell back: nothing commits it. - clarifications.BeginTurn(); - var turn2 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.NotNull(turn2.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - } - - [Fact] - public async Task NoPendingList_EmitsNothing() - { - StubSession session = new(); - var clarifications = new Clarifications(); - - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, State(("applies_to", AppliesToDescription)), clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - } - - [Fact] - public async Task AFilledSlot_IsSkipped_EvenWithAStalePendingList() - { - // Belt and braces: K30 clears Pending on a successful write, but the loop's own "still - // unfilled" test must not tell the model a filled slot "is not yet known" regardless. - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var state = State(("applies_to", AppliesToDescription)); - state.TryWrite("applies_to", JsonSerializer.SerializeToNode("ct900ent")); - - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, state, clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.Null(context.Messages); - } - - [Fact] - public async Task APendingSlot_SpeaksOnce_AndRecordsWhatWasNamed() - { - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, State(("applies_to", AppliesToDescription)), clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - var message = Assert.Single(context.Messages!); - Assert.Equal(ChatRole.System, message.Role); - Assert.Equal( - ClarificationText.Instruction(AppliesToDescription, ["ct900", "ct900ent"], 6, first: true), - message.Text); - - var snapshot = clarifications.Read("applies_to"); - Assert.Equal(1, snapshot.NamedAsks); - Assert.True(snapshot.AskedThisTurn); - Assert.Equal(Clarifications.LastNamedKind.Set, snapshot.LastNamed.Kind); - Assert.Equal(new HashSet(StringComparer.Ordinal) { "ct900", "ct900ent" }, snapshot.LastNamed.Values); - } - - [Fact] - public async Task TheUnchangedSet_IsNotAskedAgain_UntilItChanges() - { - // K37: the caller has already been asked this exact question. maxAsks: 1 makes the reset - // reachable in a small number of simulated turns. - StubSession session = new(); - var clarifications = new Clarifications(); - var state = State(("applies_to", AppliesToDescription)); - - var provider = Provider(maxAsks: 1, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, state, clarifications); - - // Turn 1: pending set A is new. Asked once (namedAsks -> 1). Each turn here commits, which - // is what CallSession does once the turn's own words reach the caller. - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - var turn1 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.NotNull(turn1.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - clarifications.CommitAsks("Is it a ct900 or a ct900ent?"); - - // Turn 2: the same set. namedAsks is at the cap (1), but K37 suppresses before the cap is - // even reached, because nothing changed. - clarifications.BeginTurn(); - var turn2 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.Null(turn2.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - Assert.False(clarifications.Read("applies_to").ResetSpent); - clarifications.CommitAsks("okay."); - - // Turn 3: the set changes. namedAsks is at the cap and differs from lastNamed, so the one - // reset fires: namedAsks returns to 1 (not 0), and the reset is spent. - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["ct800", "ct800ent"]); - var turn3 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.NotNull(turn3.Messages); - clarifications.CommitAsks("Is it a ct800 or a ct800ent?"); - var afterReset = clarifications.Read("applies_to"); - Assert.Equal(1, afterReset.NamedAsks); - Assert.True(afterReset.ResetSpent); - Assert.Equal( - new HashSet(StringComparer.Ordinal) { "ct800", "ct800ent" }, afterReset.LastNamed.Values); - - // Turn 4: the set changes again. The reset is already spent, so nothing is asked — the - // call's total stays at exactly 2 x maxAsks = 2, matching turn 1 and turn 3. - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["xt285", "xt385"]); - var turn4 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.Null(turn4.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - } - - [Fact] - public async Task TwoDifferentOverCapSets_AreNotBothSpoken() - { - // K37: above maxCandidates neither channel names a list, so two different over-cap sets read - // as the identical question and the sentinel record suppresses the second. - StubSession session = new(); - var clarifications = new Clarifications(); - var state = State(("applies_to", AppliesToDescription)); - - var provider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, state, clarifications); - - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["a", "b", "c", "d", "e", "f", "g"]); - var turn1 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - Assert.NotNull(turn1.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - clarifications.CommitAsks("Which model is it?"); - - clarifications.BeginTurn(); - clarifications.Update("applies_to", s => s.Pending = ["h", "i", "j", "k", "l", "m", "n"]); - var turn2 = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.Null(turn2.Messages); - Assert.Equal(1, clarifications.Read("applies_to").NamedAsks); - } - - [Fact] - public async Task TwoPendingSlots_SpeakTwoMessages_AndTheSecondOpensWithAnotherThing() - { - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("brand", s => s.Pending = ["sole", "spirit"]); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var provider = Provider( - maxAsks: 2, - maxCandidates: 6, - ("brand", BrandDescription), - ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn( - session, State(("brand", BrandDescription), ("applies_to", AppliesToDescription)), clarifications); - - var context = await provider.InvokingAsync(Invoking(session), TestContext.Current.CancellationToken); - - Assert.NotNull(context.Messages); - var messages = context.Messages!.ToList(); - Assert.Equal(2, messages.Count); - Assert.StartsWith("One thing is not yet known: ", messages[0].Text, StringComparison.Ordinal); - Assert.StartsWith("Another thing is not yet known: ", messages[1].Text, StringComparison.Ordinal); - } - - [Fact] - public async Task TheInstructionNeverRemovesACard() - { - // Chained the way MAF actually runs two providers on one agent: each InvokingAsync merges - // onto the context the one before it returned, so this proves the clarification is added - // context rather than a replacement — with no CallSession in between to obscure which - // provider did what. - StubSession session = new(); - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.Pending = ["ct900", "ct900ent"]); - - var knowledgeProvider = KnowledgeProviderFactory.Create( - new StubKnowledgePort([Card("a")]), - new ResolvedKnowledge(KnowledgeMode.Prefetch, Limit: 5, Citations: false, Scoped: false), - "agent-under-test", - new SourceLocatorCitationFormatter(), - loggers: null); - var clarificationProvider = Provider(maxAsks: 2, maxCandidates: 6, ("applies_to", AppliesToDescription)); - - using var scope = OpenTurn(session, State(("applies_to", AppliesToDescription)), clarifications); - - var afterKnowledge = await knowledgeProvider.InvokingAsync( - Invoking(session, "the screen says e33"), TestContext.Current.CancellationToken); - Assert.Contains(afterKnowledge.Messages!, message => message.Text.Contains("card a", StringComparison.Ordinal)); - -#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. - var merged = await clarificationProvider.InvokingAsync( - new AIContextProvider.InvokingContext(StubAgent.Instance, session, afterKnowledge), - TestContext.Current.CancellationToken); -#pragma warning restore MAAI001 - - Assert.Contains(merged.Messages!, message => message.Text.Contains("card a", StringComparison.Ordinal)); - Assert.Contains( - merged.Messages!, - message => message.Text.Contains("is not yet known", StringComparison.Ordinal)); - } - - private static ClarificationProvider Provider( - int maxAsks, int maxCandidates, params (string Slot, string Description)[] slots) - => new( - new KnowledgeAmbiguityConfiguration { MaxAsks = maxAsks, MaxCandidates = maxCandidates }, - [.. slots.Select(slot => slot.Slot)], - slots.ToDictionary(slot => slot.Slot, string? (slot) => slot.Description, StringComparer.Ordinal)); - - private static StateDocument State(params (string Slot, string Description)[] slots) - { - Dictionary declared = new(StringComparer.Ordinal); - foreach (var (slot, description) in slots) - { - declared[slot] = new StateSlotConfiguration - { - Type = StateSlotType.String, - Writer = StateWriter.Extractor, - Description = description, - }; - } - - var configuration = new AgentCoreConfiguration - { - ApiVersion = AgentCoreConfiguration.SupportedApiVersion, - Name = "clarification-provider-tests", - State = declared, - }; - - return new StateDocument(configuration); - } - - private static Scope OpenTurn(AgentSession session, StateDocument state, Clarifications clarifications) - { - var outer = TurnContextScope.Enter(new TurnContext { Session = session }); - var inner = TurnAmbients.Amend(a => a with { State = state, Clarifications = clarifications }); - return new Scope(outer, inner); - } - - /// - /// Runs the provider the way the framework runs it, over an otherwise empty context — so - /// context.Messages on the result is exactly what this provider itself contributed, with - /// no caller message riding along to make a null-versus-empty assertion pass by accident. - /// - private static AIContextProvider.InvokingContext Invoking(AgentSession session) - { -#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. - return new(StubAgent.Instance, session, new AIContext()); -#pragma warning restore MAAI001 - } - - /// Runs the provider with a caller message in view, for the knowledge provider's query. - private static AIContextProvider.InvokingContext Invoking(AgentSession session, string text) - { -#pragma warning disable MAAI001 // The context constructors are the framework's own experimental surface. - return new(StubAgent.Instance, session, new AIContext { Messages = [new ChatMessage(ChatRole.User, text)] }); -#pragma warning restore MAAI001 - } - - private static KnowledgeCard Card(string id) - => new() - { - CardId = id, - Text = "card " + id, - Authority = 3, - SourceRef = "ct900-om", - SourceLocator = "p.27", - Score = 0.87, - ViaLink = false, - }; - - private sealed class Scope : IDisposable - { - private readonly IDisposable _outer; - private readonly IDisposable _inner; - - public Scope(IDisposable outer, IDisposable inner) - { - _outer = outer; - _inner = inner; - } - - public void Dispose() - { - _inner.Dispose(); - _outer.Dispose(); - } - } - - private sealed class StubSession : AgentSession; - - /// Stands in for the agent the framework names on a context. Nothing here runs it. - private sealed class StubAgent : AIAgent - { - public static StubAgent Instance { get; } = new(); - - protected override ValueTask CreateSessionCoreAsync( - CancellationToken cancellationToken = default) - => new(new StubSession()); - - protected override ValueTask SerializeSessionCoreAsync( - AgentSession session, - JsonSerializerOptions? jsonSerializerOptions = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override ValueTask DeserializeSessionCoreAsync( - JsonElement serializedState, - JsonSerializerOptions? jsonSerializerOptions = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override Task RunCoreAsync( - IEnumerable messages, - AgentSession? session = null, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - - protected override IAsyncEnumerable RunCoreStreamingAsync( - IEnumerable messages, - AgentSession? session = null, - AgentRunOptions? options = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException(); - } -} diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs index ef4f04f2..b13b8bde 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationTextTests.cs @@ -4,8 +4,8 @@ namespace AgentCore.Application.Tests.Runtime; /// -/// The sentences §7 specifies for both ambiguity channels, rendered against §4's own -/// description: values so a human can read the result as English rather than a template. +/// The probe's note (§8), rendered against §4's own description: values so a human can read +/// the result as English rather than a template. /// public sealed class ClarificationTextTests { @@ -15,94 +15,6 @@ public sealed class ClarificationTextTests // §4's own value, verbatim: "The brand of the caller's machine." private const string BrandDescription = "The brand of the caller's machine."; - [Fact] - public void Instruction_TwoCandidates_FirstMessage_RendersTheBaseSentence() - { - var text = ClarificationText.Instruction( - AppliesToDescription, ["ct900", "ct900ent"], maxCandidates: 6, first: true); - - Assert.Equal( - "One thing is not yet known: The model, as printed on the machine. It is one of ct900 or " - + "ct900ent. Answer what the caller just said; where that calls for advice specific to one, ask " - + "the caller which first. Anything that applies to all of them is still fair game.", - text); - } - - [Fact] - public void Instruction_ThreeCandidates_JoinsWithAnOxfordComma() - { - var text = ClarificationText.Instruction( - AppliesToDescription, ["ct800", "ct900", "ct900ent"], maxCandidates: 6, first: true); - - Assert.Equal( - "One thing is not yet known: The model, as printed on the machine. It is one of ct800, ct900, " - + "or ct900ent. Answer what the caller just said; where that calls for advice specific to one, " - + "ask the caller which first. Anything that applies to all of them is still fair game.", - text); - } - - [Fact] - public void Instruction_OneCandidate_RendersTheConfirmSentence() - { - var text = ClarificationText.Instruction( - AppliesToDescription, ["ct900"], maxCandidates: 6, first: true); - - Assert.Equal( - "One thing is not yet confirmed: The model, as printed on the machine. Everything found is for " - + "ct900. Answer what the caller just said; where that calls for advice specific to it, ask the " - + "caller first whether that is what they have.", - text); - } - - [Fact] - public void Instruction_OverMaxCandidates_OmitsTheList() - { - var text = ClarificationText.Instruction( - AppliesToDescription, - ["ct800", "ct800ent", "ct900", "ct900ent", "xt285", "xt385", "xt485"], - maxCandidates: 6, - first: true); - - Assert.Equal( - "One thing is not yet known: The model, as printed on the machine. Answer what the caller just " - + "said; where that calls for advice specific to one, ask the caller first.", - text); - } - - [Fact] - public void Instruction_SecondMessage_OpensWithAnotherThing() - { - var text = ClarificationText.Instruction( - BrandDescription, ["sole", "spirit"], maxCandidates: 6, first: false); - - Assert.StartsWith("Another thing is not yet known: ", text, StringComparison.Ordinal); - Assert.DoesNotContain("One thing is not yet known", text, StringComparison.Ordinal); - } - - [Fact] - public void Instruction_SecondMessage_OneCandidate_OpensWithAnotherThing() - { - var text = ClarificationText.Instruction( - AppliesToDescription, ["ct900"], maxCandidates: 6, first: false); - - Assert.StartsWith("Another thing is not yet confirmed: ", text, StringComparison.Ordinal); - } - - [Fact] - public void Instruction_DescriptionFallsBackToTheSlotName_WhenTheCallerPassesIt() - { - // ClarificationText itself does not know about slots; the fallback to the slot name is the - // caller's job (ClarificationProvider). This fact only pins that the renderer treats - // whatever string it is given as the apposition, verbatim. - var text = ClarificationText.Instruction("applies_to", ["ct900", "ct900ent"], maxCandidates: 6, first: true); - - Assert.Equal( - "One thing is not yet known: applies_to It is one of ct900 or ct900ent. Answer what the caller " - + "just said; where that calls for advice specific to one, ask the caller which first. Anything " - + "that applies to all of them is still fair game.", - text); - } - [Fact] public void Note_TwoCandidates_JoinsWithAPlainComma_NotOr() { @@ -140,17 +52,4 @@ public void Note_OverMaxCandidates_OmitsTheList() + "Ask the caller, and do not answer from the knowledge base about it until they say.", text); } - - [Fact] - public void TwoOverCapSets_RenderTheIdenticalSentence() - { - // K37: two different over-maxCandidates sets say the same thing, which is what lets the - // sentinel record suppress the second one as a repeat rather than a new question. - var first = ClarificationText.Instruction( - AppliesToDescription, ["a", "b", "c", "d", "e", "f", "g"], maxCandidates: 6, first: true); - var second = ClarificationText.Instruction( - AppliesToDescription, ["h", "i", "j", "k", "l", "m", "n"], maxCandidates: 6, first: true); - - Assert.Equal(first, second); - } } diff --git a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs index 3239d9e9..c05c814e 100644 --- a/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs +++ b/tests/AgentCore.Application.Tests/Runtime/ClarificationsTests.cs @@ -123,31 +123,21 @@ public async Task Publish_LetsEveryWaiterReplayTheSameCards() } // ----------------------------------------------------------------------------------------- - // K41 and K43: BeginTurn opens a fresh turn. It clears the per-turn mark and the probe latch - // and its payload together, and never the counters — those are per-call, not per-turn. + // K43: BeginTurn opens a fresh turn. It clears the probe latch and its payload together, and + // never the counter — that is per-call, not per-turn. // ----------------------------------------------------------------------------------------- [Fact] - public void BeginTurn_ClearsTheLatchAndTheMark_AndLeavesTheCounters() + public void BeginTurn_ClearsTheLatch_AndLeavesTheCounter() { var clarifications = new Clarifications(); clarifications.ClaimProbe().Publish([]); - clarifications.Update("brand", s => - { - s.AskedThisTurn = true; - s.ProbeAsks = 3; - s.NamedAsks = 2; - s.ResetSpent = true; - }); + clarifications.Update("brand", s => s.ProbeAsks = 3); clarifications.BeginTurn(); - var brand = clarifications.Read("brand"); - Assert.False(brand.AskedThisTurn); - Assert.Equal(3, brand.ProbeAsks); - Assert.Equal(2, brand.NamedAsks); - Assert.True(brand.ResetSpent); + Assert.Equal(3, clarifications.Read("brand").ProbeAsks); // The latch is free again. Assert.True(clarifications.ClaimProbe().Won); @@ -205,9 +195,6 @@ public void SpentAndRestoreSpent_CarryTheBudget_AndNotWhatWasNamed() first.Update("applies_to", s => { s.ProbeAsks = 2; - s.NamedAsks = 1; - s.ResetSpent = true; - s.Pending = ["ct900", "ct900ent"]; s.LastNamed = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900" }); }); @@ -218,11 +205,8 @@ public void SpentAndRestoreSpent_CarryTheBudget_AndNotWhatWasNamed() var slot = resumed.Read("applies_to"); Assert.Equal(2, slot.ProbeAsks); - Assert.Equal(1, slot.NamedAsks); - Assert.True(slot.ResetSpent); - // The pending list and what was named belong to a turn the reconnected caller is not in. - Assert.Null(slot.Pending); + // What was named belongs to a turn the reconnected caller is not in. Assert.Equal(Clarifications.LastNamedKind.None, slot.LastNamed.Kind); } @@ -230,93 +214,33 @@ public void SpentAndRestoreSpent_CarryTheBudget_AndNotWhatWasNamed() public void Spent_LeavesOutASlotNothingHasAskedAbout() { var clarifications = new Clarifications(); - clarifications.Update("brand", s => s.Pending = ["sole", "spirit"]); + clarifications.Update( + "brand", + s => s.LastNamed = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "sole" })); Assert.Empty(clarifications.Spent()); } // ----------------------------------------------------------------------------------------- - // §7's ask is staged: reads see it at once, because step 1 and the probe's K41 skip both act on - // it this turn, but only a turn that answered the caller keeps it. - // ----------------------------------------------------------------------------------------- - [Fact] - public void Ask_IsVisibleAtOnce_ButDroppedByTheNextBeginTurn() - { - var clarifications = new Clarifications(); - var named = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900" }); - - clarifications.Ask("applies_to", named, spendsReset: false); - - var asked = clarifications.Read("applies_to"); - Assert.Equal(1, asked.NamedAsks); - Assert.True(asked.AskedThisTurn); - Assert.True(named.Names(asked.LastNamed)); - - clarifications.BeginTurn(); - - var dropped = clarifications.Read("applies_to"); - Assert.Equal(0, dropped.NamedAsks); - Assert.Equal(Clarifications.LastNamedKind.None, dropped.LastNamed.Kind); - } - - [Fact] - public void CommitAsks_KeepsTheAsk_AcrossTheTurnBoundary() - { - var clarifications = new Clarifications(); - var named = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900" }); - - clarifications.Ask("applies_to", named, spendsReset: false); - clarifications.CommitAsks("Is it a ct900?"); - clarifications.BeginTurn(); - - var kept = clarifications.Read("applies_to"); - Assert.Equal(1, kept.NamedAsks); - Assert.True(named.Names(kept.LastNamed)); - } - - [Fact] - public void Ask_ThatSpendsTheReset_ReturnsTheCounterToOne() - { - var clarifications = new Clarifications(); - clarifications.Update("applies_to", s => s.NamedAsks = 3); - - clarifications.Ask("applies_to", Clarifications.LastNamed.TooMany, spendsReset: true); - - var snapshot = clarifications.Read("applies_to"); - Assert.Equal(1, snapshot.NamedAsks); - Assert.True(snapshot.ResetSpent); - } - - // ----------------------------------------------------------------------------------------- - // Edit-and-resend: Withdraw clears what was named and what is pending, and leaves the ask - // counters untouched so a withdrawn segment cannot buy a fresh maxAsks budget. + // Edit-and-resend: Withdraw clears what was named, and leaves the ask counter untouched so a + // withdrawn segment cannot buy a fresh maxAsks budget. // ----------------------------------------------------------------------------------------- [Fact] - public void Withdraw_ClearsPendingAndLastNamed_AndLeavesTheCounters() + public void Withdraw_ClearsLastNamed_AndLeavesTheCounter() { var clarifications = new Clarifications(); clarifications.Update("brand", s => { - s.Pending = ["ct900", "ct900ent"]; s.LastNamed = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900", "ct900ent" }); s.ProbeAsks = 4; - s.NamedAsks = 1; - s.ResetSpent = true; - s.AskedThisTurn = true; }); clarifications.Withdraw(); var after = clarifications.Read("brand"); - Assert.Null(after.Pending); Assert.Equal(Clarifications.LastNamed.None, after.LastNamed); Assert.Equal(4, after.ProbeAsks); - Assert.Equal(1, after.NamedAsks); - Assert.True(after.ResetSpent); - - // BeginTurn's mark is a different lifetime; Withdraw must not touch it. - Assert.True(after.AskedThisTurn); } [Fact] @@ -326,12 +250,8 @@ public void Read_ANameNeverSeenBefore_StartsAtItsZeroValues() var slot = clarifications.Read("applies_to"); - Assert.Null(slot.Pending); Assert.Equal(Clarifications.LastNamed.None, slot.LastNamed); Assert.Equal(0, slot.ProbeAsks); - Assert.Equal(0, slot.NamedAsks); - Assert.False(slot.ResetSpent); - Assert.False(slot.AskedThisTurn); } [Fact] @@ -345,10 +265,10 @@ public void Update_TheSameName_SharesOneUnderlyingState() } // ----------------------------------------------------------------------------------------- - // §7/§8's compound transitions (K36): a slot's fields must move together as one step, or a - // concurrent reader can catch it between the two writes. This is the §8-step-6 shape - set the - // pending list and move a counter - reduced to its atomicity core: Pending is set exactly when - // ProbeAsks is odd, and a reader that ever sees them disagree caught a torn write. + // §8's compound transitions (K36): a slot's fields must move together as one step, or a + // concurrent reader can catch it between the two writes. This is the §8-step-6 shape - record + // what was named and move a counter - reduced to its atomicity core: LastNamed is set exactly + // when ProbeAsks is odd, and a reader that ever sees them disagree caught a torn write. // ----------------------------------------------------------------------------------------- [Fact] public async Task Update_ACompoundTransition_IsNeverObservedHalfApplied() @@ -365,23 +285,25 @@ public async Task Update_ACompoundTransition_IsNeverObservedHalfApplied() while (!stop.IsCancellationRequested) { var snapshot = clarifications.Read(slot); - var pendingIsSet = snapshot.Pending is not null; + var namedIsSet = snapshot.LastNamed.Kind == Clarifications.LastNamedKind.Set; var probeAsksIsOdd = snapshot.ProbeAsks % 2 != 0; - if (pendingIsSet != probeAsksIsOdd) + if (namedIsSet != probeAsksIsOdd) { Interlocked.Increment(ref tornObservations); } } }, TestContext.Current.CancellationToken); + var named = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "ct900", "ct900ent" }); + for (var i = 0; i < iterations; i++) { var opening = i % 2 == 0; clarifications.Update(slot, state => { - state.Pending = opening ? ["ct900", "ct900ent"] : null; + state.LastNamed = opening ? named : Clarifications.LastNamed.None; state.ProbeAsks++; }); } diff --git a/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs b/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs deleted file mode 100644 index 7ee2f532..00000000 --- a/tests/AgentCore.Application.Tests/Runtime/SpokenAskTests.cs +++ /dev/null @@ -1,67 +0,0 @@ -using AgentCore.Application.Runtime; -using Xunit; - -namespace AgentCore.Application.Tests.Runtime; - -/// -/// and the gate it drives: the ask -/// is charged to the slot only where the turn's own reply actually put the question. -/// -public sealed class SpokenAskTests -{ - [Fact] - public void NamedIn_ReplyNamesOneOfTheCandidates_IsTrue() - => Assert.True(SpokenAsk.NamedIn("Is it the ct900 or the ct900ent?", Named("ct900", "ct900ent"))); - - [Fact] - public void NamedIn_ReplyNamesNone_IsFalse() - => Assert.False(SpokenAsk.NamedIn("I'm sorry to hear that. What is going wrong?", Named("ct900", "ct900ent"))); - - [Fact] - public void NamedIn_ReplyRespellsACandidate_IsTrue() - { - // The fold drops separators, so a model that writes the value back with a space where the - // collection has a hyphen still counts as having asked. - Assert.True(SpokenAsk.NamedIn("Is it the F63 2013?", Named("F63-2013", "F63-2023"))); - } - - [Fact] - public void NamedIn_AnOverCapRecord_IsTrue() - { - // The over-cap instruction lists nothing, so there is no name to look for. Charging it is - // the only outcome that does not drop the ask on every turn alike. - Assert.True(SpokenAsk.NamedIn("I'm sorry to hear that.", Clarifications.LastNamed.TooMany)); - } - - [Fact] - public void CommitAsks_AReplyThatNeverPutTheQuestion_LeavesTheAskUncharged() - { - var clarifications = new Clarifications(); - - clarifications.Ask("applies_to", Named("ct900", "ct900ent"), spendsReset: false); - clarifications.CommitAsks("I'm sorry to hear that. What is going wrong?"); - clarifications.BeginTurn(); - - var slot = clarifications.Read("applies_to"); - Assert.Equal(0, slot.NamedAsks); - Assert.Equal(Clarifications.LastNamedKind.None, slot.LastNamed.Kind); - } - - [Fact] - public void CommitAsks_AReplyThatPutTheQuestion_ChargesTheAsk() - { - var clarifications = new Clarifications(); - var named = Named("ct900", "ct900ent"); - - clarifications.Ask("applies_to", named, spendsReset: false); - clarifications.CommitAsks("Is it the ct900 or the ct900ent?"); - clarifications.BeginTurn(); - - var slot = clarifications.Read("applies_to"); - Assert.Equal(1, slot.NamedAsks); - Assert.True(named.Names(slot.LastNamed)); - } - - private static Clarifications.LastNamed Named(params string[] values) - => Clarifications.LastNamed.Of(new HashSet(values, StringComparer.Ordinal)); -} diff --git a/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs b/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs deleted file mode 100644 index 3bbd896e..00000000 --- a/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerSiblingNarrowingTests.cs +++ /dev/null @@ -1,90 +0,0 @@ -using AgentCore.Application.State; -using Xunit; - -namespace AgentCore.Application.Tests.State; - -/// -/// The prefixed-sibling narrowing rule: what the caller spelled after the matched value decides -/// which of its longer siblings are still plausible. A sibling whose own extension is a peer of the -/// caller's — same length, same character class — and is not the one the caller said, is ruled out -/// by the caller's own words rather than offered back as a near-tie. -/// -public sealed class ExactStateValueLinkerSiblingNarrowingTests -{ - private static readonly HashSet NothingNamed = new(StringComparer.Ordinal); - - private static readonly string[] DatedCatalogue = ["F63", "F63-2013", "F63-2023", "F63-2026"]; - - private static readonly ExactStateValueLinker Linker = new(); - - [Fact] - public void Link_ExtensionIsAPeerOfEverySibling_LinksTheBareValue() - { - var result = Linker.Link("f63 2016", Vocabulary(DatedCatalogue), NothingNamed); - - AssertLinked(result, "F63"); - } - - [Fact] - public void Link_ExtensionIsAPeerOfOnlySomeSiblings_KeepsTheRest() - { - var result = Linker.Link("f63 2016", Vocabulary("F63", "F63-2013", "F63-2016B"), NothingNamed); - - AssertAmbiguous(result, "F63", "F63-2016B"); - } - - [Fact] - public void Link_ExtensionOfADifferentCharacterClass_DecidesNothing() - { - var result = Linker.Link("f63 console", Vocabulary(DatedCatalogue), NothingNamed); - - AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); - } - - [Fact] - public void Link_ExtensionOfADifferentLength_DecidesNothing() - { - var result = Linker.Link("a CT800 please", Vocabulary("ct800", "ct800ent"), NothingNamed); - - AssertAmbiguous(result, "ct800", "ct800ent"); - } - - [Fact] - public void Link_NoExtensionAtAll_LeavesEverySiblingStanding() - { - var result = Linker.Link("f63", Vocabulary(DatedCatalogue), NothingNamed); - - AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); - } - - [Fact] - public void Link_ExtensionThatStartsASibling_KeepsThatSibling() - { - var result = Linker.Link("f63 20", Vocabulary(DatedCatalogue), NothingNamed); - - AssertAmbiguous(result, "F63", "F63-2013", "F63-2023", "F63-2026"); - } - - private static VocabularyView Vocabulary(params string[] values) - { - Dictionary normalisedToOriginal = new(StringComparer.Ordinal); - foreach (var value in values) - { - normalisedToOriginal[VocabularyFold.Fold(value)] = value; - } - - return new VocabularyView { NormalisedToOriginal = normalisedToOriginal, Originals = values }; - } - - private static void AssertLinked(LinkResult result, string expected) - { - Assert.Equal(LinkOutcome.Linked, result.Outcome); - Assert.Equal([expected], result.Candidates); - } - - private static void AssertAmbiguous(LinkResult result, params string[] expectedSortedAscending) - { - Assert.Equal(LinkOutcome.Ambiguous, result.Outcome); - Assert.Equal(expectedSortedAscending, result.Candidates); - } -} diff --git a/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerTests.cs b/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerTests.cs deleted file mode 100644 index d09b6bb9..00000000 --- a/tests/AgentCore.Application.Tests/State/ExactStateValueLinkerTests.cs +++ /dev/null @@ -1,358 +0,0 @@ -using AgentCore.Application.State; -using Xunit; - -namespace AgentCore.Application.Tests.State; - -/// -/// The §12 linker table: every row asserts a claim an earlier revision of the design got wrong in -/// prose. The vocabulary and mentions are the catalogue linker_v9.py (the Python reference -/// the C# port was cross-checked against) uses, so a failure here can be compared against that -/// script directly. -/// -/// -/// Every non-ASCII literal here is a \uXXXX escape sequence, never a typed character — the same -/// rule follows, for the reason its header explains: a typed -/// decomposed character reaches disk pre-composed and the row would measure nothing. -/// -public sealed class ExactStateValueLinkerTests -{ - private static readonly HashSet NothingNamed = new(StringComparer.Ordinal); - - private static readonly string[] Catalogue = - [ - "f63", "f65", "f80", "f85", "tt8", - "ct800", "ct800ent", "ct850", "ct850ent", - "xt185", "xt285", "xt285s", "xt385", - "ct900", "ct900ent", "ctsbs900", "sole", - ]; - - private static readonly string[] Brands = ["sole", "truetread", "lifefitness"]; - - // U+0E01 is the Thai consonant ko kai; U+0E48 and U+0E49 are the mai ek and mai tho tone - // marks, both NonSpacingMark. The pair differs only by which mark it carries. - private static readonly string[] ThaiToneMarkPair = - [ - "\u0E01\u0E48900", - "\u0E01\u0E49900", - ]; - - // U+0915 is the Devanagari consonant ka; U+093E and U+094B are the aa and o vowel signs, - // both SpacingCombiningMark. - private static readonly string[] DevanagariPair = - [ - "\u0915\u093E900", - "\u0915\u094B900", - ]; - - private static readonly ExactStateValueLinker Linker = new(); - - [Fact] - public void Link_JoinedTwoTokenRun_LinksWithEmptyLastNamed() - { - var result = Linker.Link("CT900 ENT", Vocabulary(Catalogue), NothingNamed); - - AssertLinked(result, "ct900ent"); - } - - [Fact] - public void Link_ContainmentSwallowsTheShorterHit_LinksTheLongerValue() - { - var result = Linker.Link("a Sole F80", Vocabulary("f80", "solef80"), NothingNamed); - - AssertLinked(result, "solef80"); - } - - [Fact] - public void Link_DisjointSpansOfOneValue_ContainmentDoesNotRequireTheLongerHitToStartTheSame() - { - var result = Linker.Link("CT 900 ENT", Vocabulary("ct900", "900ent", "ct900ent"), NothingNamed); - - AssertLinked(result, "ct900ent"); - } - - [Fact] - public void Link_TwoDifferentIdsNamedInOneMention_IsAmbiguousNotASilentPick() - { - var result = Linker.Link("I have a CT900 and a CT900ENT", Vocabulary(Catalogue), NothingNamed); - - AssertAmbiguous(result, "ct900", "ct900ent"); - } - - [Fact] - public void Link_BareIdAloneWithEmptyLastNamed_IsAmbiguousWithItsPrefixedSibling() - { - var result = Linker.Link("CT900", Vocabulary(Catalogue), NothingNamed); - - AssertAmbiguous(result, "ct900", "ct900ent"); - } - - [Fact] - public void Link_BareIdAloneWithItselfInLastNamed_LinksIt() - { - var result = Linker.Link("CT900", Vocabulary(Catalogue), Named("ct900", "ct900ent", "ctsbs900")); - - AssertLinked(result, "ct900"); - } - - [Fact] - public void Link_UnrelatedIdWithAForeignLastNamed_LinksWithoutNeedingTheTieBreak() - { - var result = Linker.Link("an XT385", Vocabulary(Catalogue), Named("ct900", "ct900ent", "ctsbs900")); - - AssertLinked(result, "xt385"); - } - - [Fact] - public void Link_StrictPrefixHitWithEmptyLastNamed_IsAmbiguousNeverLinked() - { - var result = Linker.Link("a CT800", Vocabulary(Catalogue), NothingNamed); - - AssertAmbiguous(result, "ct800", "ct800ent"); - } - - [Fact] - public void Link_TwoNonPrefixIdsNamedTogether_IsAmbiguousWithTheSurvivingHits() - { - var result = Linker.Link("a CT900 and an XT385", Vocabulary(Catalogue), NothingNamed); - - AssertAmbiguous(result, "ct900", "xt385"); - } - - [Fact] - public void Link_NoRealIdSpelledOut_IsNoMatch() - { - var result = Linker.Link("so LE brand", Vocabulary(Catalogue), NothingNamed); - - AssertNoMatch(result); - } - - [Fact] - public void Link_CommaBreaksTheJoin_IsNoMatch() - { - var result = Linker.Link("my CT, 900 hours in", Vocabulary(Catalogue), NothingNamed); - - AssertNoMatch(result); - } - - [Fact] - public void Link_DotJoiner_Links() - { - var result = Linker.Link("CT. 900", Vocabulary(Catalogue), Named("ct900")); - - AssertLinked(result, "ct900"); - } - - [Fact] - public void Link_HyphenJoiner_Links() - { - var result = Linker.Link("CT - 900", Vocabulary(Catalogue), Named("ct900")); - - AssertLinked(result, "ct900"); - } - - [Fact] - public void Link_DoubleDotJoiner_Links() - { - var result = Linker.Link("C.T. 900", Vocabulary(Catalogue), Named("ct900")); - - AssertLinked(result, "ct900"); - } - - [Fact] - public void Link_BareConsoleWord_DoesNotFuzzyMatchSoleInsideIt() - { - var result = Linker.Link("the console is broken", Vocabulary(Catalogue), NothingNamed); - - AssertNoMatch(result); - } - - [Fact] - public void Link_ConsoleSentenceAlsoNamingSole_LinksSole() - { - var result = Linker.Link("the console is broken on my Sole", Vocabulary(Catalogue), NothingNamed); - - AssertLinked(result, "sole"); - } - - [Fact] - public void Link_DigitFreeTwoWordValue_JoinsOnTheThreeRuneRule() - { - var result = Linker.Link("a Life Fitness machine", Vocabulary(Brands), NothingNamed); - - AssertLinked(result, "lifefitness"); - } - - [Fact] - public void Link_MixedCaseVocabularyWithTieBreak_LinksTheCollectionsOwnSpelling() - { - var result = Linker.Link("a CT900", Vocabulary("CT900", "CT900ENT"), Named("CT900")); - - AssertLinked(result, "CT900"); - } - - [Fact] - public void Link_MixedCasePrefixWithNoTieBreak_CandidatesStayOrdinallySorted() - { - // "CT900ENT" sorts before "ct900" under StringComparer.Ordinal (uppercase before - // lowercase), so a bare prepend of the exact hit ahead of a separately sorted prefix list - // would leave this pair out of order. This locks in the fix. - var result = Linker.Link("a ct900", Vocabulary("ct900", "CT900ENT"), NothingNamed); - - AssertAmbiguous(result, "CT900ENT", "ct900"); - } - - [Fact] - public void Link_SpacedVocabularyValue_Links() - { - var result = Linker.Link("a CT 900", Vocabulary("CT 900"), NothingNamed); - - AssertLinked(result, "CT 900"); - } - - [Fact] - public void Link_ThaiToneMarkMentionBare_LinksItsOwnId() - { - var result = Linker.Link(ThaiToneMarkPair[0], Vocabulary(ThaiToneMarkPair), NothingNamed); - - AssertLinked(result, ThaiToneMarkPair[0]); - } - - [Fact] - public void Link_ThaiToneMarkMentionInsideASentence_LinksItsOwnId() - { - var result = Linker.Link("a " + ThaiToneMarkPair[0] + " please", Vocabulary(ThaiToneMarkPair), NothingNamed); - - AssertLinked(result, ThaiToneMarkPair[0]); - } - - [Fact] - public void Link_ThaiToneMarkMentionSpacedBeforeTheDigits_LinksItsOwnId() - { - var result = Linker.Link("\u0E01\u0E48 900", Vocabulary(ThaiToneMarkPair), NothingNamed); - - AssertLinked(result, ThaiToneMarkPair[0]); - } - - [Fact] - public void Link_TheOtherThaiToneMarkMention_DoesNotCrossLinkToItsSibling() - { - var result = Linker.Link(ThaiToneMarkPair[1], Vocabulary(ThaiToneMarkPair), NothingNamed); - - AssertLinked(result, ThaiToneMarkPair[1]); - } - - [Fact] - public void Link_DevanagariMention_LinksItsOwnId() - { - var result = Linker.Link("my " + DevanagariPair[0], Vocabulary(DevanagariPair), NothingNamed); - - AssertLinked(result, DevanagariPair[0]); - } - - [Fact] - public void BuildCandidates_SixtyTokenMention_StaysWithinTheFourTimesTokenCountBound() - { - var mention = string.Join(' ', Enumerable.Range(0, 60).Select(i => $"word{i}")); - var (tokens, separators) = VocabularyFold.Tokenize(mention); - - var candidates = ExactStateValueLinker.BuildCandidates(tokens, separators); - - Assert.Equal(60, tokens.Count); - Assert.True(candidates.Count <= 4 * 60, $"expected at most {4 * 60} candidates, got {candidates.Count}"); - Assert.Equal(234, candidates.Count); - } - - [Theory] - [InlineData(LinkOutcome.Linked, 0)] - [InlineData(LinkOutcome.Linked, 2)] - [InlineData(LinkOutcome.NoMatch, 1)] - [InlineData(LinkOutcome.Ambiguous, 1)] - public void LinkResult_ACandidateCountThatContradictsTheOutcome_IsRefused(LinkOutcome outcome, int candidates) - { - // IStateValueLinker is public, so a host linker is arbitrary code. The extractor indexes - // Candidates[0] on a Linked verdict rather than re-testing what this type already promises. - Assert.Throws( - () => new LinkResult(outcome, [.. Enumerable.Range(0, candidates).Select(i => $"v{i}")])); - } - - private static HashSet Named(params string[] values) - => new HashSet(values, StringComparer.Ordinal); - - private static VocabularyView Vocabulary(params string[] values) - { - Dictionary normalisedToOriginal = new(StringComparer.Ordinal); - foreach (var value in values) - { - normalisedToOriginal[VocabularyFold.Fold(value)] = value; - } - - return new VocabularyView { NormalisedToOriginal = normalisedToOriginal, Originals = values }; - } - - private static void AssertLinked(LinkResult result, string expected) - { - Assert.Equal(LinkOutcome.Linked, result.Outcome); - Assert.Equal([expected], result.Candidates); - } - - private static void AssertAmbiguous(LinkResult result, params string[] expectedSortedAscending) - { - Assert.Equal(LinkOutcome.Ambiguous, result.Outcome); - Assert.Equal(expectedSortedAscending, result.Candidates); - } - - private static void AssertNoMatch(LinkResult result) - { - Assert.Equal(LinkOutcome.NoMatch, result.Outcome); - Assert.Empty(result.Candidates); - } -} - -/// -/// : the name-keyed registry K12 asks for, always seeded with -/// exact. -/// -public sealed class StateValueLinkersTests -{ - [Fact] - public void Resolve_Exact_ReturnsTheBuiltInLinker() - { - var registry = new StateValueLinkers([]); - - var linker = registry.Resolve("exact"); - - Assert.IsType(linker); - } - - [Fact] - public void Names_AlwaysIncludesExactEvenWithNoHostLinkers() - { - var registry = new StateValueLinkers([]); - - Assert.Contains("exact", registry.Names); - } - - [Fact] - public void Resolve_AnUnregisteredName_Throws() - { - var registry = new StateValueLinkers([]); - - Assert.Throws(() => registry.Resolve("bogus")); - } - - [Fact] - public void Constructor_TwoHostLinkersShareAName_Throws() - => Assert.Throws(() => new StateValueLinkers( - [ - new NamedLinker("custom"), - new NamedLinker("custom"), - ])); - - private sealed class NamedLinker(string name) : IStateValueLinker - { - public string Name { get; } = name; - - public LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet lastNamed) - => throw new NotSupportedException(); - } -} diff --git a/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs b/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs index 786390da..27b643f6 100644 --- a/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs +++ b/tests/AgentCore.Application.Tests/State/StateDocumentTests.cs @@ -60,31 +60,6 @@ public sealed class StateDocumentTests }, }; - private static AgentCoreConfiguration WithVocabularySlot() => new() - { - ApiVersion = "agentcore/v1", - Name = "doc", - State = new Dictionary(StringComparer.Ordinal) - { - ["applies_to"] = new() - { - Type = StateSlotType.String, - Writer = StateWriter.Extractor, - Vocabulary = new SlotVocabularyConfiguration { From = "knowledge" }, - }, - }, - }; - - private static Dictionary VocabularyOf(params string[] originals) - => new Dictionary(StringComparer.Ordinal) - { - ["applies_to"] = new VocabularyView - { - NormalisedToOriginal = originals.ToDictionary(VocabularyFold.Fold, StringComparer.Ordinal), - Originals = originals, - }, - }; - [Fact] public void TryWrite_ValueOutsideTheEnum_IsRefused() { @@ -113,24 +88,6 @@ public void TryWrite_ValueInsideTheEnum_IsAccepted() Assert.Equal("f65", state.Read("applies_to")?.GetValue()); } - [Fact] - public void TryWrite_ValueOutsideTheVocabularySnapshot_IsRefused() - { - var state = new StateDocument(WithVocabularySlot(), vocabulary: VocabularyOf("f63", "f65")); - - Assert.False(state.TryWrite("applies_to", JsonValue.Create("f80"))); - Assert.True(state.IsUnfilled("applies_to")); - } - - [Fact] - public void TryWrite_ValueInsideTheVocabularySnapshot_IsAccepted() - { - var state = new StateDocument(WithVocabularySlot(), vocabulary: VocabularyOf("f63", "f65")); - - Assert.True(state.TryWrite("applies_to", JsonValue.Create("f65"))); - Assert.Equal("f65", state.Read("applies_to")?.GetValue()); - } - [Fact] public void WrittenSlots_HandsOutAFreshCopyEveryCall() { diff --git a/tests/AgentCore.Application.Tests/State/StateExtractorLinkerTests.cs b/tests/AgentCore.Application.Tests/State/StateExtractorLinkerTests.cs deleted file mode 100644 index 0e610544..00000000 --- a/tests/AgentCore.Application.Tests/State/StateExtractorLinkerTests.cs +++ /dev/null @@ -1,299 +0,0 @@ -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Runtime; -using AgentCore.Application.State; -using AgentCore.Application.Tests.Fakes; -using Microsoft.Extensions.AI; -using Xunit; - -namespace AgentCore.Application.Tests.State; - -/// -/// The gate and the linker in the extractor path (design §6): what StateExtractor.Write does -/// with a vocabulary: slot's free-text answer, and the K19 guarantee that nothing changes for -/// a document that declares none. -/// -public sealed class StateExtractorLinkerTests -{ - private const string VocabularyYaml = - """ - apiVersion: agentcore/v1 - name: linker - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge } } - brand: { type: string, writer: extractor, enum: [f80, f65] } - extractor: - model: { ref: fill } - when: after_reply - agents: - items: - - { id: only } - """; - - private const string UnknownLinkerYaml = - """ - apiVersion: agentcore/v1 - name: unknown-linker - state: - applies_to: { type: string, writer: extractor, vocabulary: { from: knowledge, linker: mine } } - extractor: - model: { ref: fill } - when: after_reply - agents: - items: - - { id: only } - """; - - private const string NoVocabularyYaml = - """ - apiVersion: agentcore/v1 - name: no-vocabulary - state: - callerSaidGoodbye: { type: boolean, default: false, writer: extractor } - extractor: - model: { ref: fill } - when: after_reply - agents: - items: - - { id: only } - """; - - private static readonly AgentCoreConfiguration VocabularyDocument = ConfigurationLoader.LoadYaml(VocabularyYaml); - - private static readonly AgentCoreConfiguration NoVocabularyDocument = ConfigurationLoader.LoadYaml(NoVocabularyYaml); - - private static readonly AgentCoreConfiguration UnknownLinkerDocument = ConfigurationLoader.LoadYaml(UnknownLinkerYaml); - - [Fact] - public void ALinkedOutcome_WritesTheCollectionsSpelling() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - - var result = extractor.Write(state, """{ "applies_to": "the CT900ENT" }""", clarifications); - - Assert.Equal(1, result.Filled); - Assert.Equal("CT900ENT", state.Read("applies_to")?.GetValue()); - } - - [Fact] - public void AnAmbiguousOutcome_LeavesTheSlotUnfilledAndSetsThePendingList() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - - var result = extractor.Write(state, """{ "applies_to": "the CT900" }""", clarifications); - - Assert.True(state.IsUnfilled("applies_to")); - Assert.Equal(0, result.Filled); - Assert.Equal(["CT900", "CT900ENT"], clarifications.Read("applies_to").Pending); - } - - [Fact] - public void APendingListAlreadySetByAnotherChannel_ANoMatchLeavesItAlone() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - clarifications.Update("applies_to", s => s.Pending = ["OTHER1", "OTHER2"]); - - extractor.Write(state, """{ "applies_to": "the elliptical machine" }""", clarifications); - - // NoMatch does nothing at all — the pending list survives untouched. - Assert.Equal(["OTHER1", "OTHER2"], clarifications.Read("applies_to").Pending); - Assert.True(state.IsUnfilled("applies_to")); - } - - [Fact] - public void AnAmbiguousOutcome_OverwritesAnExistingPendingListWithTheNewNearTie() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT", "CT850", "CT850ENT"); - clarifications.Update("applies_to", s => s.Pending = ["CT900", "CT900ENT"]); - - extractor.Write(state, """{ "applies_to": "the CT850" }""", clarifications); - - // A caller who near-ties a second, different pair must not be silently dropped because - // the first pair is still sitting unresolved: extraction runs after_reply, so this is the - // caller's own later words beating whatever was pending (§7's recovery path). - Assert.True(state.IsUnfilled("applies_to")); - Assert.Equal(["CT850", "CT850ENT"], clarifications.Read("applies_to").Pending); - } - - [Fact] - public void ANoMatchOutcome_LeavesTheSlotAndThePendingListAlone() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - - var result = extractor.Write(state, """{ "applies_to": "the elliptical machine" }""", clarifications); - - Assert.True(state.IsUnfilled("applies_to")); - Assert.Equal(0, result.Filled); - Assert.Null(clarifications.Read("applies_to").Pending); - } - - [Fact] - public void AWrittenSlot_NamedAgainByItsShorterPrefix_IsHeardAsANearTie_NotOverwritten() - { - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - - // Simulates a prior ask that named both candidates. Left in place, this would let the - // tie-break in §6 step 4 fire on the second mention and silently replace the caller's - // confirmed machine — exactly the bug K30's clear exists to prevent. - clarifications.Update( - "applies_to", - slot => slot.LastNamed = Clarifications.LastNamed.Of( - new HashSet(StringComparer.Ordinal) { "CT900", "CT900ENT" })); - - extractor.Write(state, """{ "applies_to": "the CT900ENT" }""", clarifications); - - Assert.Equal("CT900ENT", state.Read("applies_to")?.GetValue()); - Assert.Equal(Clarifications.LastNamedKind.None, clarifications.Read("applies_to").LastNamed.Kind); - - extractor.Write(state, """{ "applies_to": "the CT900" }""", clarifications); - - // Ambiguous, not Linked: LastNamed was cleared by the write above, so the shorter mention - // cannot tie-break and the filled slot stands. - Assert.Equal("CT900ENT", state.Read("applies_to")?.GetValue()); - Assert.Equal(["CT900", "CT900ENT"], clarifications.Read("applies_to").Pending); - } - - [Fact] - public void AnEnumOnlySlot_ASuccessfulWrite_ClearsItsPendingListAndLastNamed() - { - // K30 is unconditional over every slot StateExtractor.Write iterates, enum:-only slots - // included — not just the vocabulary: slots the linker touches. "brand" has a hand-written - // enum: and never sees a linker (§6's closing paragraph), so this is the one channel that - // can ever populate its Pending/LastNamed: a probe or a prior ask, simulated here directly. - var (extractor, state, clarifications) = Build("CT900", "CT900ENT"); - - clarifications.Update("brand", slot => - { - slot.Pending = ["f80", "f65"]; - slot.LastNamed = Clarifications.LastNamed.Of(new HashSet(StringComparer.Ordinal) { "f80", "f65" }); - }); - - extractor.Write(state, """{ "brand": "f80" }""", clarifications); - - Assert.Equal("f80", state.Read("brand")?.GetValue()); - Assert.Null(clarifications.Read("brand").Pending); - Assert.Equal(Clarifications.LastNamedKind.None, clarifications.Read("brand").LastNamed.Kind); - } - - [Fact] - public void ANonStringAnswerToAVocabularySlot_StillGoesThroughTheLinker() - { - // The schema asks for a string, but nothing stops a model answering the bare number. Coerced - // straight to "900" it would pass the gate, because "900" is a member — silently picking one - // side of the near-tie the linker exists to refuse. - var (extractor, state, clarifications) = Build("900", "900ENT"); - - var result = extractor.Write(state, """{ "applies_to": 900 }""", clarifications); - - Assert.True(state.IsUnfilled("applies_to")); - Assert.Equal(0, result.Filled); - Assert.Equal(["900", "900ENT"], clarifications.Read("applies_to").Pending); - } - - [Fact] - public void ALinkerThatThrows_RefusesTheSlotAndNotTheTurn() - { - var client = new ScriptedChatClient("{}"); - var extractor = new StateExtractor(UnknownLinkerDocument, client, new StateValueLinkers([])); - var state = new StateDocument( - UnknownLinkerDocument, - vocabulary: new Dictionary(StringComparer.Ordinal) - { - ["applies_to"] = ViewOf("CT900"), - }); - - // "mine" is registered nowhere, so Resolve throws. Section 8.7: that must cost the slot, not - // the call. - var result = extractor.Write(state, """{ "applies_to": "the CT900" }""", new Clarifications()); - - Assert.True(result.Deserialized); - Assert.Equal(1, result.Rejected); - Assert.True(state.IsUnfilled("applies_to")); - } - - [Fact] - public async Task NoVocabularySlot_TheRequestIsByteIdenticalThroughTheInternalOverload() - { - RecordingChatClient viaPublicApi = new("""{ "callerSaidGoodbye": null }"""); - StateExtractor publicExtractor = new(NoVocabularyDocument, viaPublicApi); - - await publicExtractor.ExtractAsync( - new StateDocument(NoVocabularyDocument), - [new ChatMessage(ChatRole.User, "hello")], - TestContext.Current.CancellationToken); - - RecordingChatClient viaInternalApi = new("""{ "callerSaidGoodbye": null }"""); - StateExtractor internalExtractor = new(NoVocabularyDocument, viaInternalApi, new StateValueLinkers([])); - - await internalExtractor.ExtractAsync( - new StateDocument(NoVocabularyDocument), - [new ChatMessage(ChatRole.User, "hello")], - new Clarifications(), - TestContext.Current.CancellationToken); - - Assert.NotNull(viaPublicApi.LastMessages); - Assert.NotNull(viaInternalApi.LastMessages); - Assert.Equal(Render(viaPublicApi.LastMessages!), Render(viaInternalApi.LastMessages!)); - } - - private static string Render(IEnumerable messages) - => string.Join('\u001e', messages.Select(message => $"{message.Role}\u001f{message.Text}")); - - private static ( - StateExtractor Extractor, - StateDocument State, - Clarifications Clarifications) Build(params string[] vocabularyValues) - { - var client = new ScriptedChatClient("{}"); - var extractor = new StateExtractor(VocabularyDocument, client, new StateValueLinkers([])); - var vocabulary = new Dictionary(StringComparer.Ordinal) - { - ["applies_to"] = ViewOf(vocabularyValues), - }; - var state = new StateDocument(VocabularyDocument, vocabulary: vocabulary); - - return (extractor, state, new Clarifications()); - } - - private static VocabularyView ViewOf(params string[] originals) - { - Dictionary normalisedToOriginal = new(StringComparer.Ordinal); - foreach (var original in originals) - { - normalisedToOriginal[VocabularyFold.Fold(original)] = original; - } - - return new VocabularyView { NormalisedToOriginal = normalisedToOriginal, Originals = originals }; - } - - private sealed class RecordingChatClient : IChatClient - { - private readonly string _reply; - - public RecordingChatClient(string reply) => _reply = reply; - - public IReadOnlyList? LastMessages { get; private set; } - - public Task GetResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - CancellationToken cancellationToken = default) - { - LastMessages = [.. messages]; - return Task.FromResult(new ChatResponse(new ChatMessage(ChatRole.Assistant, _reply))); - } - - public IAsyncEnumerable GetStreamingResponseAsync( - IEnumerable messages, - ChatOptions? options = null, - CancellationToken cancellationToken = default) - => throw new NotSupportedException("StateExtractor never streams."); - - public object? GetService(Type serviceType, object? serviceKey = null) => null; - - public void Dispose() - { - // Nothing to release. - } - } -} diff --git a/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs b/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs deleted file mode 100644 index b1d5612b..00000000 --- a/tests/AgentCore.Application.Tests/State/VocabularyCacheTests.cs +++ /dev/null @@ -1,303 +0,0 @@ -using System.Collections.Concurrent; -using AgentCore.Application.State; -using AgentCore.TestSupport; -using Xunit; - -namespace AgentCore.Application.Tests.State; - -/// -/// : the per-slot immutable vocabulary, and 's -/// section 10 refusals. -/// -public sealed class VocabularyCacheTests -{ - [Fact] - public void Replace_ZeroValues_ThrowsNamingTheSlot() - { - var cache = new VocabularyCache(); - - var exception = Assert.Throws(() => cache.Replace("machine", [], maxValues: 100)); - - Assert.Equal("machine", exception.Slot); - } - - [Fact] - public void Replace_OnlyTheWildcardValue_ThrowsAsZeroValuesAfterStripping() - { - var cache = new VocabularyCache(); - - Assert.Throws( - () => cache.Replace("machine", ["*"], maxValues: 100, wildcardValue: "*")); - } - - [Fact] - public void Replace_CountEqualsMaxValues_ThrowsBecauseATruncationCannotBeToldFromACompleteRead() - { - var cache = new VocabularyCache(); - - Assert.Throws(() => cache.Replace("machine", ["a", "b"], maxValues: 2)); - } - - [Fact] - public void Replace_CountExceedsMaxValues_StillThrows() - { - // K4's own truncation check is a rank cut against maxValues, not an exact-count comparison: - // a store that ignored its own limit and returned more than maxValues must not slip past it. - var cache = new VocabularyCache(); - - Assert.Throws(() => cache.Replace("machine", ["a", "b", "c"], maxValues: 2)); - } - - [Fact] - public void Replace_TwoValuesFoldAlike_ThrowsNamingBoth() - { - var cache = new VocabularyCache(); - - var exception = Assert.Throws( - () => cache.Replace("machine", ["T900", "t900"], maxValues: 100)); - - Assert.Contains("T900", exception.Message, StringComparison.Ordinal); - Assert.Contains("t900", exception.Message, StringComparison.Ordinal); - } - - [Fact] - public void Replace_ValueFoldsToEmpty_ThrowsAndDoesNotDependOnComposition() - { - // "***" has nothing for NFC to compose and nothing for Keep to keep, so this refusal - // fires identically whether or not the runtime can compose Unicode (K44 governs - // composition; this row exercises the K31/K46 refusal on its own). - var cache = new VocabularyCache(); - - var exception = Assert.Throws( - () => cache.Replace("machine", ["***"], maxValues: 100)); - - Assert.Contains("***", exception.Message, StringComparison.Ordinal); - } - - [Fact] - public void Replace_WildcardValueStripped_DoesNotFalselyTriggerTheFoldsToEmptyRefusal() - { - // If "*" were not removed before the empty-fold check (K6), it would fold to "" itself - // and wrongly refuse startup on a document that is otherwise perfectly fine. - var cache = new VocabularyCache(); - - cache.Replace("machine", ["*", "T900"], maxValues: 100, wildcardValue: "*"); - - var view = cache.Snapshot()["machine"]; - Assert.Equal(["T900"], view.Originals); - } - - [Fact] - public void Replace_WildcardValueFoldsLikeASurvivor_DoesNotFalselyTriggerTheFoldingCollisionRefusal() - { - // K6: the wildcard is stripped before the *collision* check specifically, not only before - // the empty-fold check. "ALL" and "all" fold alike, so if the strip ran after the collision - // check (or not at all), the untouched wildcard sentinel "ALL" would collide with the real - // survivor "all" and Replace would wrongly refuse a document that is otherwise fine. - var cache = new VocabularyCache(); - - cache.Replace("machine", ["ALL", "all"], maxValues: 100, wildcardValue: "ALL"); - - var view = cache.Snapshot()["machine"]; - Assert.Equal(["all"], view.Originals); - } - - [Fact] - public void Replace_MixedCaseSpacedHyphenatedValue_MapsBackToTheOriginal() - { - var cache = new VocabularyCache(); - - cache.Replace("machine", ["North-900 Pro"], maxValues: 100); - - var view = cache.Snapshot()["machine"]; - var normalised = VocabularyFold.Fold("North-900 Pro"); - Assert.Equal("North-900 Pro", view.NormalisedToOriginal[normalised]); - } - - [Fact] - public void Replace_ExactlyOneValue_Succeeds() - { - var cache = new VocabularyCache(); - - cache.Replace("machine", ["T900"], maxValues: 100); - - Assert.Equal(["T900"], cache.Snapshot()["machine"].Originals); - } - - [Fact] - public void Snapshot_TakenBeforeReplace_IsUnaffectedByALaterReplace() - { - var cache = new VocabularyCache(); - cache.Replace("machine", ["T900"], maxValues: 100); - - var before = cache.Snapshot(); - var viewBefore = before["machine"]; - cache.Replace("machine", ["F80"], maxValues: 100); - var after = cache.Snapshot(); - - // "Byte-identical" (the acceptance clause's word) means the same object, not merely an - // equal one: Replace swaps the outer dictionary reference rather than mutating an entry, - // so the view a caller already read must never change under it. - Assert.Same(viewBefore, before["machine"]); - Assert.NotSame(before, after); - Assert.Equal(["T900"], before["machine"].Originals); - Assert.Equal(["F80"], after["machine"].Originals); - } - - [Fact] - public void Snapshot_BeforeAnyReplace_HasNoEntryForTheSlot() - { - var cache = new VocabularyCache(); - - Assert.False(cache.Snapshot().ContainsKey("machine")); - } - - [Fact] - public void LastGoodAt_BeforeAnyReplace_IsNull() - { - var cache = new VocabularyCache(); - - Assert.Null(cache.LastGoodAt("machine")); - } - - [Fact] - public void LastGoodAt_AfterAReplace_IsTheClocksTime() - { - var clock = new FakeTimeProvider(DateTimeOffset.Parse("2026-09-02T12:00:00Z", System.Globalization.CultureInfo.InvariantCulture)); - var cache = new VocabularyCache(clock); - - cache.Replace("machine", ["T900"], maxValues: 100); - - Assert.Equal(clock.GetUtcNow(), cache.LastGoodAt("machine")); - } - - [Fact] - public async Task Snapshot_ReadWhileARefreshIsReplacing_NeverThrows() - { - var cache = new VocabularyCache(); - cache.Replace("machine", ["T900"], maxValues: 100); - - using ManualResetEventSlim reading = new(); - using CancellationTokenSource stop = new(); - - // Its own thread (LongRunning), never a pooled one: the reader spins for the whole test and - // the wait below has no timeout, so a reader left queued behind a busy thread pool — the - // rest of the suite running in parallel — would hang the test rather than fail it. - var reader = Task.Factory.StartNew( - () => - { - reading.Set(); - while (!stop.IsCancellationRequested) - { - var snapshot = cache.Snapshot(); - _ = snapshot["machine"].Originals.Count; - } - }, - TestContext.Current.CancellationToken, - TaskCreationOptions.LongRunning, - TaskScheduler.Default); - - reading.Wait(TestContext.Current.CancellationToken); - - for (var round = 0; round < 200; round++) - { - cache.Replace("machine", [round % 2 == 0 ? "T900" : "F80"], maxValues: 100); - } - - await stop.CancelAsync(); - await reader; - } - - [Fact] - public async Task Replace_TwoThreadsRacingTheSameSlot_SnapshotAndLastGoodAtAgreeOnTheLastWriter() - { - // Replace writes the new view and the new LastGoodAt inside one lock. If that regressed to - // two separate critical sections, a thread whose GetUtcNow() call landed after a later - // thread's view swap could leave Snapshot() and LastGoodAt() naming two different writes. - // - // Which thread's write is "last" is otherwise unobservable from outside the lock, so - // TaggingTimeProvider records, on every clock read, which value this thread is currently - // writing. Because GetUtcNow() only ever runs from inside Replace's own lock, the recorded - // ticks reconstruct the true lock-acquisition order regardless of how the OS scheduled the - // two threads — the assertion does not depend on which thread physically ran last. - const int Rounds = 300; - var timeout = TimeSpan.FromSeconds(10); - var provider = new TaggingTimeProvider(); - var cache = new VocabularyCache(provider); - - using ManualResetEventSlim start = new(); - - // Two barriers, not one: startOfRound re-synchronises both threads before either writes, - // so neither can pull ahead and finish its own tail alone — every round has both threads - // genuinely contending for the lock at close to the same instant. afterWrites re-joins them - // once both threads' Replace calls for the round have returned, which is a quiescent point — - // no writer is in flight and neither thread can start the next round's Replace until this - // phase's post-action returns — so the invariant can be checked here every round instead of - // only once at the very end, where it only ever exercised the last round's own timing. - using Barrier startOfRound = new(2); - using Barrier afterWrites = new(2, _ => AssertQuiescentAgreement(provider, cache)); - - void RaceWithTag(string prefix) - { - start.Wait(); - for (var index = 0; index < Rounds; index++) - { - Assert.True(startOfRound.SignalAndWait(timeout), "Timed out starting a round."); - - var value = prefix + index.ToString(System.Globalization.CultureInfo.InvariantCulture); - TaggingTimeProvider.Tag(value); - cache.Replace("machine", [value], maxValues: 1_000_000); - - // If Replace ever threw, this thread would never reach here and the other thread - // would otherwise wait forever for a partner that is not coming — the timeout turns - // that into a failed assertion instead of a hung test. - Assert.True(afterWrites.SignalAndWait(timeout), "Timed out at the round's quiescent checkpoint."); - } - } - - // Each racer gets its own thread (LongRunning), never a pooled one: a Barrier only makes - // progress while both participants are running at once, and under a full thread pool — the - // rest of the suite running in parallel — the second Task.Run can wait longer for a thread - // than the barrier timeout allows, which fails the round rather than the invariant. - var threadA = StartRacer("A"); - var threadB = StartRacer("B"); - start.Set(); - await Task.WhenAll(threadA, threadB); - - Assert.Equal(Rounds * 2, provider.Calls.Count); - - Task StartRacer(string prefix) => Task.Factory.StartNew( - () => RaceWithTag(prefix), - TestContext.Current.CancellationToken, - TaskCreationOptions.LongRunning, - TaskScheduler.Default); - } - - private static void AssertQuiescentAgreement(TaggingTimeProvider provider, VocabularyCache cache) - { - var last = provider.Calls.OrderByDescending(call => call.At).First(); - - Assert.Equal([last.Value], cache.Snapshot()["machine"].Originals); - Assert.Equal(last.At, cache.LastGoodAt("machine")); - } - - private sealed class TaggingTimeProvider : TimeProvider - { - [ThreadStatic] - private static string? _currentValue; - - private readonly ConcurrentQueue<(string Value, DateTimeOffset At)> _calls = new(); - private long _ticks; - - public IReadOnlyList<(string Value, DateTimeOffset At)> Calls => [.. _calls]; - - public static void Tag(string value) => _currentValue = value; - - public override DateTimeOffset GetUtcNow() - { - var at = DateTimeOffset.UnixEpoch.AddTicks(Interlocked.Increment(ref _ticks)); - _calls.Enqueue((_currentValue ?? string.Empty, at)); - return at; - } - } -} diff --git a/tests/AgentCore.Application.Tests/State/VocabularyFoldTests.cs b/tests/AgentCore.Application.Tests/State/VocabularyFoldTests.cs deleted file mode 100644 index 007816dc..00000000 --- a/tests/AgentCore.Application.Tests/State/VocabularyFoldTests.cs +++ /dev/null @@ -1,112 +0,0 @@ -using AgentCore.Application.State; -using Xunit; - -namespace AgentCore.Application.Tests.State; - -/// -/// : the K31 fold, and the tokeniser that shares its predicate. -/// -/// -/// Every non-ASCII literal here is a \uXXXX / \UXXXXXXXX escape sequence, never a typed -/// character. Round 12 of the design's review wrote a decomposed probe input as typed characters, -/// which an editor or a file-writing tool had already re-composed on disk, so the check silently -/// measured nothing. This file is written the same way for every row. -/// -/// Rows that hold only where the runtime composes Unicode live in -/// AgentCore.Application.Unicode.Tests instead. This project runs under the repo-wide -/// InvariantGlobalization=true that production ships, where NFC composition is a no-op. -/// -/// -public sealed class VocabularyFoldTests -{ - [Fact] - public void Fold_LetterWithRingAboveVsPlainLetter_DoesNotCollide() - { - var withRing = VocabularyFold.Fold("\u00C5T900"); - var plain = VocabularyFold.Fold("T900"); - - Assert.NotEqual(withRing, plain); - } - - [Fact] - public void Fold_SharpSVsDoubleS_DoesNotCollide() - { - var sharpS = VocabularyFold.Fold("\u00DFf80"); - var doubleS = VocabularyFold.Fold("SSF80"); - - Assert.NotEqual(sharpS, doubleS); - } - - [Fact] - public void Fold_ThaiToneMarkPresentVsAbsent_DoesNotCollide() - { - // \u0E01 is the Thai consonant ko kai; \u0E48 is the mai ek tone mark, a - // NonSpacingMark. K31 keeps marks rather than stripping them. - var withToneMark = VocabularyFold.Fold("\u0E01\u0E48"); - var withoutToneMark = VocabularyFold.Fold("\u0E01"); - - Assert.NotEqual(withToneMark, withoutToneMark); - } - - [Fact] - public void Fold_TwoAstralLetters_StayDistinct() - { - // \U0001D400 and \U0001D401 are astral (supplementary-plane) mathematical capital letters. - // char-based iteration would see two lone surrogate halves per id, both classified - // UnicodeCategory.Surrogate and so dropped by Keep, collapsing both ids to "id" and - // colliding them. Rune-based iteration reads one codepoint, correctly classified Lu. - var first = VocabularyFold.Fold("id\U0001D400"); - var second = VocabularyFold.Fold("id\U0001D401"); - - Assert.NotEqual(first, second); - } - - [Fact] - public void Fold_PunctuationOnlyValue_IsEmpty() - { - Assert.Equal(string.Empty, VocabularyFold.Fold("***")); - } - - [Fact] - public void Fold_MixedCaseSpacedHyphenatedValue_DropsSeparatorsAndLowersCase() - { - Assert.Equal("north900pro", VocabularyFold.Fold("North-900 Pro")); - } - - [Fact] - public void Tokenize_SpacedHyphenatedMention_DropsLeadingAndTrailingSeparators() - { - var (tokens, separators) = VocabularyFold.Tokenize(" north-900 pro "); - - Assert.Equal(["north", "900", "pro"], tokens); - Assert.Equal(["-", " "], separators); - } - - [Fact] - public void Tokenize_TokensConcatenated_EqualFoldOfTheWholeMention() - { - const string Mention = " North-900 \u00C5Pro!! "; - - var (tokens, _) = VocabularyFold.Tokenize(Mention); - - Assert.Equal(VocabularyFold.Fold(Mention), string.Concat(tokens)); - } - - [Fact] - public void Tokenize_NoKeptRunes_ReturnsNoTokensAndNoSeparators() - { - var (tokens, separators) = VocabularyFold.Tokenize("!!! ---"); - - Assert.Empty(tokens); - Assert.Empty(separators); - } - - [Fact] - public void Tokenize_OneTokenNoSeparators_ReturnsOneTokenAndNoSeparators() - { - var (tokens, separators) = VocabularyFold.Tokenize("T900"); - - Assert.Equal(["t900"], tokens); - Assert.Empty(separators); - } -} diff --git a/tests/AgentCore.Application.Unicode.Tests/.editorconfig b/tests/AgentCore.Application.Unicode.Tests/.editorconfig deleted file mode 100644 index 3d6eebe7..00000000 --- a/tests/AgentCore.Application.Unicode.Tests/.editorconfig +++ /dev/null @@ -1,5 +0,0 @@ -[*.cs] - -# CA1707: "Remove the underscores from member name". A test name reads Subject_Behaviour, and the -# underscore is what separates the two halves. -dotnet_diagnostic.CA1707.severity = none diff --git a/tests/AgentCore.Application.Unicode.Tests/AgentCore.Application.Unicode.Tests.csproj b/tests/AgentCore.Application.Unicode.Tests/AgentCore.Application.Unicode.Tests.csproj deleted file mode 100644 index 4812ed15..00000000 --- a/tests/AgentCore.Application.Unicode.Tests/AgentCore.Application.Unicode.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - false - true - - false - - - - - - - - - - - - - diff --git a/tests/AgentCore.Application.Unicode.Tests/State/VocabularyFoldCompositionTests.cs b/tests/AgentCore.Application.Unicode.Tests/State/VocabularyFoldCompositionTests.cs deleted file mode 100644 index 8c8a95ce..00000000 --- a/tests/AgentCore.Application.Unicode.Tests/State/VocabularyFoldCompositionTests.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Text; -using AgentCore.Application.State; -using Xunit; - -namespace AgentCore.Application.Unicode.Tests.State; - -/// -/// The claims that hold only where the runtime composes Unicode. They -/// live in this project rather than beside the rest of the fold's rows because it is the one that -/// sets InvariantGlobalization=false; under the repo-wide true that production ships, -/// NFC is a no-op and both rows below would fail. -/// -/// -/// Every non-ASCII literal here is a \uXXXX escape sequence, never a typed character. Round 12 of -/// the design's review wrote a decomposed probe input as typed characters, which an editor or a -/// file-writing tool had already re-composed on disk, so the check silently measured nothing. -/// -public sealed class VocabularyFoldCompositionTests -{ - [Fact] - public void Fold_DecomposedAndComposedSpellingsOfOneValue_Collide() - { - // U+0041 U+030A is "A" followed by a combining ring above (NFD); U+00C5 is the precomposed - // Angstrom sign (NFC). NFC composition is what makes the two fold alike. - var decomposed = VocabularyFold.Fold("\u0041\u030A900"); - var composed = VocabularyFold.Fold("\u00C5900"); - - Assert.Equal(composed, decomposed); - } - - [Fact] - public void Probe_DecomposedARing_ComposesUnderThisProjectsIcu() - { - // The exact K44 boot probe (design doc section 10). Its counterpart in - // AgentCore.AspNetCore.Tests asserts the opposite under that project's invariant runtime, - // so the pair pins both sides of the condition K44 branches on. - Assert.Equal("\u00C5", "\u0041\u030A".Normalize(NormalizationForm.FormC)); - } -} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs index ef3b4c2c..d3ae4360 100644 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AddAgentCoreTests.cs @@ -25,7 +25,6 @@ using Microsoft.Extensions.AI.Evaluation; using Microsoft.Extensions.AI; using Microsoft.Extensions.DependencyInjection; -using AgentCore.Application.State; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Text.Json.Nodes; @@ -396,19 +395,6 @@ public async Task AddAgentCore_ADocumentThatReadsNoKnowledge_ResolvesNoPort() Assert.Null(provider.GetService()); } - [Fact] - public async Task AddAgentCore_RegistersTheVocabularyEveryRefreshWritesInto() - { - using var provider = await BuildAsync(OneAgentYaml); - - var vocabulary = provider.GetRequiredService(); - - // The one the refresh services and every call session share. A consumer that reads a slot's - // values — to gate a search on the product names the knowledge base publishes, say — must - // reach that instance and not a fresh one, which would always read empty. - Assert.Same(vocabulary, provider.GetRequiredService()); - } - [Fact] public async Task AddAgentCore_RegistersTheAgentShimAsAProcessSingleton() { diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs new file mode 100644 index 00000000..06699e51 --- /dev/null +++ b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/AmbiguityStartupTests.cs @@ -0,0 +1,124 @@ +using System.Text.Json.Nodes; +using AgentCore.Application.Configuration.Schema; +using AgentCore.Application.Ports; +using AgentCore.Application.Secrets; +using AgentCore.AspNetCore.DependencyInjection; +using AgentCore.AspNetCore.Tests.Fakes; +using AgentCore.Domain.Knowledge; +using AgentCore.TestSupport; +using Microsoft.Extensions.AI; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Xunit; + +namespace AgentCore.AspNetCore.Tests.DependencyInjection; + +/// +/// The ambiguity: warning the validator raises, exercised through +/// so the plumbing that carries it to the log is what is +/// under test. +/// +public sealed class AmbiguityStartupTests +{ + [Fact] + public async Task BootAsync_ASingleFacetAmbiguityDocument_LogsTheConfigurationWarningBelowTelemetry() + { + // A warning EvaluateStructure raised (K33 here) must reach the log, through + // ConfigurationStartup.Load's returned Warnings and AgentCoreBoot's own logger. + RecordingLoggerFactory loggers = new(); + + AgentCoreOptions options = new() + { + Configuration = SingleFacetDocument(), + LoggerFactory = loggers, + }; + options.UseChatClients(_ => new RoutingChatClientFactory(new FragmentingChatClient("hello"))); + options.UseKnowledgeStores(new TestKnowledgeAdapter()); + + await using var boot = new AgentCoreBoot(Options.Create(options), loggers); + await boot.BootAsync(TestContext.Current.CancellationToken); + + var warnings = loggers.Lines.Where(line => + line.Level == LogLevel.Warning + && line.Message.Contains("/providers/knowledge/ambiguity", StringComparison.Ordinal)) + .ToList(); + + Assert.Contains(warnings, line => line.Message.Contains("at most one", StringComparison.Ordinal)); + } + + private static AgentCoreConfiguration SingleFacetDocument() + => new() + { + ApiVersion = "agentcore/v1", + Name = "ambiguity-boot", + Extractor = new ExtractorConfiguration { Model = new ModelReference { Ref = "fill" } }, + State = new Dictionary(StringComparer.Ordinal) + { + ["machine"] = new StateSlotConfiguration + { + Type = StateSlotType.String, + Writer = StateWriter.Extractor, + EnumValues = [JsonValue.Create("ct900")!, JsonValue.Create("ct1200")!], + }, + }, + Providers = new ProvidersConfiguration + { + Llm = [new LlmProviderConfiguration { Kind = "test", Model = "test", As = "fill" }], + Knowledge = new KnowledgeProviderConfiguration + { + Kind = "test", + Collection = "kb", + Fields = new KnowledgeFieldsConfiguration { Body = "body" }, + Scope = new KnowledgeScopeConfiguration + { + Template = "facets.{key}", + FromState = ["machine"], + Wildcard = new KnowledgeWildcardConfiguration { Value = "*", Facets = ["machine"] }, + }, + Ambiguity = new KnowledgeAmbiguityConfiguration(), + }, + }, + Policy = new PolicyConfiguration + { + Initial = "answering", + Stages = [new StageConfiguration { Id = "answering", Agent = "resolver", Terminal = true }], + }, + Agents = new AgentsConfiguration + { + Items = + [ + new AgentConfiguration + { + Id = "resolver", + Instructions = "I answer about one machine", + Knowledge = new AgentKnowledgeConfiguration { Mode = KnowledgeMode.Prefetch, Scoped = true }, + }, + ], + }, + }; + + /// Answers providers.knowledge.kind: test with a port that finds nothing. + private sealed class TestKnowledgeAdapter : IKnowledgeStoreAdapter + { + public string Kind => "test"; + + public bool CanServeSearch => true; + + public bool CanScope => true; + + public ValueTask CreateSearchAsync( + KnowledgeProviderConfiguration entry, + ISecretResolverPort? secrets, + IEmbeddingGenerator>? embeddings, + bool requireScope, + CancellationToken cancellationToken = default) + => ValueTask.FromResult(new EmptyPort()); + } + + private sealed class EmptyPort : IKnowledgeRetrievalPort + { + public ValueTask> SearchAsync( + string query, CancellationToken cancellationToken = default) + => ValueTask.FromResult>([]); + } +} diff --git a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/VocabularyStartupTests.cs b/tests/AgentCore.AspNetCore.Tests/DependencyInjection/VocabularyStartupTests.cs deleted file mode 100644 index b50960e3..00000000 --- a/tests/AgentCore.AspNetCore.Tests/DependencyInjection/VocabularyStartupTests.cs +++ /dev/null @@ -1,805 +0,0 @@ -using System.Text.Json.Nodes; -using AgentCore.Application.Configuration.Parsing; -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Configuration.Validation; -using AgentCore.Application.Ports; -using AgentCore.Application.Secrets; -using AgentCore.Application.State; -using AgentCore.AspNetCore.DependencyInjection; -using AgentCore.AspNetCore.Tests.Fakes; -using AgentCore.Domain.Knowledge; -using AgentCore.TestSupport; -using Microsoft.Extensions.AI; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Microsoft.Extensions.Options; -using Xunit; - -namespace AgentCore.AspNetCore.Tests.DependencyInjection; - -/// -/// Task A7: section 10's boot read of every vocabulary: slot, K44's Unicode probe, and K48's -/// per-wildcard-facet * check — all made in . -/// -public sealed class VocabularyStartupTests -{ - [Fact] - public async Task ApplyVocabularyAsync_UnscopedSlot_StripsTheWildcardAndKeepsTheRest() - { - // The sentinel is stored in the collection, so a read of any facet path returns it. It - // normalises to nothing, so a domain that keeps it can be neither linked nor gated — and the - // slot need not be scoped by for that to be true. wildcard.facets says which scope conditions - // this deployment widens, which is a different question and cannot answer this one. - var configuration = Configuration( - [("model", Vocabulary(maxValues: 10))], - new KnowledgeWildcardConfiguration { Value = "*", Facets = ["brand"] }, - extraFromState: ["brand"], - scopeVocabularySlots: false); - - var port = new FakeFacetPort().With("facets.model", "lcr-2023", "*", "f63-2019"); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true); - - Assert.Equal(["lcr-2023", "f63-2019"], cache.Snapshot()["model"].Originals); - } - - [Fact] - public async Task ApplyVocabularyAsync_AWrappedPort_ReadsTheVocabularyThroughTheWrapper() - { - // The wrapper does not read facets itself, so a cast to IFacetVocabularyPort answers false - // on it and the vocabulary would be refused. Asking the port instead reaches the store - // inside, which is what lets a cache or a log sit in front of a store without silently - // costing the document a feature. - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - var inner = new FakeFacetPort().With("facets.brand", "acme", "globex"); - ForwardingPort wrapper = new(inner); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, wrapper, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true); - - Assert.Equal(["acme", "globex"], cache.Snapshot()["brand"].Originals); - } - - [Fact] - public async Task ApplyVocabularyAsync_ZeroValues_FailsNamingTheSlotAndPath() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - FakeFacetPort port = new(); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true).AsTask()); - - var error = Assert.Single(failure.Errors); - Assert.Contains("brand", error.Message, StringComparison.Ordinal); - Assert.Contains("facets.brand", error.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_ExactlyMaxValues_FailsAsTruncated() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 3))]); - var port = new FakeFacetPort().With("facets.brand", "acme", "globex", "initech"); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true).AsTask()); - - var error = Assert.Single(failure.Errors); - Assert.Contains("3", error.Message, StringComparison.Ordinal); - Assert.Contains("brand", error.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_TwoValuesFoldAlike_FailsNamingBoth() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - var port = new FakeFacetPort().With("facets.brand", "Acme", "ACME"); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true).AsTask()); - - var error = Assert.Single(failure.Errors); - Assert.Contains("Acme", error.Message, StringComparison.Ordinal); - Assert.Contains("ACME", error.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_ExactlyOneValue_SucceedsAndWarns() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - var port = new FakeFacetPort().With("facets.brand", "acme"); - VocabularyCache cache = new(); - RecordingLoggerFactory loggers = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, loggers.CreateLogger("test"), TestContext.Current.CancellationToken, - composesUnicode: () => true); - - Assert.Equal(["acme"], cache.Snapshot()["brand"].Originals); - var line = Assert.Single(loggers.Of(1)); - Assert.Equal(Microsoft.Extensions.Logging.LogLevel.Warning, line.Level); - Assert.Equal("brand", line.Field("Slot")); - } - - [Fact] - public async Task ApplyVocabularyAsync_NonComposingRuntimeWithoutAssumeNormalized_FailsNamingInvariantGlobalization() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10, assumeNormalized: false))]); - var port = new FakeFacetPort().With("facets.brand", "acme", "globex"); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => false).AsTask()); - - var error = Assert.Single(failure.Errors); - Assert.Contains("InvariantGlobalization", error.Message, StringComparison.Ordinal); - Assert.Contains("brand", error.Message, StringComparison.Ordinal); - Assert.Empty(port.Reads); - } - - [Fact] - public async Task ApplyVocabularyAsync_NonComposingRuntimeWithAssumeNormalized_Succeeds() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10, assumeNormalized: true))]); - var port = new FakeFacetPort().With("facets.brand", "acme", "globex"); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => false); - - Assert.Equal(["acme", "globex"], cache.Snapshot()["brand"].Originals); - } - - [Fact] - public async Task ApplyVocabularyAsync_ComposingRuntime_Succeeds() - { - var configuration = Configuration([("brand", Vocabulary(maxValues: 10, assumeNormalized: false))]); - var port = new FakeFacetPort().With("facets.brand", "acme", "globex"); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken, - composesUnicode: () => true); - - Assert.Equal(["acme", "globex"], cache.Snapshot()["brand"].Originals); - } - - [Fact] - public async Task ApplyVocabularyAsync_WildcardFacetWithNoStar_LogsK48NamingTheFacet() - { - var configuration = Configuration( - [("brand", Vocabulary(maxValues: 10))], - wildcard: new KnowledgeWildcardConfiguration { Value = "*", Facets = ["brand"] }); - var port = new FakeFacetPort().With("facets.brand", "acme", "globex"); - VocabularyCache cache = new(); - RecordingLoggerFactory loggers = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, loggers.CreateLogger("test"), TestContext.Current.CancellationToken, - composesUnicode: () => true); - - var line = Assert.Single(loggers.Of(2)); - Assert.Equal("brand", line.Field("Facet")); - Assert.Contains(2, port.Reads.Where(r => r.Path == "facets.brand").Select(r => r.Limit)); - } - - [Fact] - public async Task ApplyVocabularyAsync_WildcardFacetWithStar_NoWarning() - { - var configuration = Configuration( - [("brand", Vocabulary(maxValues: 10))], - wildcard: new KnowledgeWildcardConfiguration { Value = "*", Facets = ["brand"] }); - - // The vocabulary read itself carries the wildcard (stripped by K6); the K48 read is a - // separate, small read that must see it. - var port = new FakeFacetPort().With("facets.brand", "acme", "globex", "*"); - VocabularyCache cache = new(); - RecordingLoggerFactory loggers = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, loggers.CreateLogger("test"), TestContext.Current.CancellationToken, - composesUnicode: () => true); - - Assert.Empty(loggers.Of(2)); - } - - [Fact] - public async Task ApplyVocabularyAsync_WildcardOnlyDocumentAndFacetAwarePortThrowsOnTheK48Read_WarnsAndBootSucceeds() - { - // K48 sits under "warned, not refused": a wildcard-only document (no vocabulary: slot - // anywhere) still reaches this read once its port is facet-aware (Task A4), and a store that - // cannot serve the small K48 sample -- for example, no keyword payload index at this path on - // Qdrant -- must not turn a document that was booting into one that cannot. - var configuration = Configuration( - wildcard: new KnowledgeWildcardConfiguration { Value = "*", Facets = ["applies_to"] }, - extraFromState: ["applies_to"]); - var port = new FakeFacetPort().ThrowsOn( - "facets.applies_to", new InvalidOperationException("no keyword payload index at this path")); - VocabularyCache cache = new(); - RecordingLoggerFactory loggers = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, loggers.CreateLogger("test"), TestContext.Current.CancellationToken); - - var line = Assert.Single(loggers.Of(3)); - Assert.Equal(LogLevel.Warning, line.Level); - Assert.Equal("applies_to", line.Field("Facet")); - Assert.Empty(cache.Snapshot()); - } - - [Fact] - public void ComposesUnicode_UnderThisTestHostsInvariantGlobalization_IsFalse() - { - // Nothing else pins this method itself: every other row drives the outcome through the - // composesUnicode override seam, so a regression that made ComposesUnicode() always report - // true (for example, swapping its escaped "Å" literal for typed characters, which - // reads identically but is pre-composed by the time the source file reaches disk) would pass - // every one of them. This project runs under InvariantGlobalization=true, where - // string.Normalize is a no-op, so the real method must report false here. - Assert.False(KnowledgeStartup.ComposesUnicode()); - } - - [Fact] - public async Task ApplyVocabularyAsync_NoVocabularyAndNoWildcardFacets_DoesNothing() - { - var configuration = Configuration(); - FakeFacetPort port = new(); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, port, cache, NullLogger.Instance, TestContext.Current.CancellationToken); - - Assert.Empty(port.Reads); - Assert.Empty(cache.Snapshot()); - } - - [Fact] - public async Task ApplyVocabularyAsync_HostBoundPortNotFacetAware_FailsNamingIFacetVocabularyPort() - { - // K27's first exit: options.UseKnowledgeRetrieval names a port of the host's own, and that - // port does not implement IFacetVocabularyPort. - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - HostBoundPort knowledge = new(); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, knowledge, cache, NullLogger.Instance, TestContext.Current.CancellationToken).AsTask()); - - Assert.Contains(nameof(IFacetVocabularyPort), failure.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_CompositeBuiltPortNotFacetAware_FailsNamingIFacetVocabularyPort() - { - // K27's second exit: CompositeKnowledgeStoreFactory matched providers.knowledge.kind to an - // adapter whose port also does not implement IFacetVocabularyPort. - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - CompositeBuiltPort knowledge = new(); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, knowledge, cache, NullLogger.Instance, TestContext.Current.CancellationToken).AsTask()); - - Assert.Contains(nameof(IFacetVocabularyPort), failure.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_NoPortAtAll_FailsNamingIFacetVocabularyPort() - { - // K27's third exit: no adapter was registered, so KnowledgeStartup.OpenAsync returns null. - var configuration = Configuration([("brand", Vocabulary(maxValues: 10))]); - VocabularyCache cache = new(); - - var failure = await Assert.ThrowsAsync( - () => KnowledgeStartup.ApplyVocabularyAsync( - configuration, knowledge: null, cache, NullLogger.Instance, TestContext.Current.CancellationToken).AsTask()); - - Assert.Contains(nameof(IFacetVocabularyPort), failure.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task ApplyVocabularyAsync_WildcardOnlyDocumentAndPortNotFacetAware_SkipsSilently() - { - // A pre-existing wildcard-plan document (no vocabulary: slot anywhere) must not suddenly - // require IFacetVocabularyPort just because it uses wildcard.facets -- K27's refusal is - // scoped to a document that declares vocabulary:. - var configuration = Configuration( - wildcard: new KnowledgeWildcardConfiguration { Value = "*", Facets = ["applies_to"] }, - extraFromState: ["applies_to"]); - HostBoundPort knowledge = new(); - VocabularyCache cache = new(); - - await KnowledgeStartup.ApplyVocabularyAsync( - configuration, knowledge, cache, NullLogger.Instance, TestContext.Current.CancellationToken); - - Assert.Empty(cache.Snapshot()); - } - - private static SlotVocabularyConfiguration Vocabulary(int maxValues, bool assumeNormalized = false) - => new() { From = "knowledge", MaxValues = maxValues, AssumeNormalized = assumeNormalized }; - - private static AgentCoreConfiguration Configuration( - (string Slot, SlotVocabularyConfiguration Vocabulary)[]? vocabularySlots = null, - KnowledgeWildcardConfiguration? wildcard = null, - IReadOnlyList? extraFromState = null, - bool scopeVocabularySlots = true) - { - vocabularySlots ??= []; - extraFromState ??= []; - - Dictionary state = new(StringComparer.Ordinal); - foreach (var (slot, vocabulary) in vocabularySlots) - { - state[slot] = new StateSlotConfiguration - { - Type = StateSlotType.String, - Writer = StateWriter.Extractor, - Vocabulary = vocabulary, - }; - } - - foreach (var slot in extraFromState) - { - state.TryAdd(slot, new StateSlotConfiguration { Type = StateSlotType.String, Writer = StateWriter.Extractor }); - } - - List fromState = scopeVocabularySlots - ? [.. vocabularySlots.Select(entry => entry.Slot), .. extraFromState] - : [.. extraFromState]; - - return new AgentCoreConfiguration - { - ApiVersion = "agentcore/v1", - Name = "vocabulary-startup", - State = state, - Providers = new ProvidersConfiguration - { - Knowledge = new KnowledgeProviderConfiguration - { - Kind = "test", - Collection = "kb", - Fields = new KnowledgeFieldsConfiguration { Body = "body" }, - Scope = new KnowledgeScopeConfiguration - { - Template = "facets.{key}", - FromState = fromState, - Wildcard = wildcard, - }, - }, - }, - }; - } - - /// A live port that records every read, and answers a canned map by path. - private sealed class FakeFacetPort : IKnowledgeRetrievalPort, IFacetVocabularyPort - { - private readonly Dictionary> _byPath = new(StringComparer.Ordinal); - private readonly Dictionary _throwsByPath = new(StringComparer.Ordinal); - - public List<(string Path, int Limit)> Reads { get; } = []; - - public FakeFacetPort With(string path, params string[] values) - { - _byPath[path] = values; - return this; - } - - public FakeFacetPort ThrowsOn(string path, Exception exception) - { - _throwsByPath[path] = exception; - return this; - } - - public ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - { - Reads.Add((path, limit)); - - if (_throwsByPath.TryGetValue(path, out var exception)) - { - throw exception; - } - - return ValueTask.FromResult(_byPath.TryGetValue(path, out var values) ? values : (IReadOnlyList)[]); - } - - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } - - /// A port wrapped in another, as a cache or a log would wrap one. - private sealed class ForwardingPort(IKnowledgeRetrievalPort inner) : IKnowledgeRetrievalPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => inner.SearchAsync(query, cancellationToken); - - public object? GetService(Type serviceType, object? serviceKey = null) - { - ArgumentNullException.ThrowIfNull(serviceType); - - return serviceKey is null && serviceType.IsInstanceOfType(this) - ? this - : inner.GetService(serviceType, serviceKey); - } - } - - /// Stands in for a port options.UseKnowledgeRetrieval named, with no facet read. - private sealed class HostBoundPort : IKnowledgeRetrievalPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } - - /// Stands in for a port CompositeKnowledgeStoreFactory built, with no facet read. - private sealed class CompositeBuiltPort : IKnowledgeRetrievalPort - { - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } -} - -/// -/// The rest of task A7's wiring, exercised through itself: the -/// configuration warnings logged below telemetry, ValidateLinkerNames run after the linker -/// registry is built, the vocabulary read reaching a real adapter-built port, and the background -/// refresh started. -/// -public sealed class AgentCoreBootVocabularyTests -{ - [Fact] - public async Task BootAsync_ASingleFacetAmbiguityDocument_LogsTheConfigurationWarningBelowTelemetry() - { - // R1's actual plumbing: a warning EvaluateStructure raised (K33 here) must reach the log, - // through ConfigurationStartup.Load's returned Warnings and AgentCoreBoot's own logger. - RecordingLoggerFactory loggers = new(); - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - - await using var boot = Boot(Document(Vocabulary(10)), adapter, loggers); - await boot.BootAsync(TestContext.Current.CancellationToken); - - var warnings = loggers.Lines.Where(line => - line.Level == LogLevel.Warning - && line.Message.Contains("/providers/knowledge/ambiguity", StringComparison.Ordinal)) - .ToList(); - - Assert.Contains(warnings, line => line.Message.Contains("at most one", StringComparison.Ordinal)); - } - - [Fact] - public void Load_AGraphDocumentWithAmbiguity_ReturnsTheK39Warning() - { - // K39: channel 1 cannot fire on a graph: document, so ambiguity: there is a boot warning - // (CheckVocabularyAndAmbiguity, task A1) that ConfigurationStartup.Load must not discard. - var wildcard = new KnowledgeWildcardConfiguration { Value = "*", Facets = ["applies_to", "brand"] }; - StateSlotConfiguration facet = new() { Type = StateSlotType.String, Writer = StateWriter.Extractor, EnumValues = [] }; - - var configuration = new AgentCoreConfiguration - { - ApiVersion = "agentcore/v1", - Name = "graph-ambiguity", - Graph = new GraphConfiguration(), - Extractor = new ExtractorConfiguration { Model = new ModelReference { Ref = "small" } }, - State = new Dictionary(StringComparer.Ordinal) - { - ["applies_to"] = facet with { EnumValues = [JsonValue.Create("a")!] }, - ["brand"] = facet with { EnumValues = [JsonValue.Create("b")!] }, - }, - Providers = new ProvidersConfiguration - { - Llm = [new LlmProviderConfiguration { Kind = "openai", Model = "gpt", As = "small" }], - Knowledge = new KnowledgeProviderConfiguration - { - Kind = "qdrant", - Collection = "kb", - Fields = new KnowledgeFieldsConfiguration { Body = "text" }, - Scope = new KnowledgeScopeConfiguration - { - Template = "facets.{key}", - FromState = ["applies_to", "brand"], - Wildcard = wildcard, - }, - Ambiguity = new KnowledgeAmbiguityConfiguration(), - }, - }, - }; - - AgentCoreOptions options = new() { Configuration = configuration }; - - var result = ConfigurationStartup.Load(options); - - var warning = Assert.Single(result.Warnings); - Assert.Equal("/providers/knowledge/ambiguity", warning.Pointer); - } - - [Fact] - public async Task BootAsync_AZeroValueVocabularyRead_FailsBootNamingTheSlot() - { - FacetKnowledgeAdapter adapter = new(); - - // No .With(...) call: the fake answers every path with an empty list. - await using var boot = Boot(Document(Vocabulary(10)), adapter); - - var failure = await Assert.ThrowsAsync( - () => boot.BootAsync(TestContext.Current.CancellationToken).AsTask()); - - Assert.Contains("machine", failure.Message, StringComparison.Ordinal); - Assert.True(adapter.Port.Reads.Count > 0); - } - - [Fact] - public async Task BootAsync_ABadLinkerName_FailsBootBeforeReadingTheVocabulary() - { - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - - await using var boot = Boot(Document(Vocabulary(10, linker: "bogus")), adapter); - - var failure = await Assert.ThrowsAsync( - () => boot.BootAsync(TestContext.Current.CancellationToken).AsTask()); - - Assert.Contains("bogus", failure.Message, StringComparison.Ordinal); - } - - [Fact] - public async Task BootAsync_AHostRegisteredLinkerName_Succeeds() - { - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - - await using var boot = Boot( - Document(Vocabulary(10, linker: "custom")), adapter, linkers: [new NamedLinker("custom")]); - - await boot.BootAsync(TestContext.Current.CancellationToken); - - Assert.NotNull(boot.Sessions); - } - - [Fact] - public async Task BootAsync_AHostRegisteredLinkerName_ItsResultReachesTheExtractedState() - { - // "Boot succeeds" (the fact above) would have passed against the exact bug this fact exists - // to catch: CallSessionFactory hard-coded an empty linker registry, so a host's own linker - // validated by name at boot and was then never actually consulted. Only running a real turn - // and reading back what the CUSTOM linker -- not exact, not nothing -- wrote proves the - // registry travelled all the way from UseStateValueLinkers into the extractor. - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - - var configuration = Document(Vocabulary(10, linker: "custom")); - - AgentCoreOptions options = new() { Configuration = configuration }; - options.UseChatClients(_ => new RoutingChatClientFactory(new FragmentingChatClient("okay, noted")) - .Route("fill", new FragmentingChatClient("""{"machine":"ct900"}"""))); - options.UseKnowledgeStores(adapter); - options.UseStateValueLinkers(new FixedResultLinker("custom", "ct1200")); - - await using var boot = new AgentCoreBoot(Options.Create(options), NullLoggerFactory.Instance); - await boot.BootAsync(TestContext.Current.CancellationToken); - - var session = boot.Sessions.Create(); - await session.RunTurnAsync("what machine do I have", TestContext.Current.CancellationToken); - - // exact would resolve the mention "ct900" to "ct900" itself; the custom linker ignores the - // mention and always answers "ct1200" -- chosen so the two are never accidentally the same. - Assert.Equal("ct1200", session.State.Read("machine")?.GetValue()); - } - - [Fact] - public async Task BootAsync_ValidVocabularyDocument_BuildsAWorkingSessionFactory() - { - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - - await using var boot = Boot(Document(Vocabulary(10)), adapter); - await boot.BootAsync(TestContext.Current.CancellationToken); - - var session = boot.Sessions.Create(); - Assert.NotNull(session); - } - - [Fact] - public async Task BootAsync_ARefreshIntervalConfigured_StartsTheBackgroundRefresh() - { - FacetKnowledgeAdapter adapter = new(); - adapter.Port.With("facets.machine", "ct900", "ct1200"); - FakeTimeProvider time = new(DateTimeOffset.UnixEpoch); - - await using var boot = Boot(Document(Vocabulary(10, refreshSeconds: 60)), adapter, timeProvider: time); - await boot.BootAsync(TestContext.Current.CancellationToken); - - var readsAtBoot = adapter.Port.Reads.Count; - Assert.True(readsAtBoot > 0); - - for (var attempt = 0; attempt < 200 && adapter.Port.Reads.Count <= readsAtBoot; attempt++) - { - time.Advance(TimeSpan.FromSeconds(60)); - await Task.Delay(10, TestContext.Current.CancellationToken); - } - - Assert.True(adapter.Port.Reads.Count > readsAtBoot); - } - - private static SlotVocabularyConfiguration Vocabulary(int maxValues, string? linker = null, int refreshSeconds = 0) - => new() - { - From = "knowledge", - MaxValues = maxValues, - Linker = linker ?? SlotVocabularyConfiguration.DefaultLinker, - RefreshSeconds = refreshSeconds, - - // K44 is covered at the ApplyVocabularyAsync unit level (composesUnicode seam). These - // boot-level facts are about other wiring, and the AspNetCore test host really does run - // under InvariantGlobalization=true, so without this every one of them would hit K44's - // refusal first. - AssumeNormalized = true, - }; - - private static AgentCoreConfiguration Document(SlotVocabularyConfiguration vocabulary) - => new() - { - ApiVersion = "agentcore/v1", - Name = "vocabulary-boot", - Extractor = new ExtractorConfiguration { Model = new ModelReference { Ref = "fill" } }, - State = new Dictionary(StringComparer.Ordinal) - { - ["machine"] = new StateSlotConfiguration - { - Type = StateSlotType.String, - Writer = StateWriter.Extractor, - Vocabulary = vocabulary, - }, - }, - Providers = new ProvidersConfiguration - { - Llm = [new LlmProviderConfiguration { Kind = "test", Model = "test", As = "fill" }], - Knowledge = new KnowledgeProviderConfiguration - { - Kind = "test", - Collection = "kb", - Fields = new KnowledgeFieldsConfiguration { Body = "body" }, - Scope = new KnowledgeScopeConfiguration - { - Template = "facets.{key}", - FromState = ["machine"], - Wildcard = new KnowledgeWildcardConfiguration { Value = "*", Facets = ["machine"] }, - }, - Ambiguity = new KnowledgeAmbiguityConfiguration(), - }, - }, - Policy = new PolicyConfiguration - { - Initial = "answering", - Stages = [new StageConfiguration { Id = "answering", Agent = "resolver", Terminal = true }], - }, - Agents = new AgentsConfiguration - { - Items = - [ - new AgentConfiguration - { - Id = "resolver", - Instructions = "I answer about one machine", - Knowledge = new AgentKnowledgeConfiguration { Mode = KnowledgeMode.Prefetch, Scoped = true }, - }, - ], - }, - }; - - private static AgentCoreBoot Boot( - AgentCoreConfiguration configuration, - FacetKnowledgeAdapter adapter, - RecordingLoggerFactory? loggers = null, - TimeProvider? timeProvider = null, - IStateValueLinker[]? linkers = null) - { - AgentCoreOptions options = new() - { - Configuration = configuration, - LoggerFactory = loggers, - TimeProvider = timeProvider, - }; - - options.UseChatClients(_ => new RoutingChatClientFactory(new FragmentingChatClient("hello"))); - options.UseKnowledgeStores(adapter); - - if (linkers is { Length: > 0 }) - { - options.UseStateValueLinkers(linkers); - } - - return new AgentCoreBoot(Options.Create(options), (ILoggerFactory?)loggers ?? NullLoggerFactory.Instance); - } - - /// Answers providers.knowledge.kind: test with a live facet-aware port. - private sealed class FacetKnowledgeAdapter : IKnowledgeStoreAdapter - { - public string Kind => "test"; - - public bool CanServeSearch => true; - - public bool CanScope => true; - - public FacetKnowledgePort Port { get; } = new(); - - public ValueTask CreateSearchAsync( - KnowledgeProviderConfiguration entry, - ISecretResolverPort? secrets, - IEmbeddingGenerator>? embeddings, - bool requireScope, - CancellationToken cancellationToken = default) - => ValueTask.FromResult(Port); - } - - /// A live port that records every read, and answers a canned map by path. - private sealed class FacetKnowledgePort : IKnowledgeRetrievalPort, IFacetVocabularyPort - { - private readonly Dictionary> _byPath = new(StringComparer.Ordinal); - - public List<(string Path, int Limit)> Reads { get; } = []; - - public FacetKnowledgePort With(string path, params string[] values) - { - _byPath[path] = values; - return this; - } - - public ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - { - lock (Reads) - { - Reads.Add((path, limit)); - } - - return ValueTask.FromResult(_byPath.TryGetValue(path, out var values) ? values : (IReadOnlyList)[]); - } - - public ValueTask> SearchAsync( - string query, CancellationToken cancellationToken = default) - => ValueTask.FromResult>([]); - } - - /// A linker that never links, registered under a host-chosen name. - private sealed class NamedLinker(string name) : IStateValueLinker - { - public string Name { get; } = name; - - public LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet lastNamed) - => new(LinkOutcome.NoMatch, []); - } - - /// - /// Always links to the same value, ignoring the mention. Distinguishable on purpose: no reading - /// of this test can mistake its output for exact's. - /// - private sealed class FixedResultLinker(string name, string result) : IStateValueLinker - { - public string Name { get; } = name; - - public LinkResult Link(string mention, VocabularyView vocabulary, IReadOnlySet lastNamed) - => new(LinkOutcome.Linked, [result]); - } -} diff --git a/tests/AgentCore.AspNetCore.Tests/Sessions/VocabularyRefreshServiceTests.cs b/tests/AgentCore.AspNetCore.Tests/Sessions/VocabularyRefreshServiceTests.cs deleted file mode 100644 index 8743e820..00000000 --- a/tests/AgentCore.AspNetCore.Tests/Sessions/VocabularyRefreshServiceTests.cs +++ /dev/null @@ -1,136 +0,0 @@ -using AgentCore.Application.Ports; -using AgentCore.Application.State; -using AgentCore.AspNetCore.Sessions; -using AgentCore.TestSupport; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Abstractions; -using Xunit; - -namespace AgentCore.AspNetCore.Tests.Sessions; - -/// -/// Section 11's refresh rows: a failed or degenerate refresh keeps the cache's last good view and -/// logs, and the loop itself follows CallSessionSweeper's idiom. -/// -public sealed class VocabularyRefreshServiceTests -{ - [Fact] - public async Task RefreshAsync_TheReadThrows_KeepsTheLastGoodViewAndLogs() - { - VocabularyCache cache = new(); - cache.Replace("brand", ["acme", "globex"], maxValues: 10); - var before = cache.Snapshot()["brand"]; - - RecordingLoggerFactory loggers = new(); - FailingPort port = new(new InvalidOperationException("qdrant is down")); - - VocabularyRefreshService service = new( - "brand", "facets.brand", 10, null, 900, port, cache, - TimeProvider.System, loggers.CreateLogger()); - - await service.RefreshAsync(TestContext.Current.CancellationToken); - - Assert.Same(before, cache.Snapshot()["brand"]); - var line = Assert.Single(loggers.Of(1)); - Assert.Equal("brand", line.Field("Slot")); - Assert.Same(port.Failure, line.Exception); - } - - [Fact] - public async Task RefreshAsync_TheReadReturnsExactlyMaxValues_KeepsTheLastGoodViewAndLogsDegenerate() - { - // K46: a successful but truncated read must not overwrite the last good view. - VocabularyCache cache = new(); - cache.Replace("brand", ["acme", "globex"], maxValues: 10); - var before = cache.Snapshot()["brand"]; - - RecordingLoggerFactory loggers = new(); - FakePort port = new(["a", "b", "c"]); - - VocabularyRefreshService service = new( - "brand", "facets.brand", 3, null, 900, port, cache, - TimeProvider.System, loggers.CreateLogger()); - - await service.RefreshAsync(TestContext.Current.CancellationToken); - - Assert.Same(before, cache.Snapshot()["brand"]); - var line = Assert.Single(loggers.Of(2)); - Assert.Equal("brand", line.Field("Slot")); - Assert.IsType(line.Exception); - } - - [Fact] - public async Task RefreshAsync_TheReadReturnsAGoodSet_ReplacesTheView() - { - VocabularyCache cache = new(); - cache.Replace("brand", ["acme"], maxValues: 10); - - FakePort port = new(["acme", "globex"]); - VocabularyRefreshService service = new( - "brand", "facets.brand", 10, null, 900, port, cache, - TimeProvider.System, NullLogger.Instance); - - await service.RefreshAsync(TestContext.Current.CancellationToken); - - Assert.Equal(["acme", "globex"], cache.Snapshot()["brand"].Originals); - } - - [Fact] - public async Task ExecuteAsync_TheTimerTicks_RunsARefreshOnTheConfiguredInterval() - { - VocabularyCache cache = new(); - cache.Replace("brand", ["acme"], maxValues: 10); - - FakePort port = new(["acme", "globex"]); - FakeTimeProvider time = new(DateTimeOffset.UnixEpoch); - - VocabularyRefreshService service = new( - "brand", "facets.brand", 10, null, refreshSeconds: 60, port, cache, - time, NullLogger.Instance); - - await service.StartAsync(TestContext.Current.CancellationToken); - - // BackgroundService.StartAsync runs ExecuteAsync through Task.Run, so the PeriodicTimer may - // not exist yet when this returns. Retry the advance until the fake port reports the tick - // landed, rather than assuming a single Advance lands on a timer that is not armed yet. - for (var attempt = 0; attempt < 200 && !port.Read.Task.IsCompleted; attempt++) - { - time.Advance(TimeSpan.FromSeconds(60)); - await Task.Delay(10, TestContext.Current.CancellationToken); - } - - await port.Read.Task.WaitAsync(TimeSpan.FromSeconds(1), TestContext.Current.CancellationToken); - - // The cache write is asynchronous from the read that unblocked Read.Task above, so give the - // continuation a chance to run before reading the cache back. - for (var attempt = 0; attempt < 100 && cache.Snapshot()["brand"].Originals.Count != 2; attempt++) - { - await Task.Delay(10, TestContext.Current.CancellationToken); - } - - Assert.Equal(["acme", "globex"], cache.Snapshot()["brand"].Originals); - - await service.StopAsync(TestContext.Current.CancellationToken); - } - - private sealed class FakePort(IReadOnlyList values) : IFacetVocabularyPort - { - public TaskCompletionSource Read { get; } = new(); - - public ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - { - Read.TrySetResult(); - return ValueTask.FromResult(values); - } - } - - private sealed class FailingPort(Exception failure) : IFacetVocabularyPort - { - public Exception Failure { get; } = failure; - - public ValueTask> ReadAsync( - string path, int limit, CancellationToken cancellationToken = default) - => throw Failure; - } -} diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs index ffcdccaf..a533ed37 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/AmbiguityIntegrationTests.cs @@ -6,7 +6,6 @@ using AgentCore.Application.Configuration.Validation; using AgentCore.Application.Ports; using AgentCore.Application.Runtime; -using AgentCore.Application.State; using AgentCore.Domain.Knowledge; using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; using AgentCore.Infrastructure.Tests.Fakes; @@ -21,9 +20,7 @@ namespace AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant; /// -/// Section 12's "Vocabulary and probe -- against real Qdrant" list, and the Task A7 debt: a live -/// turn proving the boot-filled reaches the -/// extractor's gate, not just a hand-seeded one. +/// Section 12's "probe -- against real Qdrant" list. /// /// /// @@ -50,8 +47,7 @@ namespace AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant; /// the row that needs exactly one card (the two-machine card) combines a distinctive token with a /// store Limit of 1, so only the fused winner survives. Every row that needs a card population /// this shared fixture must not carry for every other row -- the company-wide card, the one-machine -/// multi-card union, and the empty-search row -- builds and drops its own small collection instead, -/// the same way 's wildcard fact does. +/// multi-card union, and the empty-search row -- builds and drops its own small collection instead. /// /// public sealed class AmbiguityCorpusFixture : IAsyncLifetime @@ -202,7 +198,7 @@ public sealed class AmbiguityIntegrationTests : IClassFixtureNo ambiguity, no wildcard: a plain vocabulary: slot the extractor writes and the gate checks. - private const string VocabularyOnlyYaml = - """ - apiVersion: agentcore/v1 - name: vocabulary-cache-reaches-extractor - state: - model: - type: string - writer: extractor - description: "The model, as printed on the machine." - vocabulary: { from: knowledge } - extractor: - model: { ref: fill } - providers: - call: { kind: telnyx-relay } - speech: - stt: { kind: telnyx-relay } - tts: { kind: telnyx-relay } - knowledge: - kind: qdrant - collection: kb - fields: { body: text } - scope: - template: "facets.{key}" - agents: - items: - - id: only - instructions: "answer the caller" - """; - private readonly AmbiguityCorpusFixture _corpus; public AmbiguityIntegrationTests(AmbiguityCorpusFixture corpus) => _corpus = corpus; @@ -448,40 +414,6 @@ public async Task NoNoticeCanBeCitedAsACard() Assert.All(named.Results, r => Assert.Equal(NoticeSourceName, r.SourceName)); } - /// A facet read against a collection with maxValues values fails startup. - [QdrantFact] - public async Task FacetRead_AgainstACollectionWithMaxValuesValues_FailsStartup() - { - // This is the exact call sequence KnowledgeStartup.ApplyVocabularyAsync runs for one slot - // (port.ReadAsync then VocabularyCache.Replace with the same limit) -- KnowledgeStartup itself - // is internal to AgentCore.AspNetCore, a project this one does not reference. - var port = BuildStore(); - var values = await port.ReadAsync("facets.model", limit: 3, TestContext.Current.CancellationToken); - - Assert.Equal(3, values.Count); - - var vocabulary = new VocabularyCache(); - var failure = Assert.Throws(() => vocabulary.Replace("model", values, maxValues: 3)); - Assert.Equal("model", failure.Slot); - } - - /// A facet read against a path with no keyword index fails startup. - [QdrantFact] - public async Task FacetRead_AgainstAPathWithNoKeywordIndex_FailsStartup() - { - var port = BuildStore(); - - // "body" carries no payload index at all in this corpus -- the same uncaught exception - // ApplyVocabularyAsync would let propagate straight out of a boot it never wraps in a try. - var failure = await Assert.ThrowsAsync( - async () => await port.ReadAsync("body", 100, TestContext.Current.CancellationToken)); - - Assert.Equal(StatusCode.InvalidArgument, failure.StatusCode); - // §10 requires the exception to name the offending path -- the only part of this row a real - // Qdrant response actually decides, as opposed to the fact of throwing at all. - Assert.Contains("body", failure.Message, StringComparison.Ordinal); - } - /// A single-facet fromState deployment does not throw: the probe is skipped and the turn returns "holds nothing" (K33). [QdrantFact] public async Task SingleFacetFromStateDeployment_DoesNotThrow_ProbeIsSkipped_HoldsNothing() @@ -551,80 +483,10 @@ public async Task ProbeThatThrows_ReturnsHoldsNothing_LogsItsOwnEvent_LeavesTheM Assert.Empty(loggers.Of(12)); } - // ----------------------------------------------------------------------------------------- - // The Task A7 debt: a live turn proving the boot-filled vocabulary cache reaches the extractor. - // ----------------------------------------------------------------------------------------- - - /// - /// A value read live from the real collection's own facet -- never hand-seeded -- reaches the - /// extractor's gate and links. Task A7 proved the cache reaches CallSessionFactory only by - /// code review, a construction smoke test and a shared-instance proof in the refresh test; this is - /// the first place a value that could only have come from that boot read is actually linked. - /// - [QdrantFact] - public async Task LiveTurn_BootFilledVocabularyCache_LinksAReallyReadValue() - { - var vocabulary = await SeedVocabularyFromRealQdrantAsync(); - - RoutingChatClientFactory chatClients = new(new FixedTextChatClient("okay.")); - chatClients.Route("fill", new FixedTextChatClient("""{"model":"ct900ent"}""")); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(VocabularyOnlyYaml), - new AgentCompilationContext(chatClients) { Knowledge = BuildStore() }); - - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: vocabulary) - .Create("call-a7-live-extractor-positive"); - - await session.RunTurnAsync("I have a CT900ENT", TestContext.Current.CancellationToken); - - // "ct900ent" is not a value this test wrote anywhere -- it is the corpus's own spelling, read - // back from Qdrant into `vocabulary` a few lines above and nowhere else in this method. - Assert.Equal("ct900ent", session.State.Read("model")?.GetValue()); - } - - /// - /// The gate's other half: a value the same real read never produced is refused, proving the accept - /// above is really checking the boot-filled cache and not simply accepting any string. - /// - [QdrantFact] - public async Task LiveTurn_AValueTheBootReadNeverProduced_IsRefused() - { - var vocabulary = await SeedVocabularyFromRealQdrantAsync(); - - RoutingChatClientFactory chatClients = new(new FixedTextChatClient("okay.")); - chatClients.Route("fill", new FixedTextChatClient("""{"model":"xt385"}""")); - - var compiled = ConfigurationCompiler.Compile( - ConfigurationLoader.LoadYaml(VocabularyOnlyYaml), - new AgentCompilationContext(chatClients) { Knowledge = BuildStore() }); - - var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); - var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: vocabulary) - .Create("call-a7-live-extractor-negative"); - - await session.RunTurnAsync("I have an XT385", TestContext.Current.CancellationToken); - - Assert.Null(session.State.Read("model")); - } - // ----------------------------------------------------------------------------------------- // Helpers. // ----------------------------------------------------------------------------------------- - private async Task SeedVocabularyFromRealQdrantAsync() - { - var port = BuildStore(); - var values = await port.ReadAsync("facets.model", limit: 2000, TestContext.Current.CancellationToken); - - var vocabulary = new VocabularyCache(); - vocabulary.Replace("model", values, maxValues: 2000, wildcardValue: "*"); - return vocabulary; - } - private async Task RunAsync( string yaml, string callerQuestion, @@ -648,7 +510,7 @@ private async Task RunAsync( var extractor = CallSessionFactory.CreateExtractor(compiled, chatClients); var session = new CallSessionFactory( - compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor, vocabulary: new VocabularyCache()) + compiled, new GuardEvaluator(compiled.Configuration.Guards), extractor) .Create($"call-{Guid.NewGuid():N}"); await session.RunTurnAsync(callerQuestion, TestContext.Current.CancellationToken); @@ -688,9 +550,8 @@ private static string BuildTwoFacetYaml(int maxCandidates = 6) /// calling this -- never the reverse. Collection creation, every index, and the upsert can each /// throw against a live, sometimes-contended server, and if that happened inside an un-tried /// helper the collection this call already created on the server would be orphaned with nothing - /// left to drop it. Matches 's - /// own shape: creation, indexing and upsert all inside one try, one unconditional - /// DeleteCollectionAsync in the caller's own finally. + /// left to drop it. Creation, indexing and upsert all sit inside one try, with one + /// unconditional DeleteCollectionAsync in the caller's own finally. /// private async Task FillAdHocCollectionAsync( string collection, PointStruct[] points, bool scoped) diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetVocabularyTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetVocabularyTests.cs deleted file mode 100644 index f5ef78a5..00000000 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/FacetVocabularyTests.cs +++ /dev/null @@ -1,173 +0,0 @@ -using AgentCore.Application.Configuration.Schema; -using AgentCore.Application.Ports; -using AgentCore.Infrastructure.Knowledge.VectorData.Qdrant; -using AgentCore.Infrastructure.Tests.Fakes; -using Grpc.Core; -using Qdrant.Client; -using Qdrant.Client.Grpc; -using Xunit; - -namespace AgentCore.Infrastructure.Tests.Knowledge.VectorData.Qdrant; - -/// -/// The 30-card synthetic corpus, built once for the class. Every test here only reads. -/// -public sealed class FacetVocabularyCorpusFixture : IAsyncLifetime -{ - public string Name { get; } = $"facet-vocab-{Guid.NewGuid():N}"; - - public QdrantClient Client { get; private set; } = null!; - - public async ValueTask InitializeAsync() - { - if (!QdrantServer.IsConfigured) - { - return; - } - - Client = QdrantServer.CreateClient(); - await KbShapedCorpus.CreateAsync(Client, Name, interleaved: true, TestContext.Current.CancellationToken); - } - - public async ValueTask DisposeAsync() - { - if (Client is null) - { - return; - } - - try - { - await Client.DeleteCollectionAsync(Name); - } - finally - { - Client.Dispose(); - } - } -} - -/// -/// against a real Qdrant: what §12's four acceptance -/// clauses ask of . -/// -[Collection(QdrantServerCollection.Name)] -public sealed class FacetVocabularyTests : IClassFixture -{ - private readonly FacetVocabularyCorpusFixture _corpus; - - public FacetVocabularyTests(FacetVocabularyCorpusFixture corpus) => _corpus = corpus; - - [QdrantFact] - public async Task ReadAsync_ReturnsEveryDistinctValueAtThePath() - { - var values = await Port().ReadAsync("facets.model", 100, TestContext.Current.CancellationToken); - - Assert.Equal(["ct900", "ct900ent", "ctsbs900"], values.Order(StringComparer.Ordinal)); - } - - [QdrantFact] - public async Task ReadAsync_ResultCountEqualsLimit_ReturnsExactlyLimitValues() - { - // card_id is a Keyword-indexed field carrying 30 distinct values -- far above this limit. - var values = await Port().ReadAsync("card_id", 5, TestContext.Current.CancellationToken); - - Assert.Equal(5, values.Count); - } - - [QdrantFact] - public async Task ReadAsync_PathWithNoKeywordIndex_ThrowsAndNamesThePath() - { - // "body" carries no payload index at all in this corpus. - var ex = await Assert.ThrowsAsync( - async () => await Port().ReadAsync("body", 100, TestContext.Current.CancellationToken)); - - Assert.Equal(StatusCode.InvalidArgument, ex.StatusCode); - Assert.Contains("body", ex.Message, StringComparison.Ordinal); - } - - [QdrantFact] - public async Task ReadAsync_WildcardValueComesBackAsAnOrdinaryValue() - { - var client = QdrantServer.CreateClient(); - var collection = $"facet-vocab-wildcard-{Guid.NewGuid():N}"; - - try - { - await client.CreateCollectionAsync( - collection, - vectorsConfig: new VectorParamsMap - { - Map = { ["dense"] = new VectorParams { Size = KbShapedCorpus.Dim, Distance = Distance.Cosine } }, - }, - cancellationToken: TestContext.Current.CancellationToken); - await client.CreatePayloadIndexAsync( - collection, - "facets.brand", - PayloadSchemaType.Keyword, - cancellationToken: TestContext.Current.CancellationToken); - - var points = new[] - { - WildcardCard("card-1", brand: "*"), - WildcardCard("card-2", brand: "sole"), - }; - await client.UpsertAsync(collection, points, cancellationToken: TestContext.Current.CancellationToken); - - var port = new QdrantKnowledgeStore( - new QdrantSearchChannel(client), - new FakeEmbeddingGenerator(KbShapedCorpus.QueryVector()), - new QdrantKnowledgeStoreOptions - { - Collection = collection, - Scoped = false, - Fields = new KnowledgeFieldsConfiguration { Id = "card_id", Body = "body" }, - }); - - var values = await port.ReadAsync("facets.brand", 100, TestContext.Current.CancellationToken); - - Assert.Contains("*", values); - Assert.Contains("sole", values); - } - finally - { - await client.DeleteCollectionAsync(collection, cancellationToken: TestContext.Current.CancellationToken); - client.Dispose(); - } - } - - private static PointStruct WildcardCard(string cardId, string brand) - { - var point = new PointStruct - { - Id = new PointId { Uuid = Guid.NewGuid().ToString() }, - Vectors = new Vectors - { - Vectors_ = new NamedVectors { Vectors = { ["dense"] = KbShapedCorpus.QueryVector() } }, - }, - }; - - point.Payload["card_id"] = cardId; - point.Payload["body"] = $"{cardId} body"; - point.Payload["facets"] = new Value - { - StructValue = new Struct - { - Fields = { ["brand"] = new Value { StringValue = brand } }, - }, - }; - - return point; - } - - private QdrantKnowledgeStore Port() => new( - new QdrantSearchChannel(_corpus.Client), - new FakeEmbeddingGenerator(KbShapedCorpus.QueryVector()), - new QdrantKnowledgeStoreOptions - { - Collection = _corpus.Name, - Scoped = false, - VectorName = "dense", - Fields = new KnowledgeFieldsConfiguration { Id = "card_id", Body = "body" }, - }); -} diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/CapturingSearchChannel.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/CapturingSearchChannel.cs index f99a66c3..3ed07cf0 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/CapturingSearchChannel.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/CapturingSearchChannel.cs @@ -76,8 +76,4 @@ public Task> ScrollAsync( ScrollFilter = filter; return Task.FromResult(_fetched); } - - public Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken) => - throw new NotSupportedException("No test here drives a facet read; use QdrantSearchChannel against a live server."); } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/FacetScrollChannel.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/FacetScrollChannel.cs index 173830bd..dc8830ed 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/FacetScrollChannel.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/FacetScrollChannel.cs @@ -36,8 +36,4 @@ public Task> ScrollAsync( LastLimit = limit; return Task.FromResult(_points); } - - public Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken) => - throw new NotSupportedException("a facet read never reads distinct values."); } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/HangingSearchChannel.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/HangingSearchChannel.cs index 2c0d9afe..82f8345c 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/HangingSearchChannel.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/HangingSearchChannel.cs @@ -29,11 +29,4 @@ public async Task> ScrollAsync( await Task.Delay(_delay, cancellationToken).ConfigureAwait(false); return []; } - - public async Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken) - { - await Task.Delay(_delay, cancellationToken).ConfigureAwait(false); - return []; - } } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/RecordingSearchChannel.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/RecordingSearchChannel.cs index aad035a3..d35619a5 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/RecordingSearchChannel.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/Fakes/RecordingSearchChannel.cs @@ -35,8 +35,4 @@ public Task> RetrieveAsync( public Task> ScrollAsync( string collection, Filter filter, uint limit, CancellationToken cancellationToken) => throw new NotSupportedException("These tests drive links.lookup: direct, which never scrolls."); - - public Task> FacetAsync( - string collection, string key, ulong limit, CancellationToken cancellationToken) => - throw new NotSupportedException("These tests drive links.lookup: direct, which never facets."); } diff --git a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs index abad9f9b..ea7d5216 100644 --- a/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs +++ b/tests/AgentCore.Infrastructure.Tests/Knowledge/VectorData/Qdrant/QdrantKnowledgeStoreTests.cs @@ -132,25 +132,6 @@ public void Options_LeftAtTheirDefaults_CarryTheValuesTheDesignNames() Assert.Null(options.ScopeTemplate); } - [Fact] - public async Task ReadAsync_NegativeLimit_Throws() - { - // limit becomes (ulong)limit right below the guard; without it, a negative int wraps into a - // huge facet request instead of failing the way a public port method should. - var store = new QdrantKnowledgeStore( - new CapturingSearchChannel([]), - new FakeEmbeddingGenerator(1f), - new QdrantKnowledgeStoreOptions - { - Collection = "anything", - Scoped = false, - Fields = new KnowledgeFieldsConfiguration { Body = "body" }, - }); - - await Assert.ThrowsAsync( - async () => await store.ReadAsync("facets.brand", -1, TestContext.Current.CancellationToken)); - } - [QdrantFact] public async Task SearchAsync_LookalikeIdentifier_RanksTheIdentifierCardFirst() {