From 6ca5f8935645b15b304f2778cf1ce883971b2f5b Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 23 Nov 2026 04:32:15 +0000 Subject: [PATCH] Use prompt-defined structured output contracts --- docs/roadmap/implementation.md | 7 + internal/cli/process.go | 1 - .../cli/process_ordered_integration_test.go | 61 ++++++++ internal/core/config/config.go | 4 +- internal/core/config/config_test.go | 3 +- internal/core/config/resolve.go | 1 - internal/core/config/resolve_test.go | 4 +- internal/framework/llm/adapter.go | 18 +-- .../framework/llm/adapter_capacity_test.go | 5 +- internal/framework/llm/adapter_test.go | 96 ++++++++---- internal/framework/llm/conversation_test.go | 13 +- internal/framework/llm/coordinate_test.go | 45 +++++- internal/framework/llm/native_adapter_test.go | 32 +++- internal/framework/llm/observations_test.go | 3 +- .../adapter_integration_test.go | 2 +- .../framework/proposal_generation/generate.go | 6 +- .../proposal_generation/generate_test.go | 23 +-- internal/framework/responseschema/registry.go | 144 +----------------- .../framework/responseschema/registry_test.go | 121 +-------------- .../framework/runner/cancellation_test.go | 4 +- internal/framework/runner/repair.go | 3 +- internal/framework/runner/repair_test.go | 3 +- internal/framework/structuredoutput/call.go | 14 +- .../validators/llm_integration_test.go | 2 +- .../framework/validators/llm_validators.go | 8 +- .../validators/llm_validators_test.go | 16 +- internal/modules/glossary/module_test.go | 2 +- internal/modules/grammar/module_test.go | 2 +- internal/modules/homophones/module_test.go | 2 +- internal/modules/spoken_word/module_test.go | 2 +- internal/prompts/registry_test.go | 97 ++++++------ 31 files changed, 299 insertions(+), 445 deletions(-) diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 1d29357..8c6eef2 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -275,6 +275,13 @@ an assembled partial-success case showing usable sibling work continues. Update adapter, conversation, proposal, validator, runner, and config fixtures at their existing ownership boundaries. +**Complete.** Prompt definitions now select structural contracts and repair +budgets. The Audita schema registry and configuration override are removed. +Focused tests passed for all eleven shipped prompts, explicit repair budgets, +operator replacements, recoverable decode failures including coordinated repair, +partial pipeline progress, and the affected CLI, runner, validator, module, and +configuration packages. + ## Stage 5: Retain Native Execution Evidence in the Collector **Outcome:** Execution collection carries Audita attribution around native facts, diff --git a/internal/cli/process.go b/internal/cli/process.go index 3d07082..ceb169c 100644 --- a/internal/cli/process.go +++ b/internal/cli/process.go @@ -10,7 +10,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/core/outputschema" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner" "go.maximumdirect.net/ckconfig" diff --git a/internal/cli/process_ordered_integration_test.go b/internal/cli/process_ordered_integration_test.go index 04979fa..f255c57 100644 --- a/internal/cli/process_ordered_integration_test.go +++ b/internal/cli/process_ordered_integration_test.go @@ -243,3 +243,64 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) { t.Fatalf("result=%+v errors=%+v", result.Transcript, result.Snapshot.Errors) } } + +func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) { + dir := t.TempDir() + files := map[string]string{ + "config.yml": "version: 3\nllm: {validation_profile: review}\npipeline:\n stages:\n - module: grammar\n llm: {proposal_profile: invalid}\n - module: homophones\n llm: {proposal_profile: good}\n", + "prompts.yml": "profiles:\n - {id: invalid, endpoint: 'https://example.invalid/v1', model: invalid, api_key_required: false}\n - {id: good, endpoint: 'https://example.invalid/v1', model: good, api_key_required: false}\n - {id: review, endpoint: 'https://example.invalid/v1', model: review, api_key_required: false}\ncollections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: [{role: user, content: 'operator prompt'}]\n output: {format: text, validation_mode: none}\n", + "transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"helo"}]`, + } + for name, value := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0600); err != nil { + t.Fatal(err) + } + } + loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "") + if err != nil { + t.Fatal(err) + } + transport := controlledTransport(func(r *http.Request) (*http.Response, error) { + var request struct { + Model string `json:"model"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return nil, err + } + output := `{"validations":[{"correction_index":1,"approved":true,"reason":"ok"}]}` + switch request.Model { + case "invalid": + output = `{"corrections":[` + case "good": + output = `{"corrections":[{"id":1,"original_text":"helo","corrected_text":"hello"}]}` + } + encoded, err := json.Marshal(output) + if err != nil { + return nil, err + } + body := fmt.Sprintf(`{"model":%q,"choices":[{"message":{"content":%s}}]}`, request.Model, encoded) + return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil + }) + runtime, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) + if err != nil { + t.Fatal(err) + } + source, err := schema.ParseSourceTranscriptJSON([]byte(files["transcript.json"])) + if err != nil { + t.Fatal(err) + } + inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source} + loaded.Config.Application.Reporting.StdoutDir = dir + prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(dir, "transcript.json")}, inputs, &bytes.Buffer{}) + if err != nil { + t.Fatal(err) + } + defer prepared.Prepared.Output.Close() + result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) + if err != nil { + t.Fatal(err) + } + if result.Transcript.Segments[0].Text != "hello" || len(result.Snapshot.Errors) != 1 || (result.Snapshot.Errors[0].StageIndex == nil || *result.Snapshot.Errors[0].StageIndex != 0) || len(result.Snapshot.Errors[0].Failures) != 1 || result.Snapshot.Errors[0].Failures[0].Reason != "invalid_output" { + t.Fatalf("transcript=%+v errors=%+v", result.Transcript, result.Snapshot.Errors) + } +} diff --git a/internal/core/config/config.go b/internal/core/config/config.go index 945c25d..c3ddb9b 100644 --- a/internal/core/config/config.go +++ b/internal/core/config/config.go @@ -50,7 +50,6 @@ type LLM struct { CorrectionRepairProfile *string `yaml:"correction_repair_profile"` CorrectionRepairAttempts int `yaml:"correction_repair_attempts"` TransientRetries int `yaml:"transient_retries"` - RepairAttempts int `yaml:"repair_attempts"` OperationTimeout time.Duration `yaml:"operation_timeout"` } type Pipeline struct { @@ -96,7 +95,7 @@ type Reporting struct { func defaults() Config { return Config{ Version: 3, - LLM: LLM{TransientRetries: 2, RepairAttempts: 2, CorrectionRepairAttempts: 1, OperationTimeout: 15 * time.Minute}, + LLM: LLM{TransientRetries: 2, CorrectionRepairAttempts: 1, OperationTimeout: 15 * time.Minute}, Pipeline: Pipeline{Stages: []Stage{{Module: "glossary"}, {Module: "homophones"}, {Module: "glossary"}, {Module: "spoken_word"}, {Module: "grammar"}}}, Output: Output{Schema: "bare-segments"}, Validation: Validation{MaxPromptTokens: DefaultValidationMaxPromptTokens}, @@ -176,7 +175,6 @@ func validate(c *Config, v *ck.Validation) { func validateRuntimeSettings(check func(bool, ck.Path, string), base ck.Path, settings LLM, validation Validation, context Context) { llm := base.Key("llm") check(settings.TransientRetries >= 0, llm.Key("transient_retries"), "retry budget must be non-negative") - check(settings.RepairAttempts >= 0 && settings.RepairAttempts <= 3, llm.Key("repair_attempts"), "repair attempts must be between zero and three") check(settings.CorrectionRepairAttempts >= 0, llm.Key("correction_repair_attempts"), "correction repair attempts must be non-negative") check(settings.CorrectionRepairProfile == nil || *settings.CorrectionRepairProfile != "", llm.Key("correction_repair_profile"), "correction repair profile must not be empty; use null to clear it") check(settings.OperationTimeout > 0, llm.Key("operation_timeout"), "operation timeout must be positive") diff --git a/internal/core/config/config_test.go b/internal/core/config/config_test.go index 881165e..63d06f6 100644 --- a/internal/core/config/config_test.go +++ b/internal/core/config/config_test.go @@ -51,7 +51,8 @@ func TestSchemaConstraintsAndExplicitValues(t *testing.T) { {"unknown module", "pipeline:\n stages:\n - module: unknown\n", false}, {"invalid chunk limit", "chunking:\n target_sections: 0\n", false}, {"null group", "llm: null\n", false}, - {"zero budgets", "llm:\n transient_retries: 0\n repair_attempts: 0\n", true}, + {"zero retries", "llm:\n transient_retries: 0\n", true}, + {"retired repair budget", "llm:\n repair_attempts: 0\n", false}, } { t.Run(tc.name, func(t *testing.T) { if err := os.WriteFile(path, []byte(tc.text), 0644); err != nil { diff --git a/internal/core/config/resolve.go b/internal/core/config/resolve.go index adc1875..a68d5e6 100644 --- a/internal/core/config/resolve.go +++ b/internal/core/config/resolve.go @@ -63,7 +63,6 @@ func resolveSettings(c *Config, r *ck.Resolution) error { proposal := llm.Key("proposal_profile") ck.Default(r, proposal, &item.LLM.ProposalProfile, cloneSelection(c.LLM.ProposalProfile), "inherit proposal profile", rootLLM.Key("proposal_profile")) ck.Default(r, llm.Key("transient_retries"), &item.LLM.TransientRetries, c.LLM.TransientRetries, "inherit retry budget", rootLLM.Key("transient_retries")) - ck.Default(r, llm.Key("repair_attempts"), &item.LLM.RepairAttempts, c.LLM.RepairAttempts, "inherit repair budget", rootLLM.Key("repair_attempts")) ck.Default(r, llm.Key("correction_repair_attempts"), &item.LLM.CorrectionRepairAttempts, c.LLM.CorrectionRepairAttempts, "inherit correction repair budget", rootLLM.Key("correction_repair_attempts")) ck.Default(r, llm.Key("operation_timeout"), &item.LLM.OperationTimeout, c.LLM.OperationTimeout, "inherit operation timeout", rootLLM.Key("operation_timeout")) ck.Default(r, base.Key("validation").Key("max_prompt_tokens"), &item.Validation.MaxPromptTokens, c.Validation.MaxPromptTokens, "inherit validation budget", ck.Keys("validation", "max_prompt_tokens")) diff --git a/internal/core/config/resolve_test.go b/internal/core/config/resolve_test.go index 4fc1b49..48c5138 100644 --- a/internal/core/config/resolve_test.go +++ b/internal/core/config/resolve_test.go @@ -27,7 +27,6 @@ func TestResolutionCopiesRootOverridesAndHonorsClears(t *testing.T) { glossaries: [party] llm: proposal_profile: A - repair_attempts: 2 context: description: root pipeline: @@ -36,7 +35,6 @@ pipeline: glossaries: [party] llm: proposal_profile: B - repair_attempts: 0 context: description: "" - module: grammar @@ -52,7 +50,7 @@ pipeline: if !reflect.DeepEqual(cfg.ProtectedTerms, []string{"spells"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[0].Glossaries, []string{"party"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[1].Glossaries, []string{"spells"}) || len(cfg.Pipeline.Stages[2].Glossaries) != 0 { t.Fatalf("resolved: %+v", cfg) } - if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].LLM.RepairAttempts != 0 || cfg.Pipeline.Stages[0].Context.Description != "" { + if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].Context.Description != "" { t.Fatalf("clears lost: %+v", cfg.Pipeline.Stages) } if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" { diff --git a/internal/framework/llm/adapter.go b/internal/framework/llm/adapter.go index 3acc132..dd4ca1e 100644 --- a/internal/framework/llm/adapter.go +++ b/internal/framework/llm/adapter.go @@ -10,7 +10,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" pk "go.maximumdirect.net/promptkit" @@ -139,15 +138,10 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re if err := validateOutputTarget(out); err != nil { return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "invalid structured output target", Cause: err}) } - contract, err := OutputContract(req.Schema, c.settings.RepairAttempts) - if err != nil { - return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "unknown structured response schema", Cause: err}) - } call.request = pk.RunRequest{ PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables), CaptureExchange: req.CaptureExchange, TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout, - Validation: contract, Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) { if event.Kind == pk.ExecutionFinished { mu.Lock() @@ -195,7 +189,8 @@ func (c *RoleClient) finishResponse(parent context.Context, response *structured } if decodeErr := json.Unmarshal([]byte(result.RawOutput), out); decodeErr != nil { var typeError *json.UnmarshalTypeError - if errors.As(decodeErr, &typeError) { + var syntaxError *json.SyntaxError + if errors.As(decodeErr, &typeError) || errors.As(decodeErr, &syntaxError) { return &structuredoutput.Failure{Class: structuredoutput.FailureRecoverable, Reason: outcomes.ReasonInvalidOutput, Message: "structured output contains an unusable value", Cause: decodeErr} } return &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "validated structured output could not be decoded", Cause: decodeErr} @@ -216,15 +211,6 @@ func (c *RoleClient) CompleteStructured(ctx context.Context, req structuredoutpu return call.finish(result, err) } -// OutputContract maps an Audita domain schema to the native request contract. -func OutputContract(schema responseschema.Key, repairs int) (*pk.OutputContract, error) { - path, ok := responseschema.AssetPath(schema) - if !ok { - return nil, fmt.Errorf("schema %q", schema) - } - return &pk.OutputContract{Format: pk.FormatJSON, ValidationMode: pk.ValidationJSONSchema, SchemaPath: path, RepairAttempts: repairs}, nil -} - // classifiedFailure deliberately checks setup defects before broad PromptKit // validation/generation wrappers. Provider text is kept only in the typed cause. func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure { diff --git a/internal/framework/llm/adapter_capacity_test.go b/internal/framework/llm/adapter_capacity_test.go index 9ead440..4796551 100644 --- a/internal/framework/llm/adapter_capacity_test.go +++ b/internal/framework/llm/adapter_capacity_test.go @@ -13,7 +13,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" ck "go.maximumdirect.net/configkit" ) @@ -63,7 +62,7 @@ func TestRolesShareBackendCapacityAndReleaseAfterCancellation(t *testing.T) { if err != nil { t.Fatal(err) } - request := adapterRequest(responseschema.CorrectionSetKey) + request := adapterRequest("proposal") done := make(chan error, 1) go func() { _, err := proposal.CompleteStructured(context.Background(), request, &map[string]any{}) @@ -113,7 +112,7 @@ func TestDistinctBackendsHaveIndependentCapacity(t *testing.T) { if err != nil { t.Fatal(err) } - request := adapterRequest(responseschema.CorrectionSetKey) + request := adapterRequest("proposal") done := make(chan error, 2) go func() { _, err := first.CompleteStructured(context.Background(), request, &map[string]any{}) diff --git a/internal/framework/llm/adapter_test.go b/internal/framework/llm/adapter_test.go index 6744aa9..8998ecf 100644 --- a/internal/framework/llm/adapter_test.go +++ b/internal/framework/llm/adapter_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "io/fs" "net/http" "os" "path/filepath" @@ -18,7 +19,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ck "go.maximumdirect.net/configkit" @@ -85,6 +85,25 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in t.Fatal(err) } } + // Use complete operator definitions so each fixture selects its own budget. + promptDir := filepath.Join(dir, "prompts") + if err := os.Mkdir(promptDir, 0700); err != nil { + t.Fatal(err) + } + for _, meta := range prompts.RegisteredMetadata() { + if (operatorPrompt != "" && meta.PromptID == prompts.PromptIDModuleGlossaryProposal) || + (strings.Contains(operatorPrompt, "id: modules.grammar.repair") && meta.PromptID == prompts.PromptIDModuleGrammarRepair) { + continue + } + data, err := fs.ReadFile(prompts.Filesystem(), meta.EmbeddedPath) + if err != nil { + t.Fatal(err) + } + data = append(data, []byte(fmt.Sprintf(" repair_attempts: %d\n", repairs))...) + if err := os.WriteFile(filepath.Join(promptDir, filepath.Base(meta.EmbeddedPath)), data, 0600); err != nil { + t.Fatal(err) + } + } loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "") if err != nil { t.Fatal(err) @@ -115,7 +134,7 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in if err != nil { t.Fatal(err) } - settings := config.Config{LLM: config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries, RepairAttempts: repairs}} + settings := config.Config{LLM: config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries}} return &testRuntime{Runtime: runtime, Config: settings}, &count, dir } @@ -123,20 +142,20 @@ func operatorPromptDocument(system, user string) string { return fmt.Sprintf("collections:\n audita:\n prompts:\n - id: modules.glossary.proposal\n messages:\n - role: system\n content: %q\n - role: user\n content: %q\n output:\n format: text\n validation_mode: none\n", system, user) } -func adapterRequest(schema responseschema.Key) structuredoutput.Request { +func adapterRequest(schema string) structuredoutput.Request { id := prompts.PromptIDModuleGlossaryProposal vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"} - if schema == responseschema.ValidatorDecisionSetKey { + if schema == "validation" { id = prompts.PromptIDValidatorEditorialReview vars = map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"} } - return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Schema: schema, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}} + return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}} } func TestPreparedAdapterRepairsAndClassifies(t *testing.T) { - for _, schema := range []responseschema.Key{responseschema.CorrectionSetKey, responseschema.ValidatorDecisionSetKey} { + for _, schema := range []string{"proposal", "validation"} { valid := `{"corrections":[]}` - if schema == responseschema.ValidatorDecisionSetKey { + if schema == "validation" { valid = `{"validations":[]}` } for _, tc := range []struct { @@ -161,7 +180,7 @@ func TestPreparedAdapterRepairsAndClassifies(t *testing.T) { t.Run(string(schema)+"/"+tc.name, func(t *testing.T) { runtime, count, _ := adapterFixture(t, tc.replies, tc.retries, tc.repairs, nil) role := "proposal" - if schema == responseschema.ValidatorDecisionSetKey { + if schema == "validation" { role = "validation" } var events []pk.ExecutionEvent @@ -251,7 +270,7 @@ func TestCorrectionSchemaReplacementValuesThroughAdapter(t *testing.T) { t.Fatal(err) } var out map[string]any - response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &out) + response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &out) if got := count.Load(); got != 1 { t.Fatalf("expected one provider generation, got %d", got) } @@ -296,7 +315,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) { if err != nil { t.Fatal(err) } - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") req.Variables["HardeningPolicy"] = "attacker-controlled" var out map[string]any response, err := client.CompleteStructured(context.Background(), req, &out) @@ -329,7 +348,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) { } -func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing.T) { +func TestOperatorPromptUsesOwnContractAndOptionalSharedText(t *testing.T) { cases := []struct { name string system string @@ -343,8 +362,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing name: "operator text without shared references", system: "Operator system instructions.", user: "Operator request without variables.", - replies: []reply{{200, `{"wrong":true}`}, {200, `{"corrections":[]}`}}, - repairs: 1, + replies: []reply{{200, `{"wrong":true}`}}, wantSystem: "Operator system instructions.", wantUser: "Operator request without variables.", }, @@ -376,7 +394,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing if err != nil { t.Fatal(err) } - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") if tc.name == "operator text with shared references" { req.Variables["HardeningPolicy"] = "attacker-controlled" } @@ -416,7 +434,7 @@ func TestPreparedAdapterRejectsTargetDriftAndPreparationErrors(t *testing.T) { if err != nil { t.Fatal(err) } - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") req.PromptID = "missing.prompt" var out map[string]any if _, err := client.CompleteStructured(context.Background(), req, &out); err == nil || count.Load() != 0 { @@ -438,7 +456,7 @@ func TestPreparedAdapterCancellationStopsRetryWait(t *testing.T) { t.Fatal(err) } var out map[string]any - _, err = client.CompleteStructured(ctx, adapterRequest(responseschema.CorrectionSetKey), &out) + _, err = client.CompleteStructured(ctx, adapterRequest("proposal"), &out) if !errors.Is(err, context.Canceled) || count.Load() != 1 { t.Fatalf("cancellation: %v, HTTP calls=%d", err, count.Load()) } @@ -453,7 +471,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t t.Fatal(err) } var output map[string]any - response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output) + response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonOperationTimeout || !errors.Is(err, pk.ErrOperationTimeout) || !response.Execution.Available { t.Fatalf("local timeout: failure=%#v counts=%+v", failure, response.Execution) @@ -461,7 +479,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t parent, cancel := context.WithCancel(context.Background()) cancel() - response, err = client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output) + response, err = client.CompleteStructured(parent, adapterRequest("proposal"), &output) if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureCanceled || failure.Reason != outcomes.ReasonCanceled || !errors.Is(err, context.Canceled) || response.Execution.Available { t.Fatalf("parent cancellation: failure=%#v counts=%+v", failure, response.Execution) } @@ -488,7 +506,7 @@ func TestPreparedAdapterDistinguishesAttemptTimeoutFromParentDeadline(t *testing defer cancel() before := count.Load() var output map[string]any - response, err := client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output) + response, err := client.CompleteStructured(parent, adapterRequest("proposal"), &output) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != tc.class || failure.Reason != tc.reason || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, pk.ErrOperationTimeout) || @@ -510,7 +528,7 @@ func TestPreparedAdapterMissingCredentialRetainsSetupCause(t *testing.T) { t.Fatal(err) } var output map[string]any - _, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output) + _, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure || !errors.Is(err, pk.ErrAPIKeyEnvMissing) || !strings.Contains(err.Error(), "ADAPTER_KEY") || @@ -530,21 +548,16 @@ func TestPreparedAdapterClassifiesSetupAndDomainDecodeFailures(t *testing.T) { CorrectionIndex int `json:"correction_index"` } `json:"validations"` } - response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.ValidatorDecisionSetKey), &output) + response, err := client.CompleteStructured(context.Background(), adapterRequest("validation"), &output) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || !response.Execution.Available { t.Fatalf("decode overflow: failure=%#v counts=%+v", failure, response.Execution) } - _, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), nil) + _, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), nil) if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure { t.Fatalf("invalid target: %#v", failure) } - req := adapterRequest("missing_schema") - _, err = client.CompleteStructured(context.Background(), req, &output) - if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure { - t.Fatalf("unknown schema: %#v", failure) - } - req = adapterRequest(responseschema.ValidatorDecisionSetKey) + req := adapterRequest("validation") req.PromptID = "missing.prompt" _, err = client.CompleteStructured(context.Background(), req, &output) if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure { @@ -559,7 +572,7 @@ func TestPreparedAdapterNonRetryableProviderStatus(t *testing.T) { t.Fatal(err) } var output map[string]any - response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output) + response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output) var failure *structuredoutput.Failure if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonProviderFailed || count.Load() != 1 || response.Execution.HTTPStatus == nil || *response.Execution.HTTPStatus != http.StatusBadRequest { t.Fatalf("non-retryable provider failure: failure=%#v calls=%d counts=%+v", failure, count.Load(), response.Execution) @@ -586,3 +599,28 @@ func TestOperationTimeoutDuringPreparationIsRecoverable(t *testing.T) { t.Fatalf("failure = %#v", failure) } } + +func TestPermissivePromptReturnsRecoverableDecodeFailures(t *testing.T) { + for _, tc := range []struct { + name, body string + }{ + {"malformed JSON", `{"corrections": [`}, + {"incompatible value", `{"corrections":"not-an-array"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + runtime, calls, _ := adapterFixtureWithPrompt(t, []reply{{200, tc.body}}, 0, 0, nil, operatorPromptDocument("system", "user")) + client, err := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, CallHooks{}) + if err != nil { + t.Fatal(err) + } + var output struct { + Corrections []struct{} `json:"corrections"` + } + _, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output) + var failure *structuredoutput.Failure + if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || calls.Load() != 1 { + t.Fatalf("failure=%v calls=%d", err, calls.Load()) + } + }) + } +} diff --git a/internal/framework/llm/conversation_test.go b/internal/framework/llm/conversation_test.go index f2abd9e..4d49cec 100644 --- a/internal/framework/llm/conversation_test.go +++ b/internal/framework/llm/conversation_test.go @@ -16,7 +16,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ck "go.maximumdirect.net/configkit" @@ -71,7 +70,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) { t.Fatal(err) } vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"} - initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: vars, CaptureExchange: true}, &map[string]any{}) + initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: vars, CaptureExchange: true}, &map[string]any{}) if err != nil || initial.Exchange == nil { t.Fatalf("capture: %+v %v", initial, err) } @@ -87,7 +86,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) { if turns == 2 { return nil, nil } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil }) if err != nil || exhausted || turns != 2 { t.Fatalf("coordinated dialogue: turns=%d exhausted=%v error=%v", turns, exhausted, err) @@ -112,7 +111,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) { if turn.Response != nil { return nil, turn.Err } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil } _, err = repair.Coordinate(context.Background(), initial.Exchange, 1, independent) if err != nil || len(messages) != 4 || len(messages[3]) != len(prefix)+2 || !strings.Contains(string(messages[3][len(prefix)+1].Content), "independent") { @@ -159,11 +158,11 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T) if err != nil { t.Fatal(err) } - client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: 1}, CallHooks{}) + client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{}) if err != nil { t.Fatal(err) } - base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{}) + base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{}) if err != nil { t.Fatal(err) } @@ -173,7 +172,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T) result = turn.Response return nil, turn.Err } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil }) if err != nil || exhausted || result == nil { t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err) diff --git a/internal/framework/llm/coordinate_test.go b/internal/framework/llm/coordinate_test.go index 9ada235..4289cec 100644 --- a/internal/framework/llm/coordinate_test.go +++ b/internal/framework/llm/coordinate_test.go @@ -6,7 +6,6 @@ import ( "testing" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" pk "go.maximumdirect.net/promptkit" @@ -31,7 +30,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) { if err != nil { t.Fatal(err) } - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") req.CaptureExchange = true base, err := client.CompleteStructured(context.Background(), req, &map[string]any{}) if err != nil { @@ -55,7 +54,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) { return nil, nil } } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil }) if err != nil || exhausted != tc.again || deliveries != 1 || count.Load() != 2 { t.Fatalf("exhausted=%v delivered=%d calls=%d err=%v", exhausted, deliveries, count.Load(), err) @@ -78,7 +77,7 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) { runtime, _, _ := adapterFixture(t, []reply{{200, `{"corrections":[]}`}, {200, `{"proposal_ref":1,"decision":{"action":"withdraw","correction":null}}`}}, 0, 0, nil) collector := NewObservationCollector() proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks()) - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") req.CaptureExchange = true base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{}) if err != nil { @@ -102,7 +101,7 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) { } return nil, turn.Err } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil }) if !errors.Is(err, context.Canceled) || deliveries != 1 { t.Fatalf("deliveries=%d err=%v", deliveries, err) @@ -118,7 +117,7 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) { proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks()) repair, _ := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, collector.Hooks()) validation, _ := runtime.NewRoleClient("validation", "base", runtime.Config.LLM, collector.Hooks()) - req := adapterRequest(responseschema.CorrectionSetKey) + req := adapterRequest("proposal") req.CaptureExchange = true base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{}) if err != nil { @@ -129,13 +128,43 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) { if turn.Err != nil { return nil, turn.Err } - _, err := validation.CompleteStructured(ctx, adapterRequest(responseschema.ValidatorDecisionSetKey), &map[string]any{}) + _, err := validation.CompleteStructured(ctx, adapterRequest("validation"), &map[string]any{}) return nil, err } - return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil }) summary := Summarize(collector.Snapshot()) if err != nil || count.Load() != 3 || summary.ProviderAttempts != 3 || summary.LogicalCalls != 3 || !summary.TerminalCoverageComplete { t.Fatalf("calls=%d summary=%+v err=%v", count.Load(), summary, err) } } + +func TestCoordinatorDeliversRecoverableMalformedOutput(t *testing.T) { + operator := "collections:\n audita:\n prompts:\n - id: modules.grammar.repair\n messages:\n - role: user\n content: '{{.RepairRequestJSON}}'\n output:\n format: text\n validation_mode: none\n" + runtime, count, _ := adapterFixtureWithPrompt(t, []reply{{200, `{"corrections":[]}`}, {200, `{"decision":[`}}, 0, 0, nil, operator) + client, err := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, CallHooks{}) + if err != nil { + t.Fatal(err) + } + request := adapterRequest("proposal") + request.CaptureExchange = true + base, err := client.CompleteStructured(context.Background(), request, &map[string]any{}) + if err != nil { + t.Fatal(err) + } + delivered := false + _, err = client.Coordinate(context.Background(), base.Exchange, 1, func(_ context.Context, turn structuredoutput.Turn) (*structuredoutput.Request, error) { + if turn.Response != nil { + delivered = true + var failure *structuredoutput.Failure + if !errors.As(turn.Err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput { + t.Fatalf("turn error = %v", turn.Err) + } + return nil, nil + } + return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil + }) + if err != nil || !delivered || count.Load() != 2 { + t.Fatalf("error=%v delivered=%v calls=%d", err, delivered, count.Load()) + } +} diff --git a/internal/framework/llm/native_adapter_test.go b/internal/framework/llm/native_adapter_test.go index 09c3ee3..3f32384 100644 --- a/internal/framework/llm/native_adapter_test.go +++ b/internal/framework/llm/native_adapter_test.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "io/fs" "net/http" "os" "path/filepath" @@ -16,7 +17,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ck "go.maximumdirect.net/configkit" @@ -58,7 +58,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) { t.Fatal(err) } var out map[string]any - _, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out) + _, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out) if err == nil || calls != 1 { t.Fatalf("error = %v, calls = %d", err, calls) } @@ -78,7 +78,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) { if err != nil { t.Fatal(err) } - request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} + request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} for _, tc := range []struct { name string repair int @@ -91,6 +91,22 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) { {"no repair", 0, []string{`{"wrong":true}`}, 1, false}, } { t.Run(tc.name, func(t *testing.T) { + prompt, err := fs.ReadFile(prompts.Filesystem(), "assets/prompts/modules.grammar.proposal.yaml") + if err != nil { + t.Fatal(err) + } + prompt = append(prompt, []byte(fmt.Sprintf(" repair_attempts: %d\n", tc.repair))...) + promptDir := filepath.Join(dir, "prompts") + if err := os.MkdirAll(promptDir, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(promptDir, "grammar.yml"), prompt, 0600); err != nil { + t.Fatal(err) + } + selected, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "") + if err != nil { + t.Fatal(err) + } calls := 0 httpClient := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) { item := tc.outputs[min(calls, len(tc.outputs)-1)] @@ -99,11 +115,11 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) { body := fmt.Sprintf(`{"model":"test-model","choices":[{"message":{"content":%s}}]}`, payload) return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil })} - runtime, err := NewRuntime(context.Background(), loaded, httpClient) + runtime, err := NewRuntime(context.Background(), selected, httpClient) if err != nil { t.Fatal(err) } - client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: tc.repair}, CallHooks{}) + client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{}) if err != nil { t.Fatal(err) } @@ -176,7 +192,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) { if err != nil { t.Fatal(err) } - request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} + request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} done := make(chan error, 1) go func() { _, err := first.CompleteStructured(context.Background(), request, &map[string]any{}) @@ -222,7 +238,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) { if err != nil { t.Fatal(err) } - req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} + req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} response, err := client.CompleteStructured(context.Background(), req, &map[string]any{}) if err != nil || calls != 2 || response.Execution.TransientRetries != 1 { t.Fatalf("error=%v calls=%d execution=%+v", err, calls, response.Execution) @@ -256,7 +272,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) { if err != nil { t.Fatal(err) } - req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} + req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} for _, tc := range []struct{ profile, auth string }{{"inherited", "Bearer backend-secret-value"}, {"explicit", "Bearer profile-secret-value"}, {"cleared", ""}} { t.Run(tc.profile, func(t *testing.T) { client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{}) diff --git a/internal/framework/llm/observations_test.go b/internal/framework/llm/observations_test.go index 173ab2b..90f2fec 100644 --- a/internal/framework/llm/observations_test.go +++ b/internal/framework/llm/observations_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" pk "go.maximumdirect.net/promptkit" ) @@ -98,7 +97,7 @@ func TestRoleClientFeedsCollectorAcrossPreparationFailure(t *testing.T) { if err != nil { t.Fatal(err) } - request := adapterRequest(responseschema.CorrectionSetKey) + request := adapterRequest("proposal") request.Context.ModuleInstance = "glossary_1" index := 3 request.Context.SectionIndex = &index diff --git a/internal/framework/proposal_generation/adapter_integration_test.go b/internal/framework/proposal_generation/adapter_integration_test.go index 3f9c1b7..a399791 100644 --- a/internal/framework/proposal_generation/adapter_integration_test.go +++ b/internal/framework/proposal_generation/adapter_integration_test.go @@ -56,7 +56,7 @@ func TestRepairedProposalStillFacesDomainChecks(t *testing.T) { t.Fatal(err) } settings := loaded.Config.Application.LLM - settings.TransientRetries, settings.RepairAttempts = 0, 1 + settings.TransientRetries = 0 client, err := runtime.NewRoleClient("proposal", "base", settings, llm.CallHooks{}) if err != nil { t.Fatal(err) diff --git a/internal/framework/proposal_generation/generate.go b/internal/framework/proposal_generation/generate.go index f129f7a..f7aabcd 100644 --- a/internal/framework/proposal_generation/generate.go +++ b/internal/framework/proposal_generation/generate.go @@ -13,7 +13,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/stagename" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" ) @@ -86,8 +85,8 @@ func GenerateCandidates(ctx context.Context, req Request) (Result, error) { CaptureExchange: req.CaptureExchange, CaptureDiagnostics: req.Interactions != nil, PromptID: req.PromptID, - Variables: req.Variables, Schema: responseschema.CorrectionSetKey, - Context: coordinates, + Variables: req.Variables, + Context: coordinates, }, &response) sectionIndex := 0 if req.Section != nil { @@ -113,7 +112,6 @@ func GenerateCandidates(ctx context.Context, req Request) (Result, error) { "segment_ids": segmentIDs(req.WorkingTranscript), "prompt": completion.Prompt, } - requestMetadata["response_schema"] = responseschema.MustLookup(responseschema.CorrectionSetKey).DiagnosticsMap() artifacts, _ = req.Interactions.WriteInteraction(structuredoutput.Interaction{ Name: stage, Context: coordinates, RequestMetadata: requestMetadata, RequestPayload: completion.Prepared, ResponsePayload: map[string]any{"decoded": response, "final_content": completion.FinalContent, "model": completion.Model}, diff --git a/internal/framework/proposal_generation/generate_test.go b/internal/framework/proposal_generation/generate_test.go index caa07d5..45c34f3 100644 --- a/internal/framework/proposal_generation/generate_test.go +++ b/internal/framework/proposal_generation/generate_test.go @@ -14,7 +14,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" ) @@ -122,12 +121,12 @@ func TestGenerateCandidatesUsesCorrectionSetSchema(t *testing.T) { t.Fatalf("expected 1 LLM call, got %d", len(client.calls)) } call := client.calls[0] - if call.Schema != responseschema.CorrectionSetKey || call.PromptID != req.PromptID || call.Context.Role != "proposal" { + if call.PromptID != req.PromptID || call.Context.Role != "proposal" { t.Fatalf("unexpected call contract: %+v", call) } } -func TestGenerateCandidatesDiagnosticsIncludeSchemaMetadata(t *testing.T) { +func TestGenerateCandidatesDiagnosticsOmitRegistrySchemaMetadata(t *testing.T) { client := &fakeStructuredClient{ responses: []StructuredCorrectionSet{ {Corrections: []StructuredCorrectionProposal{{SegmentReference: 1, OriginalText: "teh", CorrectedText: "the"}}}, @@ -146,13 +145,8 @@ func TestGenerateCandidatesDiagnosticsIncludeSchemaMetadata(t *testing.T) { if !ok { t.Fatalf("expected request metadata map, got %T", diag.lastRequestMetadata) } - schemaMap, ok := metadata["response_schema"].(map[string]any) - if !ok { - t.Fatalf("expected response_schema metadata map, got %T", metadata["response_schema"]) - } - want := responseschema.MustLookup(responseschema.CorrectionSetKey) - if schemaMap["id"] != want.ID || schemaMap["version"] != want.Version || schemaMap["name"] != want.Name || schemaMap["sha256"] != want.SHA256 { - t.Fatalf("unexpected diagnostics schema metadata: got=%v want=%+v", schemaMap, want) + if _, exists := metadata["response_schema"]; exists { + t.Fatal("unexpected registry schema metadata") } } @@ -293,13 +287,8 @@ func TestGenerateCandidatesDiagnosticsWritten(t *testing.T) { if start, ok := metadata["start_index"].(float64); !ok || start != 0 { t.Fatalf("missing response-local origin: %s", raw) } - schemaMap, ok := metadata["response_schema"].(map[string]any) - if !ok { - t.Fatalf("expected response_schema metadata in diagnostics, got %T", metadata["response_schema"]) - } - want := responseschema.MustLookup(responseschema.CorrectionSetKey) - if schemaMap["id"] != want.ID || schemaMap["version"] != want.Version || schemaMap["name"] != want.Name || schemaMap["sha256"] != want.SHA256 { - t.Fatalf("unexpected schema metadata in diagnostics: got=%v want=%+v", schemaMap, want) + if _, exists := metadata["response_schema"]; exists { + t.Fatal("unexpected registry schema metadata") } var coordinates struct { Context structuredoutput.DiagnosticContext `json:"context"` diff --git a/internal/framework/responseschema/registry.go b/internal/framework/responseschema/registry.go index 87aaf00..cc5fabe 100644 --- a/internal/framework/responseschema/registry.go +++ b/internal/framework/responseschema/registry.go @@ -1,154 +1,14 @@ package responseschema import ( - "crypto/sha256" "embed" - "encoding/hex" - "encoding/json" - "fmt" "io/fs" - "sort" - "strings" ) -// Key identifies one structured response schema used by Audita. -type Key string - -const ( - CorrectionSetKey Key = "correction_set" - CorrectionRepairKey Key = "correction_repair" - ValidatorDecisionSetKey Key = "validator_decision_set" - AssetRoot = "assets" - correctionSetSchemaID = "audita.correction_set" - correctionRepairSchemaID = "audita.correction_repair" - validatorDecisionSchemaID = "audita.validator_decision_set" - schemaVersionV1 = "v1" -) +const AssetRoot = "assets" //go:embed assets/*.json var schemaAssets embed.FS -// Filesystem exposes the canonical embedded schemas to PromptKit. +// Filesystem exposes embedded schemas to PromptKit. func Filesystem() fs.FS { return schemaAssets } - -func AssetPath(key Key) (string, bool) { - switch key { - case CorrectionSetKey: - return "correction_set.v1.json", true - case CorrectionRepairKey: - return "correction_repair.v1.json", true - case ValidatorDecisionSetKey: - return "validator_decision_set.v1.json", true - default: - return "", false - } -} - -// Schema describes one registered structured response schema. -type Schema struct { - ID string `json:"id"` - Version string `json:"version"` - Name string `json:"name"` - JSONSchema json.RawMessage `json:"json_schema"` - SHA256 string `json:"sha256"` -} - -func (s Schema) DiagnosticsMap() map[string]any { - return map[string]any{ - "id": s.ID, - "version": s.Version, - "name": s.Name, - "sha256": s.SHA256, - } -} - -var registry = map[Key]Schema{ - CorrectionRepairKey: mustBuildSchemaFromAsset(correctionRepairSchemaID, schemaVersionV1, "audita_correction_repair_v1", "assets/correction_repair.v1.json"), - CorrectionSetKey: mustBuildSchemaFromAsset( - correctionSetSchemaID, - schemaVersionV1, - "audita_correction_set_v1", - "assets/correction_set.v1.json", - ), - ValidatorDecisionSetKey: mustBuildSchemaFromAsset( - validatorDecisionSchemaID, - schemaVersionV1, - "audita_validator_decision_set_v1", - "assets/validator_decision_set.v1.json", - ), -} - -func Registered() []Schema { - keys := make([]string, 0, len(registry)) - for key := range registry { - keys = append(keys, string(key)) - } - sort.Strings(keys) - - out := make([]Schema, 0, len(keys)) - for _, key := range keys { - out = append(out, cloneSchema(registry[Key(key)])) - } - return out -} - -// Lookup returns a copy of the registered schema for the provided key. -func Lookup(key Key) (Schema, bool) { - schema, ok := registry[key] - if !ok { - return Schema{}, false - } - return cloneSchema(schema), true -} - -// MustLookup returns a copy of the registered schema and panics when missing. -func MustLookup(key Key) Schema { - schema, ok := Lookup(key) - if !ok { - panic(fmt.Sprintf("unknown structured response schema key %q", key)) - } - return schema -} - -func cloneSchema(in Schema) Schema { - out := in - if in.JSONSchema != nil { - out.JSONSchema = append(json.RawMessage(nil), in.JSONSchema...) - } - return out -} - -func mustBuildSchemaFromAsset(id string, version string, name string, assetPath string) Schema { - rawSchema, err := schemaAssets.ReadFile(assetPath) - if err != nil { - panic(fmt.Sprintf("read response schema asset %q: %v", assetPath, err)) - } - return mustBuildSchema(id, version, name, rawSchema) -} - -func mustBuildSchema(id string, version string, name string, rawSchema []byte) Schema { - id = strings.TrimSpace(id) - version = strings.TrimSpace(version) - name = strings.TrimSpace(name) - if id == "" { - panic("schema id must not be empty") - } - if version == "" { - panic("schema version must not be empty") - } - if name == "" { - panic("schema name must not be empty") - } - if !json.Valid(rawSchema) { - panic(fmt.Sprintf("schema %s:%s is not valid JSON", id, version)) - } - - hash := sha256.Sum256(rawSchema) - return Schema{ - ID: id, - Version: version, - Name: name, - JSONSchema: append(json.RawMessage(nil), rawSchema...), - SHA256: hex.EncodeToString(hash[:]), - } -} diff --git a/internal/framework/responseschema/registry_test.go b/internal/framework/responseschema/registry_test.go index 982bdf6..80808af 100644 --- a/internal/framework/responseschema/registry_test.go +++ b/internal/framework/responseschema/registry_test.go @@ -1,129 +1,20 @@ package responseschema import ( - "bytes" - "crypto/sha256" - "encoding/hex" "encoding/json" - "io" + "io/fs" "testing" jsonschema "github.com/santhosh-tekuri/jsonschema/v6" ) -func TestPromptKitSchemaPathsUseCanonicalAssets(t *testing.T) { - for _, key := range []Key{CorrectionSetKey, CorrectionRepairKey, ValidatorDecisionSetKey} { - path, ok := AssetPath(key) - if !ok { - t.Fatalf("missing path for %q", key) - } - file, err := Filesystem().Open(AssetRoot + "/" + path) - if err != nil { - t.Fatal(err) - } - data, err := io.ReadAll(file) - file.Close() - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(data, MustLookup(key).JSONSchema) { - t.Fatalf("PromptKit schema differs for %q", key) - } - } -} - -func TestLookupKnownSchemas(t *testing.T) { - correction, ok := Lookup(CorrectionSetKey) - if !ok { - t.Fatalf("expected correction-set schema to be registered") - } - if correction.ID != correctionSetSchemaID { - t.Fatalf("unexpected correction-set schema id %q", correction.ID) - } - if correction.Version != schemaVersionV1 { - t.Fatalf("unexpected correction-set schema version %q", correction.Version) - } - if correction.Name != "audita_correction_set_v1" { - t.Fatalf("unexpected correction-set schema name %q", correction.Name) - } - - validation, ok := Lookup(ValidatorDecisionSetKey) - if !ok { - t.Fatalf("expected validator-decision schema to be registered") - } - if validation.ID != validatorDecisionSchemaID { - t.Fatalf("unexpected validator-decision schema id %q", validation.ID) - } - if validation.Version != schemaVersionV1 { - t.Fatalf("unexpected validator-decision schema version %q", validation.Version) - } - if validation.Name != "audita_validator_decision_set_v1" { - t.Fatalf("unexpected validator-decision schema name %q", validation.Name) - } -} - -func TestLookupUnknownSchema(t *testing.T) { - if _, ok := Lookup(Key("missing")); ok { - t.Fatalf("expected unknown schema lookup to fail") - } -} - -func TestSchemaHashesMatchRegisteredJSON(t *testing.T) { - for _, key := range []Key{CorrectionSetKey, CorrectionRepairKey, ValidatorDecisionSetKey} { - schema, ok := Lookup(key) - if !ok { - t.Fatalf("missing schema %q", key) - } - sum := sha256.Sum256(schema.JSONSchema) - expected := hex.EncodeToString(sum[:]) - if schema.SHA256 != expected { - t.Fatalf("unexpected hash for %q: got %q want %q", key, schema.SHA256, expected) - } - } -} - -func TestLookupReturnsSchemaCopy(t *testing.T) { - schema, ok := Lookup(CorrectionSetKey) - if !ok { - t.Fatalf("missing correction-set schema") - } - if len(schema.JSONSchema) == 0 { - t.Fatalf("expected non-empty schema payload") - } - schema.JSONSchema[0] = 'x' - - again, ok := Lookup(CorrectionSetKey) - if !ok { - t.Fatalf("missing correction-set schema on second lookup") - } - if len(again.JSONSchema) == 0 { - t.Fatalf("unexpected empty schema payload") - } - if again.JSONSchema[0] != '{' { - t.Fatalf("expected lookup to return independent schema copy") - } -} - -func TestDiagnosticsMapIncludesStableSchemaMetadataShapeForAllSchemas(t *testing.T) { - registered := Registered() - if len(registered) == 0 { - t.Fatalf("expected registered response schemas") - } - - for _, schema := range registered { - metadataMap := schema.DiagnosticsMap() - if metadataMap["id"] != schema.ID || - metadataMap["version"] != schema.Version || - metadataMap["name"] != schema.Name || - metadataMap["sha256"] != schema.SHA256 { - t.Fatalf("unexpected diagnostics metadata map for %q: %+v", schema.ID, metadataMap) - } - } -} - func TestCorrectionRepairSchema(t *testing.T) { var document any - if err := json.Unmarshal(MustLookup(CorrectionRepairKey).JSONSchema, &document); err != nil { + raw, err := fs.ReadFile(Filesystem(), AssetRoot+"/correction_repair.v1.json") + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(raw, &document); err != nil { t.Fatal(err) } compiler := jsonschema.NewCompiler() diff --git a/internal/framework/runner/cancellation_test.go b/internal/framework/runner/cancellation_test.go index 04b44a7..6bde927 100644 --- a/internal/framework/runner/cancellation_test.go +++ b/internal/framework/runner/cancellation_test.go @@ -18,7 +18,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" @@ -101,8 +100,7 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) { var out map[string]any _, err := client.CompleteStructured(ctx, structuredoutput.Request{ PromptID: prompts.PromptIDValidatorEditorialReview, - Variables: map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}, Schema: responseschema.ValidatorDecisionSetKey, - Context: structuredoutput.DiagnosticContext{ModuleKey: req.ModuleKey, ModuleInstance: req.ModuleInstance, SectionIndex: req.SectionIndex}, + Variables: map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}, Context: structuredoutput.DiagnosticContext{ModuleKey: req.ModuleKey, ModuleInstance: req.ModuleInstance, SectionIndex: req.SectionIndex}, }, &out) return validators.Result{}, err }} diff --git a/internal/framework/runner/repair.go b/internal/framework/runner/repair.go index 7a6abd8..b4fe636 100644 --- a/internal/framework/runner/repair.go +++ b/internal/framework/runner/repair.go @@ -10,7 +10,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposal_generation" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators" ) @@ -163,7 +162,7 @@ func runRepairBranch(ctx context.Context, branchInput repairBranchInput) (repair } proposalIndex, attemptNumber := original.ProposalIndex, branch.AttemptCount+1 - return &structuredoutput.Request{PromptID: promptID, Variables: map[string]string{"RepairRequestJSON": payload}, Schema: responseschema.CorrectionRepairKey, CaptureDiagnostics: debug, Context: structuredoutput.DiagnosticContext{StageIndex: &input.Spec.Index, StageID: input.Spec.ID, Role: "correction_repair", ModuleKey: input.Spec.ModuleKey, ModuleInstance: input.Spec.InstanceName, SectionIndex: input.SectionIndex, ProposalIndex: &proposalIndex, RepairAttempt: &attemptNumber}}, nil + return &structuredoutput.Request{PromptID: promptID, Variables: map[string]string{"RepairRequestJSON": payload}, CaptureDiagnostics: debug, Context: structuredoutput.DiagnosticContext{StageIndex: &input.Spec.Index, StageID: input.Spec.ID, Role: "correction_repair", ModuleKey: input.Spec.ModuleKey, ModuleInstance: input.Spec.InstanceName, SectionIndex: input.SectionIndex, ProposalIndex: &proposalIndex, RepairAttempt: &attemptNumber}}, nil } exhausted, coordinationErr := input.Spec.RepairCoordinator.Coordinate(ctx, input.Exchange, input.Spec.Settings.LLM.CorrectionRepairAttempts, func(ctx context.Context, turn structuredoutput.Turn) (*structuredoutput.Request, error) { if turn.Response == nil { diff --git a/internal/framework/runner/repair_test.go b/internal/framework/runner/repair_test.go index 0ed634e..8047542 100644 --- a/internal/framework/runner/repair_test.go +++ b/internal/framework/runner/repair_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ck "go.maximumdirect.net/configkit" "io" @@ -514,7 +513,7 @@ func (c *repairClient) Coordinate(ctx context.Context, _ *structuredoutput.Excha t.Fatal(err) } var output map[string]any - base, err := client.CompleteStructured(ctx, structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, CaptureExchange: true, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &output) + base, err := client.CompleteStructured(ctx, structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, CaptureExchange: true, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &output) if err != nil { return false, err } diff --git a/internal/framework/structuredoutput/call.go b/internal/framework/structuredoutput/call.go index c37df56..5213214 100644 --- a/internal/framework/structuredoutput/call.go +++ b/internal/framework/structuredoutput/call.go @@ -6,7 +6,6 @@ import ( "time" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" ) // DiagnosticContext identifies the logical call without examining rendered text. @@ -23,15 +22,14 @@ type DiagnosticContext struct { RepairAttempt *int `json:"repair_attempt,omitempty"` } -// Request names an embedded prompt and response schema. Profile selection and +// Request names a prompt. Profile selection and // credentials are supplied by the role-bound runtime client. type Request struct { - PromptID string `json:"prompt_id"` - Variables map[string]string `json:"variables"` - Schema responseschema.Key `json:"schema"` - Context DiagnosticContext `json:"context"` - CaptureExchange bool `json:"-"` - CaptureDiagnostics bool `json:"-"` + PromptID string `json:"prompt_id"` + Variables map[string]string `json:"variables"` + Context DiagnosticContext `json:"context"` + CaptureExchange bool `json:"-"` + CaptureDiagnostics bool `json:"-"` } // PromptMetadata is the execution snapshot returned by the runtime when available. diff --git a/internal/framework/validators/llm_integration_test.go b/internal/framework/validators/llm_integration_test.go index a45824d..63ecff0 100644 --- a/internal/framework/validators/llm_integration_test.go +++ b/internal/framework/validators/llm_integration_test.go @@ -93,7 +93,7 @@ func testValidationClient(t *testing.T, transport http.RoundTripper) structuredo t.Fatal(err) } settings := loaded.Config.Application.LLM - settings.TransientRetries, settings.RepairAttempts = 0, 1 + settings.TransientRetries = 0 client, err := runtime.NewRoleClient("validation", "base", settings, llm.CallHooks{}) if err != nil { t.Fatal(err) diff --git a/internal/framework/validators/llm_validators.go b/internal/framework/validators/llm_validators.go index f1a3f7e..c6c97df 100644 --- a/internal/framework/validators/llm_validators.go +++ b/internal/framework/validators/llm_validators.go @@ -12,7 +12,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/core/jsonnumber" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/stagename" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" @@ -130,8 +129,8 @@ func (v *LLMBackedValidator) Validate(ctx context.Context, req Request) (Result, coordinates := structuredoutput.DiagnosticContext{StageIndex: req.StageIndex, StageID: req.StageID, Role: "validation", ModuleKey: req.ModuleKey, ModuleInstance: req.ModuleInstance, SectionIndex: req.SectionIndex, BatchIndex: &batch.BatchIndex, ValidatorName: v.name, ProposalIndex: req.RepairProposalIndex, RepairAttempt: req.RepairAttempt} completion, err = req.LLMClient.CompleteStructured(ctx, StructuredCompletionRequest{ PromptID: promptMetadata.PromptID, - Variables: variables, Schema: responseschema.ValidatorDecisionSetKey, - Context: coordinates, CaptureDiagnostics: req.Interactions != nil, + Variables: variables, + Context: coordinates, CaptureDiagnostics: req.Interactions != nil, }, &response) batchIndex := batch.BatchIndex operation := outcomes.Operation{ @@ -153,7 +152,6 @@ func (v *LLMBackedValidator) Validate(ctx context.Context, req Request) (Result, if coordinates.ProposalIndex != nil && req.RepairAttempt != nil { stageInstance = fmt.Sprintf("%s:proposal-%04d:attempt-%04d", stageInstance, *coordinates.ProposalIndex, *req.RepairAttempt) } - responseSchema := responseschema.MustLookup(responseschema.ValidatorDecisionSetKey) responsePayload := map[string]any{"decoded": response, "final_content": completion.FinalContent, "model": completion.Model} if reconciled != nil { view := *reconciled @@ -177,7 +175,7 @@ func (v *LLMBackedValidator) Validate(ctx context.Context, req Request) (Result, "stage_index": req.StageIndex, "stage_id": req.StageID, "module_key": req.ModuleKey, "validator_name": v.name, "validator_type": v.validatorType, "batch_index": batch.BatchIndex, "proposal_indices": indices, "repair_proposal_index": coordinates.ProposalIndex, "repair_attempt": req.RepairAttempt, - "prompt": completion.Prompt, "response_schema": responseSchema.DiagnosticsMap(), + "prompt": completion.Prompt, }, RequestPayload: completion.Prepared, ResponsePayload: responsePayload, ErrorPayload: errPayload(callErr), } diff --git a/internal/framework/validators/llm_validators_test.go b/internal/framework/validators/llm_validators_test.go index 1f4d930..6dee1b8 100644 --- a/internal/framework/validators/llm_validators_test.go +++ b/internal/framework/validators/llm_validators_test.go @@ -14,7 +14,6 @@ import ( "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ) @@ -168,7 +167,7 @@ func TestLLMBackedValidatorApprovalAndRejection(t *testing.T) { t.Fatalf("expected one LLM call, got %d", len(client.calls)) } call := client.calls[0] - if call.Schema != responseschema.ValidatorDecisionSetKey || call.PromptID != prompts.PromptIDValidatorSpokenFormPlausibility || call.Context.Role != "validation" || call.Context.ValidatorName != v.Name() || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") { + if call.PromptID != prompts.PromptIDValidatorSpokenFormPlausibility || call.Context.Role != "validation" || call.Context.ValidatorName != v.Name() || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") { t.Fatalf("unexpected validator call: %+v", call) } } @@ -329,7 +328,7 @@ func TestLLMBackedValidatorOversizedSingleProposalRejectsOnlyThatProposal(t *tes } } -func TestLLMBackedValidatorDiagnosticsIncludeSchemaMetadata(t *testing.T) { +func TestLLMBackedValidatorDiagnosticsOmitRegistrySchemaMetadata(t *testing.T) { client := &fakeStructuredLLMClient{responses: []LLMValidationResponse{{Validations: []LLMValidationDecision{ {CorrectionIndex: "1", Approved: true, Reason: "ok"}, }}}} @@ -349,13 +348,8 @@ func TestLLMBackedValidatorDiagnosticsIncludeSchemaMetadata(t *testing.T) { if !ok { t.Fatalf("expected metadata map, got %T", writer.lastRequestMetadata) } - schemaMap, ok := metadata["response_schema"].(map[string]any) - if !ok { - t.Fatalf("expected response_schema map, got %T", metadata["response_schema"]) - } - want := responseschema.MustLookup(responseschema.ValidatorDecisionSetKey) - if schemaMap["id"] != want.ID || schemaMap["version"] != want.Version || schemaMap["name"] != want.Name || schemaMap["sha256"] != want.SHA256 { - t.Fatalf("unexpected diagnostics schema metadata: got=%v want=%+v", schemaMap, want) + if _, exists := metadata["response_schema"]; exists { + t.Fatal("unexpected registry schema metadata") } } @@ -385,7 +379,7 @@ func TestEveryValidationTypeSelectsEmbeddedPromptAndVariables(t *testing.T) { t.Fatalf("calls=%d", len(client.calls)) } call := client.calls[0] - if call.PromptID != tc.prompt || call.Schema != responseschema.ValidatorDecisionSetKey || call.Context.Role != "validation" || call.Context.BatchIndex == nil || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") || !strings.Contains(call.Variables["TranscriptDescriptionBlock"], "Fantasy scene") { + if call.PromptID != tc.prompt || call.Context.Role != "validation" || call.Context.BatchIndex == nil || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") || !strings.Contains(call.Variables["TranscriptDescriptionBlock"], "Fantasy scene") { t.Fatalf("mapping: %+v", call) } }) diff --git a/internal/modules/glossary/module_test.go b/internal/modules/glossary/module_test.go index eaf5976..8e44b7d 100644 --- a/internal/modules/glossary/module_test.go +++ b/internal/modules/glossary/module_test.go @@ -123,7 +123,7 @@ func TestGlossaryModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T) t.Fatalf("expected one glossary:proposal call, got %+v", client.calls) } call := client.calls[0] - if call.Schema != "correction_set" || call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { + if call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { t.Fatalf("proposal mapping incomplete: %+v", call) } diff --git a/internal/modules/grammar/module_test.go b/internal/modules/grammar/module_test.go index abb108f..fd4451b 100644 --- a/internal/modules/grammar/module_test.go +++ b/internal/modules/grammar/module_test.go @@ -133,7 +133,7 @@ func TestGrammarModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T) { t.Fatalf("expected one grammar:proposal call, got %+v", client.calls) } call := client.calls[0] - if call.Schema != "correction_set" || call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { + if call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { t.Fatalf("proposal mapping incomplete: %+v", call) } diff --git a/internal/modules/homophones/module_test.go b/internal/modules/homophones/module_test.go index c452fdd..9ffae0b 100644 --- a/internal/modules/homophones/module_test.go +++ b/internal/modules/homophones/module_test.go @@ -124,7 +124,7 @@ func TestHomophonesModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T t.Fatalf("expected one homophones:proposal call, got %+v", client.calls) } call := client.calls[0] - if call.Schema != "correction_set" || call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { + if call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { t.Fatalf("proposal mapping incomplete: %+v", call) } diff --git a/internal/modules/spoken_word/module_test.go b/internal/modules/spoken_word/module_test.go index afba56a..72bf02e 100644 --- a/internal/modules/spoken_word/module_test.go +++ b/internal/modules/spoken_word/module_test.go @@ -124,7 +124,7 @@ func TestSpokenWordModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T t.Fatalf("expected one spoken_word:proposal call, got %+v", client.calls) } call := client.calls[0] - if call.Schema != "correction_set" || call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { + if call.Context.Role != "proposal" || !strings.Contains(call.Variables["SectionJSON"], "section_index") || !strings.Contains(call.Variables["GlossaryJSON"], "Jesters") { t.Fatalf("proposal mapping incomplete: %+v", call) } diff --git a/internal/prompts/registry_test.go b/internal/prompts/registry_test.go index 99740ba..b807f39 100644 --- a/internal/prompts/registry_test.go +++ b/internal/prompts/registry_test.go @@ -1,52 +1,36 @@ -package prompts +package prompts_test import ( "context" "strings" "testing" - "gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema" + "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" + "gitea.maximumdirect.net/eric/audita/v4/internal/prompts" ck "go.maximumdirect.net/configkit" pk "go.maximumdirect.net/promptkit" + "os" + "path/filepath" ) func TestEmbeddedDefinitionsPrepareThroughPromptKit(t *testing.T) { - promptInputs, err := pk.FilesystemInputs("embedded prompts", Filesystem(), AssetRoot) - if err != nil { - t.Fatal(err) - } - endpoint := "https://example.invalid/v1" - model := "fixture-model" - sources := pk.ConfigurationSources{ - Underlays: []ck.Underlay{ - {Inputs: promptInputs}, - {Inputs: []ck.Input{{Source: pk.ProfileSource("registry fixture profile", []pk.ProfileConfig{ - {ID: "fixture", Endpoint: &endpoint, Model: &model}, - })}}}, - }, - } - engine, err := pk.NewEngine(pk.Config{Sources: sources}, - pk.WithSchemaFS(responseschema.Filesystem(), responseschema.AssetRoot), - ) - if err != nil { - t.Fatal(err) - } + engine := fixtureEngine(t) vars := map[string]string{ - "HardeningPolicy": HardeningText(), + "HardeningPolicy": prompts.HardeningText(), "TranscriptDescriptionBlock": "Transcript description:\nfixture-description\n\n", "GlossaryJSON": "{\"name\":\"fixture-glossary\"}", "SectionJSON": "{\"text\":\"fixture-section\"}", "PayloadJSON": "[{\"text\":\"fixture-correction\"}]", } - vars = WithSharedVariables(vars) + vars = prompts.WithSharedVariables(vars) for _, tc := range []struct{ id, schema, payload string }{ - {PromptIDModuleGlossaryProposal, "correction_set.v1.json", "fixture-section"}, - {PromptIDModuleHomophonesProposal, "correction_set.v1.json", "fixture-section"}, - {PromptIDModuleSpokenWordProposal, "correction_set.v1.json", "fixture-section"}, - {PromptIDModuleGrammarProposal, "correction_set.v1.json", "fixture-section"}, - {PromptIDValidatorSpokenFormPlausibility, "validator_decision_set.v1.json", "fixture-correction"}, - {PromptIDValidatorMeaningReversalReview, "validator_decision_set.v1.json", "fixture-correction"}, - {PromptIDValidatorEditorialReview, "validator_decision_set.v1.json", "fixture-correction"}, + {prompts.PromptIDModuleGlossaryProposal, "correction_set.v1.json", "fixture-section"}, + {prompts.PromptIDModuleHomophonesProposal, "correction_set.v1.json", "fixture-section"}, + {prompts.PromptIDModuleSpokenWordProposal, "correction_set.v1.json", "fixture-section"}, + {prompts.PromptIDModuleGrammarProposal, "correction_set.v1.json", "fixture-section"}, + {prompts.PromptIDValidatorSpokenFormPlausibility, "validator_decision_set.v1.json", "fixture-correction"}, + {prompts.PromptIDValidatorMeaningReversalReview, "validator_decision_set.v1.json", "fixture-correction"}, + {prompts.PromptIDValidatorEditorialReview, "validator_decision_set.v1.json", "fixture-correction"}, } { t.Run(tc.id, func(t *testing.T) { prepared, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: tc.id, ProfileID: "fixture", Vars: vars}) @@ -56,6 +40,13 @@ func TestEmbeddedDefinitionsPrepareThroughPromptKit(t *testing.T) { if prepared.PromptID != tc.id || prepared.OutputContract.SchemaPath != tc.schema || prepared.StructuredOutput == nil { t.Fatalf("selection/schema: %+v", prepared) } + inspection, err := engine.InspectPrompt(context.Background(), tc.id) + if err != nil { + t.Fatal(err) + } + if prepared.OutputContract.RepairAttempts != inspection.OutputContract.RepairAttempts { + t.Fatalf("prepared budget = %d, inspected budget = %d", prepared.OutputContract.RepairAttempts, inspection.OutputContract.RepairAttempts) + } if len(prepared.Messages) != 2 { t.Fatalf("message count: %d", len(prepared.Messages)) } @@ -68,7 +59,7 @@ func TestEmbeddedDefinitionsPrepareThroughPromptKit(t *testing.T) { if strings.HasPrefix(tc.id, "audita/modules.") && !strings.Contains(rendered, "fixture-glossary") { t.Error("missing glossary context") } - missing := map[string]string{"HardeningPolicy": HardeningText()} + missing := map[string]string{"HardeningPolicy": prompts.HardeningText()} if _, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: tc.id, ProfileID: "fixture", Vars: missing}); err == nil { t.Error("missing variables accepted") } @@ -86,32 +77,24 @@ func TestRegistryMetadataIdentifiesRequiredPrompts(t *testing.T) { "audita/validators.spoken_form_plausibility", } for _, id := range required { - metadata, ok := LookupMetadata(id) - if !ok || metadata.PromptID != id || metadata.PromptSource != SourceBuiltin || - metadata.EmbeddedPath != AssetRoot+"/"+strings.TrimPrefix(id, "audita/")+".yaml" { + metadata, ok := prompts.LookupMetadata(id) + if !ok || metadata.PromptID != id || metadata.PromptSource != prompts.SourceBuiltin || + metadata.EmbeddedPath != prompts.AssetRoot+"/"+strings.TrimPrefix(id, "audita/")+".yaml" { t.Fatalf("required prompt metadata for %q: %+v", id, metadata) } } - all := RegisteredMetadata() + all := prompts.RegisteredMetadata() all[0].PromptID = "changed" - if again := RegisteredMetadata(); again[0].PromptID == "changed" { + if again := prompts.RegisteredMetadata(); again[0].PromptID == "changed" { t.Fatal("metadata enumeration shares mutable state") } } func TestRepairDefinitionsPrepareThroughPromptKit(t *testing.T) { - inputs, err := pk.FilesystemInputs("embedded prompts", Filesystem(), AssetRoot) - if err != nil { - t.Fatal(err) - } - endpoint, model := "https://example.invalid/v1", "fixture" - engine, err := pk.NewEngine(pk.Config{Sources: pk.ConfigurationSources{Underlays: []ck.Underlay{{Inputs: inputs}, {Inputs: []ck.Input{{Source: pk.ProfileSource("fixture", []pk.ProfileConfig{{ID: "fixture", Endpoint: &endpoint, Model: &model}})}}}}}}, pk.WithSchemaFS(responseschema.Filesystem(), responseschema.AssetRoot)) - if err != nil { - t.Fatal(err) - } - for _, id := range []string{PromptIDModuleGlossaryRepair, PromptIDModuleHomophonesRepair, PromptIDModuleSpokenWordRepair, PromptIDModuleGrammarRepair} { + engine := fixtureEngine(t) + for _, id := range []string{prompts.PromptIDModuleGlossaryRepair, prompts.PromptIDModuleHomophonesRepair, prompts.PromptIDModuleSpokenWordRepair, prompts.PromptIDModuleGrammarRepair} { t.Run(id, func(t *testing.T) { - prepared, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: id, ProfileID: "fixture", Vars: WithSharedVariables(map[string]string{"RepairRequestJSON": `{"proposal_ref":2,"correction":{"id":1,"original_text":" ","corrected_text":""},"findings":[{"validator":"shape","reason":"example"}]}`})}) + prepared, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: id, ProfileID: "fixture", Vars: prompts.WithSharedVariables(map[string]string{"RepairRequestJSON": `{"proposal_ref":2,"correction":{"id":1,"original_text":" ","corrected_text":""},"findings":[{"validator":"shape","reason":"example"}]}`})}) if err != nil { t.Fatal(err) } @@ -126,3 +109,21 @@ func TestRepairDefinitionsPrepareThroughPromptKit(t *testing.T) { }) } } + +func fixtureEngine(t *testing.T) *pk.Engine { + t.Helper() + dir := t.TempDir() + main := filepath.Join(dir, "config.yml") + if err := os.WriteFile(main, []byte("version: 3\npromptkit:\n profiles:\n - id: fixture\n endpoint: https://example.invalid/v1\n model: fixture-model\n"), 0600); err != nil { + t.Fatal(err) + } + loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "") + if err != nil { + t.Fatal(err) + } + engine, err := pk.NewFromConfig(loaded, pk.RuntimeConfig{}) + if err != nil { + t.Fatal(err) + } + return engine +}