Use prompt-defined structured output contracts

This commit is contained in:
2026-11-23 04:32:15 +00:00
parent 9977cd9130
commit 6ca5f89356
31 changed files with 299 additions and 445 deletions

View File

@@ -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 adapter, conversation, proposal, validator, runner, and config fixtures at their
existing ownership boundaries. 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 ## Stage 5: Retain Native Execution Evidence in the Collector
**Outcome:** Execution collection carries Audita attribution around native facts, **Outcome:** Execution collection carries Audita attribution around native facts,

View File

@@ -10,7 +10,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/outputschema" "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/reporting"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "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/preflight"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
"go.maximumdirect.net/ckconfig" "go.maximumdirect.net/ckconfig"

View File

@@ -243,3 +243,64 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
t.Fatalf("result=%+v errors=%+v", result.Transcript, result.Snapshot.Errors) 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)
}
}

View File

@@ -50,7 +50,6 @@ type LLM struct {
CorrectionRepairProfile *string `yaml:"correction_repair_profile"` CorrectionRepairProfile *string `yaml:"correction_repair_profile"`
CorrectionRepairAttempts int `yaml:"correction_repair_attempts"` CorrectionRepairAttempts int `yaml:"correction_repair_attempts"`
TransientRetries int `yaml:"transient_retries"` TransientRetries int `yaml:"transient_retries"`
RepairAttempts int `yaml:"repair_attempts"`
OperationTimeout time.Duration `yaml:"operation_timeout"` OperationTimeout time.Duration `yaml:"operation_timeout"`
} }
type Pipeline struct { type Pipeline struct {
@@ -96,7 +95,7 @@ type Reporting struct {
func defaults() Config { func defaults() Config {
return Config{ return Config{
Version: 3, 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"}}}, Pipeline: Pipeline{Stages: []Stage{{Module: "glossary"}, {Module: "homophones"}, {Module: "glossary"}, {Module: "spoken_word"}, {Module: "grammar"}}},
Output: Output{Schema: "bare-segments"}, Output: Output{Schema: "bare-segments"},
Validation: Validation{MaxPromptTokens: DefaultValidationMaxPromptTokens}, 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) { func validateRuntimeSettings(check func(bool, ck.Path, string), base ck.Path, settings LLM, validation Validation, context Context) {
llm := base.Key("llm") llm := base.Key("llm")
check(settings.TransientRetries >= 0, llm.Key("transient_retries"), "retry budget must be non-negative") 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.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.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") check(settings.OperationTimeout > 0, llm.Key("operation_timeout"), "operation timeout must be positive")

View File

@@ -51,7 +51,8 @@ func TestSchemaConstraintsAndExplicitValues(t *testing.T) {
{"unknown module", "pipeline:\n stages:\n - module: unknown\n", false}, {"unknown module", "pipeline:\n stages:\n - module: unknown\n", false},
{"invalid chunk limit", "chunking:\n target_sections: 0\n", false}, {"invalid chunk limit", "chunking:\n target_sections: 0\n", false},
{"null group", "llm: null\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) { t.Run(tc.name, func(t *testing.T) {
if err := os.WriteFile(path, []byte(tc.text), 0644); err != nil { if err := os.WriteFile(path, []byte(tc.text), 0644); err != nil {

View File

@@ -63,7 +63,6 @@ func resolveSettings(c *Config, r *ck.Resolution) error {
proposal := llm.Key("proposal_profile") 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, 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("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("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, 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")) 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"))

View File

@@ -27,7 +27,6 @@ func TestResolutionCopiesRootOverridesAndHonorsClears(t *testing.T) {
glossaries: [party] glossaries: [party]
llm: llm:
proposal_profile: A proposal_profile: A
repair_attempts: 2
context: context:
description: root description: root
pipeline: pipeline:
@@ -36,7 +35,6 @@ pipeline:
glossaries: [party] glossaries: [party]
llm: llm:
proposal_profile: B proposal_profile: B
repair_attempts: 0
context: context:
description: "" description: ""
- module: grammar - 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 { 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) 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) t.Fatalf("clears lost: %+v", cfg.Pipeline.Stages)
} }
if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" { if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" {

View File

@@ -10,7 +10,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "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/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/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit" 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 { if err := validateOutputTarget(out); err != nil {
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "invalid structured output target", Cause: err}) 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{ call.request = pk.RunRequest{
PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables), PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables),
CaptureExchange: req.CaptureExchange, CaptureExchange: req.CaptureExchange,
TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout, TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout,
Validation: contract,
Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) { Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) {
if event.Kind == pk.ExecutionFinished { if event.Kind == pk.ExecutionFinished {
mu.Lock() 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 { if decodeErr := json.Unmarshal([]byte(result.RawOutput), out); decodeErr != nil {
var typeError *json.UnmarshalTypeError 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.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} 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) 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 // classifiedFailure deliberately checks setup defects before broad PromptKit
// validation/generation wrappers. Provider text is kept only in the typed cause. // validation/generation wrappers. Provider text is kept only in the typed cause.
func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure { func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure {

View File

@@ -13,7 +13,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
) )
@@ -63,7 +62,7 @@ func TestRolesShareBackendCapacityAndReleaseAfterCancellation(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
request := adapterRequest(responseschema.CorrectionSetKey) request := adapterRequest("proposal")
done := make(chan error, 1) done := make(chan error, 1)
go func() { go func() {
_, err := proposal.CompleteStructured(context.Background(), request, &map[string]any{}) _, err := proposal.CompleteStructured(context.Background(), request, &map[string]any{})
@@ -113,7 +112,7 @@ func TestDistinctBackendsHaveIndependentCapacity(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
request := adapterRequest(responseschema.CorrectionSetKey) request := adapterRequest("proposal")
done := make(chan error, 2) done := make(chan error, 2)
go func() { go func() {
_, err := first.CompleteStructured(context.Background(), request, &map[string]any{}) _, err := first.CompleteStructured(context.Background(), request, &map[string]any{})

View File

@@ -6,6 +6,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -18,7 +19,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "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/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/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
@@ -85,6 +85,25 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
t.Fatal(err) 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"))}, "") loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -115,7 +134,7 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
if err != nil { if err != nil {
t.Fatal(err) 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 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) 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 id := prompts.PromptIDModuleGlossaryProposal
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"} vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
if schema == responseschema.ValidatorDecisionSetKey { if schema == "validation" {
id = prompts.PromptIDValidatorEditorialReview id = prompts.PromptIDValidatorEditorialReview
vars = map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"} 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) { func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
for _, schema := range []responseschema.Key{responseschema.CorrectionSetKey, responseschema.ValidatorDecisionSetKey} { for _, schema := range []string{"proposal", "validation"} {
valid := `{"corrections":[]}` valid := `{"corrections":[]}`
if schema == responseschema.ValidatorDecisionSetKey { if schema == "validation" {
valid = `{"validations":[]}` valid = `{"validations":[]}`
} }
for _, tc := range []struct { for _, tc := range []struct {
@@ -161,7 +180,7 @@ func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
t.Run(string(schema)+"/"+tc.name, func(t *testing.T) { t.Run(string(schema)+"/"+tc.name, func(t *testing.T) {
runtime, count, _ := adapterFixture(t, tc.replies, tc.retries, tc.repairs, nil) runtime, count, _ := adapterFixture(t, tc.replies, tc.retries, tc.repairs, nil)
role := "proposal" role := "proposal"
if schema == responseschema.ValidatorDecisionSetKey { if schema == "validation" {
role = "validation" role = "validation"
} }
var events []pk.ExecutionEvent var events []pk.ExecutionEvent
@@ -251,7 +270,7 @@ func TestCorrectionSchemaReplacementValuesThroughAdapter(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
var out map[string]any 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 { if got := count.Load(); got != 1 {
t.Fatalf("expected one provider generation, got %d", got) t.Fatalf("expected one provider generation, got %d", got)
} }
@@ -296,7 +315,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.Variables["HardeningPolicy"] = "attacker-controlled" req.Variables["HardeningPolicy"] = "attacker-controlled"
var out map[string]any var out map[string]any
response, err := client.CompleteStructured(context.Background(), req, &out) 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 { cases := []struct {
name string name string
system string system string
@@ -343,8 +362,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
name: "operator text without shared references", name: "operator text without shared references",
system: "Operator system instructions.", system: "Operator system instructions.",
user: "Operator request without variables.", user: "Operator request without variables.",
replies: []reply{{200, `{"wrong":true}`}, {200, `{"corrections":[]}`}}, replies: []reply{{200, `{"wrong":true}`}},
repairs: 1,
wantSystem: "Operator system instructions.", wantSystem: "Operator system instructions.",
wantUser: "Operator request without variables.", wantUser: "Operator request without variables.",
}, },
@@ -376,7 +394,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
if tc.name == "operator text with shared references" { if tc.name == "operator text with shared references" {
req.Variables["HardeningPolicy"] = "attacker-controlled" req.Variables["HardeningPolicy"] = "attacker-controlled"
} }
@@ -416,7 +434,7 @@ func TestPreparedAdapterRejectsTargetDriftAndPreparationErrors(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.PromptID = "missing.prompt" req.PromptID = "missing.prompt"
var out map[string]any var out map[string]any
if _, err := client.CompleteStructured(context.Background(), req, &out); err == nil || count.Load() != 0 { 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) t.Fatal(err)
} }
var out map[string]any 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 { if !errors.Is(err, context.Canceled) || count.Load() != 1 {
t.Fatalf("cancellation: %v, HTTP calls=%d", err, count.Load()) t.Fatalf("cancellation: %v, HTTP calls=%d", err, count.Load())
} }
@@ -453,7 +471,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t
t.Fatal(err) t.Fatal(err)
} }
var output map[string]any 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 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 { 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) 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()) parent, cancel := context.WithCancel(context.Background())
cancel() 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 { 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) t.Fatalf("parent cancellation: failure=%#v counts=%+v", failure, response.Execution)
} }
@@ -488,7 +506,7 @@ func TestPreparedAdapterDistinguishesAttemptTimeoutFromParentDeadline(t *testing
defer cancel() defer cancel()
before := count.Load() before := count.Load()
var output map[string]any 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 var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != tc.class || failure.Reason != tc.reason || if !errors.As(err, &failure) || failure.Class != tc.class || failure.Reason != tc.reason ||
!errors.Is(err, context.DeadlineExceeded) || errors.Is(err, pk.ErrOperationTimeout) || !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, pk.ErrOperationTimeout) ||
@@ -510,7 +528,7 @@ func TestPreparedAdapterMissingCredentialRetainsSetupCause(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
var output map[string]any 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 var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure || if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure ||
!errors.Is(err, pk.ErrAPIKeyEnvMissing) || !strings.Contains(err.Error(), "ADAPTER_KEY") || !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"` CorrectionIndex int `json:"correction_index"`
} `json:"validations"` } `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 var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || !response.Execution.Available { 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) 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 { if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
t.Fatalf("invalid target: %#v", failure) t.Fatalf("invalid target: %#v", failure)
} }
req := adapterRequest("missing_schema") req := adapterRequest("validation")
_, 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.PromptID = "missing.prompt" req.PromptID = "missing.prompt"
_, err = client.CompleteStructured(context.Background(), req, &output) _, err = client.CompleteStructured(context.Background(), req, &output)
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure { 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) t.Fatal(err)
} }
var output map[string]any 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 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 { 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) 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) 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())
}
})
}
}

View File

@@ -16,7 +16,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "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/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
@@ -71,7 +70,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"} 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 { if err != nil || initial.Exchange == nil {
t.Fatalf("capture: %+v %v", initial, err) t.Fatalf("capture: %+v %v", initial, err)
} }
@@ -87,7 +86,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
if turns == 2 { if turns == 2 {
return nil, nil 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 { if err != nil || exhausted || turns != 2 {
t.Fatalf("coordinated dialogue: turns=%d exhausted=%v error=%v", turns, exhausted, err) 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 { if turn.Response != nil {
return nil, turn.Err 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) _, 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") { 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 { if err != nil {
t.Fatal(err) 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 { if err != nil {
t.Fatal(err) 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -173,7 +172,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
result = turn.Response result = turn.Response
return nil, turn.Err 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 { if err != nil || exhausted || result == nil {
t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err) t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err)

View File

@@ -6,7 +6,6 @@ import (
"testing" "testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "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/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit" pk "go.maximumdirect.net/promptkit"
@@ -31,7 +30,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.CaptureExchange = true req.CaptureExchange = true
base, err := client.CompleteStructured(context.Background(), req, &map[string]any{}) base, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil { if err != nil {
@@ -55,7 +54,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
return nil, nil 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 { 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) 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) runtime, _, _ := adapterFixture(t, []reply{{200, `{"corrections":[]}`}, {200, `{"proposal_ref":1,"decision":{"action":"withdraw","correction":null}}`}}, 0, 0, nil)
collector := NewObservationCollector() collector := NewObservationCollector()
proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks()) proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.CaptureExchange = true req.CaptureExchange = true
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{}) base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil { if err != nil {
@@ -102,7 +101,7 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) {
} }
return nil, turn.Err 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 { if !errors.Is(err, context.Canceled) || deliveries != 1 {
t.Fatalf("deliveries=%d err=%v", deliveries, err) 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()) proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
repair, _ := runtime.NewRoleClient("repair", "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()) validation, _ := runtime.NewRoleClient("validation", "base", runtime.Config.LLM, collector.Hooks())
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.CaptureExchange = true req.CaptureExchange = true
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{}) base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil { if err != nil {
@@ -129,13 +128,43 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) {
if turn.Err != nil { if turn.Err != nil {
return nil, turn.Err 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 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()) summary := Summarize(collector.Snapshot())
if err != nil || count.Load() != 3 || summary.ProviderAttempts != 3 || summary.LogicalCalls != 3 || !summary.TerminalCoverageComplete { 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) 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())
}
}

View File

@@ -6,6 +6,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"net/http" "net/http"
"os" "os"
"path/filepath" "path/filepath"
@@ -16,7 +17,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "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/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/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
@@ -58,7 +58,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
var out map[string]any 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 { if err == nil || calls != 1 {
t.Fatalf("error = %v, calls = %d", err, calls) t.Fatalf("error = %v, calls = %d", err, calls)
} }
@@ -78,7 +78,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) 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 { for _, tc := range []struct {
name string name string
repair int repair int
@@ -91,6 +91,22 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
{"no repair", 0, []string{`{"wrong":true}`}, 1, false}, {"no repair", 0, []string{`{"wrong":true}`}, 1, false},
} { } {
t.Run(tc.name, func(t *testing.T) { 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 calls := 0
httpClient := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) { httpClient := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
item := tc.outputs[min(calls, len(tc.outputs)-1)] 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) 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 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 { if err != nil {
t.Fatal(err) 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 { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -176,7 +192,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) 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) done := make(chan error, 1)
go func() { go func() {
_, err := first.CompleteStructured(context.Background(), request, &map[string]any{}) _, err := first.CompleteStructured(context.Background(), request, &map[string]any{})
@@ -222,7 +238,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) 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{}) response, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil || calls != 2 || response.Execution.TransientRetries != 1 { if err != nil || calls != 2 || response.Execution.TransientRetries != 1 {
t.Fatalf("error=%v calls=%d execution=%+v", err, calls, response.Execution) t.Fatalf("error=%v calls=%d execution=%+v", err, calls, response.Execution)
@@ -256,7 +272,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) 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", ""}} { 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) { t.Run(tc.profile, func(t *testing.T) {
client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{}) client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{})

View File

@@ -9,7 +9,6 @@ import (
"testing" "testing"
"time" "time"
"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/structuredoutput"
pk "go.maximumdirect.net/promptkit" pk "go.maximumdirect.net/promptkit"
) )
@@ -98,7 +97,7 @@ func TestRoleClientFeedsCollectorAcrossPreparationFailure(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
request := adapterRequest(responseschema.CorrectionSetKey) request := adapterRequest("proposal")
request.Context.ModuleInstance = "glossary_1" request.Context.ModuleInstance = "glossary_1"
index := 3 index := 3
request.Context.SectionIndex = &index request.Context.SectionIndex = &index

View File

@@ -56,7 +56,7 @@ func TestRepairedProposalStillFacesDomainChecks(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
settings := loaded.Config.Application.LLM settings := loaded.Config.Application.LLM
settings.TransientRetries, settings.RepairAttempts = 0, 1 settings.TransientRetries = 0
client, err := runtime.NewRoleClient("proposal", "base", settings, llm.CallHooks{}) client, err := runtime.NewRoleClient("proposal", "base", settings, llm.CallHooks{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@@ -13,7 +13,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" "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/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "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/stagename"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "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, CaptureExchange: req.CaptureExchange,
CaptureDiagnostics: req.Interactions != nil, CaptureDiagnostics: req.Interactions != nil,
PromptID: req.PromptID, PromptID: req.PromptID,
Variables: req.Variables, Schema: responseschema.CorrectionSetKey, Variables: req.Variables,
Context: coordinates, Context: coordinates,
}, &response) }, &response)
sectionIndex := 0 sectionIndex := 0
if req.Section != nil { if req.Section != nil {
@@ -113,7 +112,6 @@ func GenerateCandidates(ctx context.Context, req Request) (Result, error) {
"segment_ids": segmentIDs(req.WorkingTranscript), "segment_ids": segmentIDs(req.WorkingTranscript),
"prompt": completion.Prompt, "prompt": completion.Prompt,
} }
requestMetadata["response_schema"] = responseschema.MustLookup(responseschema.CorrectionSetKey).DiagnosticsMap()
artifacts, _ = req.Interactions.WriteInteraction(structuredoutput.Interaction{ artifacts, _ = req.Interactions.WriteInteraction(structuredoutput.Interaction{
Name: stage, Context: coordinates, RequestMetadata: requestMetadata, RequestPayload: completion.Prepared, Name: stage, Context: coordinates, RequestMetadata: requestMetadata, RequestPayload: completion.Prepared,
ResponsePayload: map[string]any{"decoded": response, "final_content": completion.FinalContent, "model": completion.Model}, ResponsePayload: map[string]any{"decoded": response, "final_content": completion.FinalContent, "model": completion.Model},

View File

@@ -14,7 +14,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "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/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "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/structuredoutput"
) )
@@ -122,12 +121,12 @@ func TestGenerateCandidatesUsesCorrectionSetSchema(t *testing.T) {
t.Fatalf("expected 1 LLM call, got %d", len(client.calls)) t.Fatalf("expected 1 LLM call, got %d", len(client.calls))
} }
call := client.calls[0] 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) t.Fatalf("unexpected call contract: %+v", call)
} }
} }
func TestGenerateCandidatesDiagnosticsIncludeSchemaMetadata(t *testing.T) { func TestGenerateCandidatesDiagnosticsOmitRegistrySchemaMetadata(t *testing.T) {
client := &fakeStructuredClient{ client := &fakeStructuredClient{
responses: []StructuredCorrectionSet{ responses: []StructuredCorrectionSet{
{Corrections: []StructuredCorrectionProposal{{SegmentReference: 1, OriginalText: "teh", CorrectedText: "the"}}}, {Corrections: []StructuredCorrectionProposal{{SegmentReference: 1, OriginalText: "teh", CorrectedText: "the"}}},
@@ -146,13 +145,8 @@ func TestGenerateCandidatesDiagnosticsIncludeSchemaMetadata(t *testing.T) {
if !ok { if !ok {
t.Fatalf("expected request metadata map, got %T", diag.lastRequestMetadata) t.Fatalf("expected request metadata map, got %T", diag.lastRequestMetadata)
} }
schemaMap, ok := metadata["response_schema"].(map[string]any) if _, exists := metadata["response_schema"]; exists {
if !ok { t.Fatal("unexpected registry schema metadata")
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)
} }
} }
@@ -293,13 +287,8 @@ func TestGenerateCandidatesDiagnosticsWritten(t *testing.T) {
if start, ok := metadata["start_index"].(float64); !ok || start != 0 { if start, ok := metadata["start_index"].(float64); !ok || start != 0 {
t.Fatalf("missing response-local origin: %s", raw) t.Fatalf("missing response-local origin: %s", raw)
} }
schemaMap, ok := metadata["response_schema"].(map[string]any) if _, exists := metadata["response_schema"]; exists {
if !ok { t.Fatal("unexpected registry schema metadata")
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)
} }
var coordinates struct { var coordinates struct {
Context structuredoutput.DiagnosticContext `json:"context"` Context structuredoutput.DiagnosticContext `json:"context"`

View File

@@ -1,154 +1,14 @@
package responseschema package responseschema
import ( import (
"crypto/sha256"
"embed" "embed"
"encoding/hex"
"encoding/json"
"fmt"
"io/fs" "io/fs"
"sort"
"strings"
) )
// Key identifies one structured response schema used by Audita. const AssetRoot = "assets"
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"
)
//go:embed assets/*.json //go:embed assets/*.json
var schemaAssets embed.FS 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 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[:]),
}
}

View File

@@ -1,129 +1,20 @@
package responseschema package responseschema
import ( import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json" "encoding/json"
"io" "io/fs"
"testing" "testing"
jsonschema "github.com/santhosh-tekuri/jsonschema/v6" 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) { func TestCorrectionRepairSchema(t *testing.T) {
var document any 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) t.Fatal(err)
} }
compiler := jsonschema.NewCompiler() compiler := jsonschema.NewCompiler()

View File

@@ -18,7 +18,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "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/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "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/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
@@ -101,8 +100,7 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) {
var out map[string]any var out map[string]any
_, err := client.CompleteStructured(ctx, structuredoutput.Request{ _, err := client.CompleteStructured(ctx, structuredoutput.Request{
PromptID: prompts.PromptIDValidatorEditorialReview, PromptID: prompts.PromptIDValidatorEditorialReview,
Variables: map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}, Schema: responseschema.ValidatorDecisionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}, Context: structuredoutput.DiagnosticContext{ModuleKey: req.ModuleKey, ModuleInstance: req.ModuleInstance, SectionIndex: req.SectionIndex},
Context: structuredoutput.DiagnosticContext{ModuleKey: req.ModuleKey, ModuleInstance: req.ModuleInstance, SectionIndex: req.SectionIndex},
}, &out) }, &out)
return validators.Result{}, err return validators.Result{}, err
}} }}

View File

@@ -10,7 +10,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "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/proposal_generation"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "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/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators" "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 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) { 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 { if turn.Response == nil {

View File

@@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm" "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" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
"io" "io"
@@ -514,7 +513,7 @@ func (c *repairClient) Coordinate(ctx context.Context, _ *structuredoutput.Excha
t.Fatal(err) t.Fatal(err)
} }
var output map[string]any 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 { if err != nil {
return false, err return false, err
} }

View File

@@ -6,7 +6,6 @@ import (
"time" "time"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "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. // DiagnosticContext identifies the logical call without examining rendered text.
@@ -23,15 +22,14 @@ type DiagnosticContext struct {
RepairAttempt *int `json:"repair_attempt,omitempty"` 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. // credentials are supplied by the role-bound runtime client.
type Request struct { type Request struct {
PromptID string `json:"prompt_id"` PromptID string `json:"prompt_id"`
Variables map[string]string `json:"variables"` Variables map[string]string `json:"variables"`
Schema responseschema.Key `json:"schema"` Context DiagnosticContext `json:"context"`
Context DiagnosticContext `json:"context"` CaptureExchange bool `json:"-"`
CaptureExchange bool `json:"-"` CaptureDiagnostics bool `json:"-"`
CaptureDiagnostics bool `json:"-"`
} }
// PromptMetadata is the execution snapshot returned by the runtime when available. // PromptMetadata is the execution snapshot returned by the runtime when available.

View File

@@ -93,7 +93,7 @@ func testValidationClient(t *testing.T, transport http.RoundTripper) structuredo
t.Fatal(err) t.Fatal(err)
} }
settings := loaded.Config.Application.LLM settings := loaded.Config.Application.LLM
settings.TransientRetries, settings.RepairAttempts = 0, 1 settings.TransientRetries = 0
client, err := runtime.NewRoleClient("validation", "base", settings, llm.CallHooks{}) client, err := runtime.NewRoleClient("validation", "base", settings, llm.CallHooks{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@@ -12,7 +12,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config" "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/core/jsonnumber"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "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/stagename"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "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} 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{ completion, err = req.LLMClient.CompleteStructured(ctx, StructuredCompletionRequest{
PromptID: promptMetadata.PromptID, PromptID: promptMetadata.PromptID,
Variables: variables, Schema: responseschema.ValidatorDecisionSetKey, Variables: variables,
Context: coordinates, CaptureDiagnostics: req.Interactions != nil, Context: coordinates, CaptureDiagnostics: req.Interactions != nil,
}, &response) }, &response)
batchIndex := batch.BatchIndex batchIndex := batch.BatchIndex
operation := outcomes.Operation{ operation := outcomes.Operation{
@@ -153,7 +152,6 @@ func (v *LLMBackedValidator) Validate(ctx context.Context, req Request) (Result,
if coordinates.ProposalIndex != nil && req.RepairAttempt != nil { if coordinates.ProposalIndex != nil && req.RepairAttempt != nil {
stageInstance = fmt.Sprintf("%s:proposal-%04d:attempt-%04d", stageInstance, *coordinates.ProposalIndex, *req.RepairAttempt) 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} responsePayload := map[string]any{"decoded": response, "final_content": completion.FinalContent, "model": completion.Model}
if reconciled != nil { if reconciled != nil {
view := *reconciled 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, "stage_index": req.StageIndex, "stage_id": req.StageID, "module_key": req.ModuleKey,
"validator_name": v.name, "validator_type": v.validatorType, "batch_index": batch.BatchIndex, "validator_name": v.name, "validator_type": v.validatorType, "batch_index": batch.BatchIndex,
"proposal_indices": indices, "repair_proposal_index": coordinates.ProposalIndex, "repair_attempt": req.RepairAttempt, "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), RequestPayload: completion.Prepared, ResponsePayload: responsePayload, ErrorPayload: errPayload(callErr),
} }

View File

@@ -14,7 +14,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "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/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "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/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "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)) t.Fatalf("expected one LLM call, got %d", len(client.calls))
} }
call := client.calls[0] 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) 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{ client := &fakeStructuredLLMClient{responses: []LLMValidationResponse{{Validations: []LLMValidationDecision{
{CorrectionIndex: "1", Approved: true, Reason: "ok"}, {CorrectionIndex: "1", Approved: true, Reason: "ok"},
}}}} }}}}
@@ -349,13 +348,8 @@ func TestLLMBackedValidatorDiagnosticsIncludeSchemaMetadata(t *testing.T) {
if !ok { if !ok {
t.Fatalf("expected metadata map, got %T", writer.lastRequestMetadata) t.Fatalf("expected metadata map, got %T", writer.lastRequestMetadata)
} }
schemaMap, ok := metadata["response_schema"].(map[string]any) if _, exists := metadata["response_schema"]; exists {
if !ok { t.Fatal("unexpected registry schema metadata")
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)
} }
} }
@@ -385,7 +379,7 @@ func TestEveryValidationTypeSelectsEmbeddedPromptAndVariables(t *testing.T) {
t.Fatalf("calls=%d", len(client.calls)) t.Fatalf("calls=%d", len(client.calls))
} }
call := client.calls[0] 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) t.Fatalf("mapping: %+v", call)
} }
}) })

View File

@@ -123,7 +123,7 @@ func TestGlossaryModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T)
t.Fatalf("expected one glossary:proposal call, got %+v", client.calls) t.Fatalf("expected one glossary:proposal call, got %+v", client.calls)
} }
call := client.calls[0] 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) t.Fatalf("proposal mapping incomplete: %+v", call)
} }

View File

@@ -133,7 +133,7 @@ func TestGrammarModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T) {
t.Fatalf("expected one grammar:proposal call, got %+v", client.calls) t.Fatalf("expected one grammar:proposal call, got %+v", client.calls)
} }
call := client.calls[0] 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) t.Fatalf("proposal mapping incomplete: %+v", call)
} }

View File

@@ -124,7 +124,7 @@ func TestHomophonesModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T
t.Fatalf("expected one homophones:proposal call, got %+v", client.calls) t.Fatalf("expected one homophones:proposal call, got %+v", client.calls)
} }
call := client.calls[0] 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) t.Fatalf("proposal mapping incomplete: %+v", call)
} }

View File

@@ -124,7 +124,7 @@ func TestSpokenWordModuleProposeMapsCorrectionsAndWritesDiagnostics(t *testing.T
t.Fatalf("expected one spoken_word:proposal call, got %+v", client.calls) t.Fatalf("expected one spoken_word:proposal call, got %+v", client.calls)
} }
call := client.calls[0] 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) t.Fatalf("proposal mapping incomplete: %+v", call)
} }

View File

@@ -1,52 +1,36 @@
package prompts package prompts_test
import ( import (
"context" "context"
"strings" "strings"
"testing" "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" ck "go.maximumdirect.net/configkit"
pk "go.maximumdirect.net/promptkit" pk "go.maximumdirect.net/promptkit"
"os"
"path/filepath"
) )
func TestEmbeddedDefinitionsPrepareThroughPromptKit(t *testing.T) { func TestEmbeddedDefinitionsPrepareThroughPromptKit(t *testing.T) {
promptInputs, err := pk.FilesystemInputs("embedded prompts", Filesystem(), AssetRoot) engine := fixtureEngine(t)
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)
}
vars := map[string]string{ vars := map[string]string{
"HardeningPolicy": HardeningText(), "HardeningPolicy": prompts.HardeningText(),
"TranscriptDescriptionBlock": "Transcript description:\nfixture-description\n\n", "TranscriptDescriptionBlock": "Transcript description:\nfixture-description\n\n",
"GlossaryJSON": "{\"name\":\"fixture-glossary\"}", "GlossaryJSON": "{\"name\":\"fixture-glossary\"}",
"SectionJSON": "{\"text\":\"fixture-section\"}", "SectionJSON": "{\"text\":\"fixture-section\"}",
"PayloadJSON": "[{\"text\":\"fixture-correction\"}]", "PayloadJSON": "[{\"text\":\"fixture-correction\"}]",
} }
vars = WithSharedVariables(vars) vars = prompts.WithSharedVariables(vars)
for _, tc := range []struct{ id, schema, payload string }{ for _, tc := range []struct{ id, schema, payload string }{
{PromptIDModuleGlossaryProposal, "correction_set.v1.json", "fixture-section"}, {prompts.PromptIDModuleGlossaryProposal, "correction_set.v1.json", "fixture-section"},
{PromptIDModuleHomophonesProposal, "correction_set.v1.json", "fixture-section"}, {prompts.PromptIDModuleHomophonesProposal, "correction_set.v1.json", "fixture-section"},
{PromptIDModuleSpokenWordProposal, "correction_set.v1.json", "fixture-section"}, {prompts.PromptIDModuleSpokenWordProposal, "correction_set.v1.json", "fixture-section"},
{PromptIDModuleGrammarProposal, "correction_set.v1.json", "fixture-section"}, {prompts.PromptIDModuleGrammarProposal, "correction_set.v1.json", "fixture-section"},
{PromptIDValidatorSpokenFormPlausibility, "validator_decision_set.v1.json", "fixture-correction"}, {prompts.PromptIDValidatorSpokenFormPlausibility, "validator_decision_set.v1.json", "fixture-correction"},
{PromptIDValidatorMeaningReversalReview, "validator_decision_set.v1.json", "fixture-correction"}, {prompts.PromptIDValidatorMeaningReversalReview, "validator_decision_set.v1.json", "fixture-correction"},
{PromptIDValidatorEditorialReview, "validator_decision_set.v1.json", "fixture-correction"}, {prompts.PromptIDValidatorEditorialReview, "validator_decision_set.v1.json", "fixture-correction"},
} { } {
t.Run(tc.id, func(t *testing.T) { t.Run(tc.id, func(t *testing.T) {
prepared, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: tc.id, ProfileID: "fixture", Vars: vars}) 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 { if prepared.PromptID != tc.id || prepared.OutputContract.SchemaPath != tc.schema || prepared.StructuredOutput == nil {
t.Fatalf("selection/schema: %+v", prepared) 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 { if len(prepared.Messages) != 2 {
t.Fatalf("message count: %d", len(prepared.Messages)) 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") { if strings.HasPrefix(tc.id, "audita/modules.") && !strings.Contains(rendered, "fixture-glossary") {
t.Error("missing glossary context") 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 { if _, err := engine.Prepare(context.Background(), pk.RunRequest{PromptID: tc.id, ProfileID: "fixture", Vars: missing}); err == nil {
t.Error("missing variables accepted") t.Error("missing variables accepted")
} }
@@ -86,32 +77,24 @@ func TestRegistryMetadataIdentifiesRequiredPrompts(t *testing.T) {
"audita/validators.spoken_form_plausibility", "audita/validators.spoken_form_plausibility",
} }
for _, id := range required { for _, id := range required {
metadata, ok := LookupMetadata(id) metadata, ok := prompts.LookupMetadata(id)
if !ok || metadata.PromptID != id || metadata.PromptSource != SourceBuiltin || if !ok || metadata.PromptID != id || metadata.PromptSource != prompts.SourceBuiltin ||
metadata.EmbeddedPath != AssetRoot+"/"+strings.TrimPrefix(id, "audita/")+".yaml" { metadata.EmbeddedPath != prompts.AssetRoot+"/"+strings.TrimPrefix(id, "audita/")+".yaml" {
t.Fatalf("required prompt metadata for %q: %+v", id, metadata) t.Fatalf("required prompt metadata for %q: %+v", id, metadata)
} }
} }
all := RegisteredMetadata() all := prompts.RegisteredMetadata()
all[0].PromptID = "changed" 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") t.Fatal("metadata enumeration shares mutable state")
} }
} }
func TestRepairDefinitionsPrepareThroughPromptKit(t *testing.T) { func TestRepairDefinitionsPrepareThroughPromptKit(t *testing.T) {
inputs, err := pk.FilesystemInputs("embedded prompts", Filesystem(), AssetRoot) engine := fixtureEngine(t)
if err != nil { for _, id := range []string{prompts.PromptIDModuleGlossaryRepair, prompts.PromptIDModuleHomophonesRepair, prompts.PromptIDModuleSpokenWordRepair, prompts.PromptIDModuleGrammarRepair} {
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} {
t.Run(id, func(t *testing.T) { 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 { if err != nil {
t.Fatal(err) 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
}