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

@@ -10,7 +10,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit"
@@ -139,15 +138,10 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
if err := validateOutputTarget(out); err != nil {
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "invalid structured output target", Cause: err})
}
contract, err := OutputContract(req.Schema, c.settings.RepairAttempts)
if err != nil {
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "unknown structured response schema", Cause: err})
}
call.request = pk.RunRequest{
PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables),
CaptureExchange: req.CaptureExchange,
TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout,
Validation: contract,
Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) {
if event.Kind == pk.ExecutionFinished {
mu.Lock()
@@ -195,7 +189,8 @@ func (c *RoleClient) finishResponse(parent context.Context, response *structured
}
if decodeErr := json.Unmarshal([]byte(result.RawOutput), out); decodeErr != nil {
var typeError *json.UnmarshalTypeError
if errors.As(decodeErr, &typeError) {
var syntaxError *json.SyntaxError
if errors.As(decodeErr, &typeError) || errors.As(decodeErr, &syntaxError) {
return &structuredoutput.Failure{Class: structuredoutput.FailureRecoverable, Reason: outcomes.ReasonInvalidOutput, Message: "structured output contains an unusable value", Cause: decodeErr}
}
return &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "validated structured output could not be decoded", Cause: decodeErr}
@@ -216,15 +211,6 @@ func (c *RoleClient) CompleteStructured(ctx context.Context, req structuredoutpu
return call.finish(result, err)
}
// OutputContract maps an Audita domain schema to the native request contract.
func OutputContract(schema responseschema.Key, repairs int) (*pk.OutputContract, error) {
path, ok := responseschema.AssetPath(schema)
if !ok {
return nil, fmt.Errorf("schema %q", schema)
}
return &pk.OutputContract{Format: pk.FormatJSON, ValidationMode: pk.ValidationJSONSchema, SchemaPath: path, RepairAttempts: repairs}, nil
}
// classifiedFailure deliberately checks setup defects before broad PromptKit
// validation/generation wrappers. Provider text is kept only in the typed cause.
func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure {

View File

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

View File

@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
@@ -18,7 +19,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit"
@@ -85,6 +85,25 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
t.Fatal(err)
}
}
// Use complete operator definitions so each fixture selects its own budget.
promptDir := filepath.Join(dir, "prompts")
if err := os.Mkdir(promptDir, 0700); err != nil {
t.Fatal(err)
}
for _, meta := range prompts.RegisteredMetadata() {
if (operatorPrompt != "" && meta.PromptID == prompts.PromptIDModuleGlossaryProposal) ||
(strings.Contains(operatorPrompt, "id: modules.grammar.repair") && meta.PromptID == prompts.PromptIDModuleGrammarRepair) {
continue
}
data, err := fs.ReadFile(prompts.Filesystem(), meta.EmbeddedPath)
if err != nil {
t.Fatal(err)
}
data = append(data, []byte(fmt.Sprintf(" repair_attempts: %d\n", repairs))...)
if err := os.WriteFile(filepath.Join(promptDir, filepath.Base(meta.EmbeddedPath)), data, 0600); err != nil {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
if err != nil {
t.Fatal(err)
@@ -115,7 +134,7 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
if err != nil {
t.Fatal(err)
}
settings := config.Config{LLM: config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries, RepairAttempts: repairs}}
settings := config.Config{LLM: config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries}}
return &testRuntime{Runtime: runtime, Config: settings}, &count, dir
}
@@ -123,20 +142,20 @@ func operatorPromptDocument(system, user string) string {
return fmt.Sprintf("collections:\n audita:\n prompts:\n - id: modules.glossary.proposal\n messages:\n - role: system\n content: %q\n - role: user\n content: %q\n output:\n format: text\n validation_mode: none\n", system, user)
}
func adapterRequest(schema responseschema.Key) structuredoutput.Request {
func adapterRequest(schema string) structuredoutput.Request {
id := prompts.PromptIDModuleGlossaryProposal
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
if schema == responseschema.ValidatorDecisionSetKey {
if schema == "validation" {
id = prompts.PromptIDValidatorEditorialReview
vars = map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}
}
return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Schema: schema, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}}
return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}}
}
func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
for _, schema := range []responseschema.Key{responseschema.CorrectionSetKey, responseschema.ValidatorDecisionSetKey} {
for _, schema := range []string{"proposal", "validation"} {
valid := `{"corrections":[]}`
if schema == responseschema.ValidatorDecisionSetKey {
if schema == "validation" {
valid = `{"validations":[]}`
}
for _, tc := range []struct {
@@ -161,7 +180,7 @@ func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
t.Run(string(schema)+"/"+tc.name, func(t *testing.T) {
runtime, count, _ := adapterFixture(t, tc.replies, tc.retries, tc.repairs, nil)
role := "proposal"
if schema == responseschema.ValidatorDecisionSetKey {
if schema == "validation" {
role = "validation"
}
var events []pk.ExecutionEvent
@@ -251,7 +270,7 @@ func TestCorrectionSchemaReplacementValuesThroughAdapter(t *testing.T) {
t.Fatal(err)
}
var out map[string]any
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &out)
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &out)
if got := count.Load(); got != 1 {
t.Fatalf("expected one provider generation, got %d", got)
}
@@ -296,7 +315,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
req.Variables["HardeningPolicy"] = "attacker-controlled"
var out map[string]any
response, err := client.CompleteStructured(context.Background(), req, &out)
@@ -329,7 +348,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
}
func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing.T) {
func TestOperatorPromptUsesOwnContractAndOptionalSharedText(t *testing.T) {
cases := []struct {
name string
system string
@@ -343,8 +362,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
name: "operator text without shared references",
system: "Operator system instructions.",
user: "Operator request without variables.",
replies: []reply{{200, `{"wrong":true}`}, {200, `{"corrections":[]}`}},
repairs: 1,
replies: []reply{{200, `{"wrong":true}`}},
wantSystem: "Operator system instructions.",
wantUser: "Operator request without variables.",
},
@@ -376,7 +394,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
if err != nil {
t.Fatal(err)
}
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
if tc.name == "operator text with shared references" {
req.Variables["HardeningPolicy"] = "attacker-controlled"
}
@@ -416,7 +434,7 @@ func TestPreparedAdapterRejectsTargetDriftAndPreparationErrors(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
req.PromptID = "missing.prompt"
var out map[string]any
if _, err := client.CompleteStructured(context.Background(), req, &out); err == nil || count.Load() != 0 {
@@ -438,7 +456,7 @@ func TestPreparedAdapterCancellationStopsRetryWait(t *testing.T) {
t.Fatal(err)
}
var out map[string]any
_, err = client.CompleteStructured(ctx, adapterRequest(responseschema.CorrectionSetKey), &out)
_, err = client.CompleteStructured(ctx, adapterRequest("proposal"), &out)
if !errors.Is(err, context.Canceled) || count.Load() != 1 {
t.Fatalf("cancellation: %v, HTTP calls=%d", err, count.Load())
}
@@ -453,7 +471,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t
t.Fatal(err)
}
var output map[string]any
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonOperationTimeout || !errors.Is(err, pk.ErrOperationTimeout) || !response.Execution.Available {
t.Fatalf("local timeout: failure=%#v counts=%+v", failure, response.Execution)
@@ -461,7 +479,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t
parent, cancel := context.WithCancel(context.Background())
cancel()
response, err = client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output)
response, err = client.CompleteStructured(parent, adapterRequest("proposal"), &output)
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureCanceled || failure.Reason != outcomes.ReasonCanceled || !errors.Is(err, context.Canceled) || response.Execution.Available {
t.Fatalf("parent cancellation: failure=%#v counts=%+v", failure, response.Execution)
}
@@ -488,7 +506,7 @@ func TestPreparedAdapterDistinguishesAttemptTimeoutFromParentDeadline(t *testing
defer cancel()
before := count.Load()
var output map[string]any
response, err := client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output)
response, err := client.CompleteStructured(parent, adapterRequest("proposal"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != tc.class || failure.Reason != tc.reason ||
!errors.Is(err, context.DeadlineExceeded) || errors.Is(err, pk.ErrOperationTimeout) ||
@@ -510,7 +528,7 @@ func TestPreparedAdapterMissingCredentialRetainsSetupCause(t *testing.T) {
t.Fatal(err)
}
var output map[string]any
_, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure ||
!errors.Is(err, pk.ErrAPIKeyEnvMissing) || !strings.Contains(err.Error(), "ADAPTER_KEY") ||
@@ -530,21 +548,16 @@ func TestPreparedAdapterClassifiesSetupAndDomainDecodeFailures(t *testing.T) {
CorrectionIndex int `json:"correction_index"`
} `json:"validations"`
}
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.ValidatorDecisionSetKey), &output)
response, err := client.CompleteStructured(context.Background(), adapterRequest("validation"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || !response.Execution.Available {
t.Fatalf("decode overflow: failure=%#v counts=%+v", failure, response.Execution)
}
_, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), nil)
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), nil)
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
t.Fatalf("invalid target: %#v", failure)
}
req := adapterRequest("missing_schema")
_, err = client.CompleteStructured(context.Background(), req, &output)
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
t.Fatalf("unknown schema: %#v", failure)
}
req = adapterRequest(responseschema.ValidatorDecisionSetKey)
req := adapterRequest("validation")
req.PromptID = "missing.prompt"
_, err = client.CompleteStructured(context.Background(), req, &output)
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
@@ -559,7 +572,7 @@ func TestPreparedAdapterNonRetryableProviderStatus(t *testing.T) {
t.Fatal(err)
}
var output map[string]any
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonProviderFailed || count.Load() != 1 || response.Execution.HTTPStatus == nil || *response.Execution.HTTPStatus != http.StatusBadRequest {
t.Fatalf("non-retryable provider failure: failure=%#v calls=%d counts=%+v", failure, count.Load(), response.Execution)
@@ -586,3 +599,28 @@ func TestOperationTimeoutDuringPreparationIsRecoverable(t *testing.T) {
t.Fatalf("failure = %#v", failure)
}
}
func TestPermissivePromptReturnsRecoverableDecodeFailures(t *testing.T) {
for _, tc := range []struct {
name, body string
}{
{"malformed JSON", `{"corrections": [`},
{"incompatible value", `{"corrections":"not-an-array"}`},
} {
t.Run(tc.name, func(t *testing.T) {
runtime, calls, _ := adapterFixtureWithPrompt(t, []reply{{200, tc.body}}, 0, 0, nil, operatorPromptDocument("system", "user"))
client, err := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, CallHooks{})
if err != nil {
t.Fatal(err)
}
var output struct {
Corrections []struct{} `json:"corrections"`
}
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || calls.Load() != 1 {
t.Fatalf("failure=%v calls=%d", err, calls.Load())
}
})
}
}

View File

@@ -16,7 +16,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit"
@@ -71,7 +70,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
t.Fatal(err)
}
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: vars, CaptureExchange: true}, &map[string]any{})
initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: vars, CaptureExchange: true}, &map[string]any{})
if err != nil || initial.Exchange == nil {
t.Fatalf("capture: %+v %v", initial, err)
}
@@ -87,7 +86,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
if turns == 2 {
return nil, nil
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil
})
if err != nil || exhausted || turns != 2 {
t.Fatalf("coordinated dialogue: turns=%d exhausted=%v error=%v", turns, exhausted, err)
@@ -112,7 +111,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
if turn.Response != nil {
return nil, turn.Err
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil
}
_, err = repair.Coordinate(context.Background(), initial.Exchange, 1, independent)
if err != nil || len(messages) != 4 || len(messages[3]) != len(prefix)+2 || !strings.Contains(string(messages[3][len(prefix)+1].Content), "independent") {
@@ -159,11 +158,11 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
if err != nil {
t.Fatal(err)
}
client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: 1}, CallHooks{})
client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{})
if err != nil {
t.Fatal(err)
}
base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{})
base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{})
if err != nil {
t.Fatal(err)
}
@@ -173,7 +172,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
result = turn.Response
return nil, turn.Err
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil
})
if err != nil || exhausted || result == nil {
t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err)

View File

@@ -6,7 +6,6 @@ import (
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit"
@@ -31,7 +30,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
req.CaptureExchange = true
base, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil {
@@ -55,7 +54,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
return nil, nil
}
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
})
if err != nil || exhausted != tc.again || deliveries != 1 || count.Load() != 2 {
t.Fatalf("exhausted=%v delivered=%d calls=%d err=%v", exhausted, deliveries, count.Load(), err)
@@ -78,7 +77,7 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) {
runtime, _, _ := adapterFixture(t, []reply{{200, `{"corrections":[]}`}, {200, `{"proposal_ref":1,"decision":{"action":"withdraw","correction":null}}`}}, 0, 0, nil)
collector := NewObservationCollector()
proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
req.CaptureExchange = true
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil {
@@ -102,7 +101,7 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) {
}
return nil, turn.Err
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
})
if !errors.Is(err, context.Canceled) || deliveries != 1 {
t.Fatalf("deliveries=%d err=%v", deliveries, err)
@@ -118,7 +117,7 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) {
proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
repair, _ := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, collector.Hooks())
validation, _ := runtime.NewRoleClient("validation", "base", runtime.Config.LLM, collector.Hooks())
req := adapterRequest(responseschema.CorrectionSetKey)
req := adapterRequest("proposal")
req.CaptureExchange = true
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil {
@@ -129,13 +128,43 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) {
if turn.Err != nil {
return nil, turn.Err
}
_, err := validation.CompleteStructured(ctx, adapterRequest(responseschema.ValidatorDecisionSetKey), &map[string]any{})
_, err := validation.CompleteStructured(ctx, adapterRequest("validation"), &map[string]any{})
return nil, err
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
})
summary := Summarize(collector.Snapshot())
if err != nil || count.Load() != 3 || summary.ProviderAttempts != 3 || summary.LogicalCalls != 3 || !summary.TerminalCoverageComplete {
t.Fatalf("calls=%d summary=%+v err=%v", count.Load(), summary, err)
}
}
func TestCoordinatorDeliversRecoverableMalformedOutput(t *testing.T) {
operator := "collections:\n audita:\n prompts:\n - id: modules.grammar.repair\n messages:\n - role: user\n content: '{{.RepairRequestJSON}}'\n output:\n format: text\n validation_mode: none\n"
runtime, count, _ := adapterFixtureWithPrompt(t, []reply{{200, `{"corrections":[]}`}, {200, `{"decision":[`}}, 0, 0, nil, operator)
client, err := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, CallHooks{})
if err != nil {
t.Fatal(err)
}
request := adapterRequest("proposal")
request.CaptureExchange = true
base, err := client.CompleteStructured(context.Background(), request, &map[string]any{})
if err != nil {
t.Fatal(err)
}
delivered := false
_, err = client.Coordinate(context.Background(), base.Exchange, 1, func(_ context.Context, turn structuredoutput.Turn) (*structuredoutput.Request, error) {
if turn.Response != nil {
delivered = true
var failure *structuredoutput.Failure
if !errors.As(turn.Err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput {
t.Fatalf("turn error = %v", turn.Err)
}
return nil, nil
}
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
})
if err != nil || !delivered || count.Load() != 2 {
t.Fatalf("error=%v delivered=%v calls=%d", err, delivered, count.Load())
}
}

View File

@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
@@ -16,7 +17,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit"
@@ -58,7 +58,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
t.Fatal(err)
}
var out map[string]any
_, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out)
_, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out)
if err == nil || calls != 1 {
t.Fatalf("error = %v, calls = %d", err, calls)
}
@@ -78,7 +78,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
if err != nil {
t.Fatal(err)
}
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
for _, tc := range []struct {
name string
repair int
@@ -91,6 +91,22 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
{"no repair", 0, []string{`{"wrong":true}`}, 1, false},
} {
t.Run(tc.name, func(t *testing.T) {
prompt, err := fs.ReadFile(prompts.Filesystem(), "assets/prompts/modules.grammar.proposal.yaml")
if err != nil {
t.Fatal(err)
}
prompt = append(prompt, []byte(fmt.Sprintf(" repair_attempts: %d\n", tc.repair))...)
promptDir := filepath.Join(dir, "prompts")
if err := os.MkdirAll(promptDir, 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(promptDir, "grammar.yml"), prompt, 0600); err != nil {
t.Fatal(err)
}
selected, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
if err != nil {
t.Fatal(err)
}
calls := 0
httpClient := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
item := tc.outputs[min(calls, len(tc.outputs)-1)]
@@ -99,11 +115,11 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
body := fmt.Sprintf(`{"model":"test-model","choices":[{"message":{"content":%s}}]}`, payload)
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}
runtime, err := NewRuntime(context.Background(), loaded, httpClient)
runtime, err := NewRuntime(context.Background(), selected, httpClient)
if err != nil {
t.Fatal(err)
}
client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: tc.repair}, CallHooks{})
client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{})
if err != nil {
t.Fatal(err)
}
@@ -176,7 +192,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
if err != nil {
t.Fatal(err)
}
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
done := make(chan error, 1)
go func() {
_, err := first.CompleteStructured(context.Background(), request, &map[string]any{})
@@ -222,7 +238,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
response, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil || calls != 2 || response.Execution.TransientRetries != 1 {
t.Fatalf("error=%v calls=%d execution=%+v", err, calls, response.Execution)
@@ -256,7 +272,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
if err != nil {
t.Fatal(err)
}
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
for _, tc := range []struct{ profile, auth string }{{"inherited", "Bearer backend-secret-value"}, {"explicit", "Bearer profile-secret-value"}, {"cleared", ""}} {
t.Run(tc.profile, func(t *testing.T) {
client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{})

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,154 +1,14 @@
package responseschema
import (
"crypto/sha256"
"embed"
"encoding/hex"
"encoding/json"
"fmt"
"io/fs"
"sort"
"strings"
)
// Key identifies one structured response schema used by Audita.
type Key string
const (
CorrectionSetKey Key = "correction_set"
CorrectionRepairKey Key = "correction_repair"
ValidatorDecisionSetKey Key = "validator_decision_set"
AssetRoot = "assets"
correctionSetSchemaID = "audita.correction_set"
correctionRepairSchemaID = "audita.correction_repair"
validatorDecisionSchemaID = "audita.validator_decision_set"
schemaVersionV1 = "v1"
)
const AssetRoot = "assets"
//go:embed assets/*.json
var schemaAssets embed.FS
// Filesystem exposes the canonical embedded schemas to PromptKit.
// Filesystem exposes embedded schemas to PromptKit.
func Filesystem() fs.FS { return schemaAssets }
func AssetPath(key Key) (string, bool) {
switch key {
case CorrectionSetKey:
return "correction_set.v1.json", true
case CorrectionRepairKey:
return "correction_repair.v1.json", true
case ValidatorDecisionSetKey:
return "validator_decision_set.v1.json", true
default:
return "", false
}
}
// Schema describes one registered structured response schema.
type Schema struct {
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
JSONSchema json.RawMessage `json:"json_schema"`
SHA256 string `json:"sha256"`
}
func (s Schema) DiagnosticsMap() map[string]any {
return map[string]any{
"id": s.ID,
"version": s.Version,
"name": s.Name,
"sha256": s.SHA256,
}
}
var registry = map[Key]Schema{
CorrectionRepairKey: mustBuildSchemaFromAsset(correctionRepairSchemaID, schemaVersionV1, "audita_correction_repair_v1", "assets/correction_repair.v1.json"),
CorrectionSetKey: mustBuildSchemaFromAsset(
correctionSetSchemaID,
schemaVersionV1,
"audita_correction_set_v1",
"assets/correction_set.v1.json",
),
ValidatorDecisionSetKey: mustBuildSchemaFromAsset(
validatorDecisionSchemaID,
schemaVersionV1,
"audita_validator_decision_set_v1",
"assets/validator_decision_set.v1.json",
),
}
func Registered() []Schema {
keys := make([]string, 0, len(registry))
for key := range registry {
keys = append(keys, string(key))
}
sort.Strings(keys)
out := make([]Schema, 0, len(keys))
for _, key := range keys {
out = append(out, cloneSchema(registry[Key(key)]))
}
return out
}
// Lookup returns a copy of the registered schema for the provided key.
func Lookup(key Key) (Schema, bool) {
schema, ok := registry[key]
if !ok {
return Schema{}, false
}
return cloneSchema(schema), true
}
// MustLookup returns a copy of the registered schema and panics when missing.
func MustLookup(key Key) Schema {
schema, ok := Lookup(key)
if !ok {
panic(fmt.Sprintf("unknown structured response schema key %q", key))
}
return schema
}
func cloneSchema(in Schema) Schema {
out := in
if in.JSONSchema != nil {
out.JSONSchema = append(json.RawMessage(nil), in.JSONSchema...)
}
return out
}
func mustBuildSchemaFromAsset(id string, version string, name string, assetPath string) Schema {
rawSchema, err := schemaAssets.ReadFile(assetPath)
if err != nil {
panic(fmt.Sprintf("read response schema asset %q: %v", assetPath, err))
}
return mustBuildSchema(id, version, name, rawSchema)
}
func mustBuildSchema(id string, version string, name string, rawSchema []byte) Schema {
id = strings.TrimSpace(id)
version = strings.TrimSpace(version)
name = strings.TrimSpace(name)
if id == "" {
panic("schema id must not be empty")
}
if version == "" {
panic("schema version must not be empty")
}
if name == "" {
panic("schema name must not be empty")
}
if !json.Valid(rawSchema) {
panic(fmt.Sprintf("schema %s:%s is not valid JSON", id, version))
}
hash := sha256.Sum256(rawSchema)
return Schema{
ID: id,
Version: version,
Name: name,
JSONSchema: append(json.RawMessage(nil), rawSchema...),
SHA256: hex.EncodeToString(hash[:]),
}
}

View File

@@ -1,129 +1,20 @@
package responseschema
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"io/fs"
"testing"
jsonschema "github.com/santhosh-tekuri/jsonschema/v6"
)
func TestPromptKitSchemaPathsUseCanonicalAssets(t *testing.T) {
for _, key := range []Key{CorrectionSetKey, CorrectionRepairKey, ValidatorDecisionSetKey} {
path, ok := AssetPath(key)
if !ok {
t.Fatalf("missing path for %q", key)
}
file, err := Filesystem().Open(AssetRoot + "/" + path)
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(file)
file.Close()
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(data, MustLookup(key).JSONSchema) {
t.Fatalf("PromptKit schema differs for %q", key)
}
}
}
func TestLookupKnownSchemas(t *testing.T) {
correction, ok := Lookup(CorrectionSetKey)
if !ok {
t.Fatalf("expected correction-set schema to be registered")
}
if correction.ID != correctionSetSchemaID {
t.Fatalf("unexpected correction-set schema id %q", correction.ID)
}
if correction.Version != schemaVersionV1 {
t.Fatalf("unexpected correction-set schema version %q", correction.Version)
}
if correction.Name != "audita_correction_set_v1" {
t.Fatalf("unexpected correction-set schema name %q", correction.Name)
}
validation, ok := Lookup(ValidatorDecisionSetKey)
if !ok {
t.Fatalf("expected validator-decision schema to be registered")
}
if validation.ID != validatorDecisionSchemaID {
t.Fatalf("unexpected validator-decision schema id %q", validation.ID)
}
if validation.Version != schemaVersionV1 {
t.Fatalf("unexpected validator-decision schema version %q", validation.Version)
}
if validation.Name != "audita_validator_decision_set_v1" {
t.Fatalf("unexpected validator-decision schema name %q", validation.Name)
}
}
func TestLookupUnknownSchema(t *testing.T) {
if _, ok := Lookup(Key("missing")); ok {
t.Fatalf("expected unknown schema lookup to fail")
}
}
func TestSchemaHashesMatchRegisteredJSON(t *testing.T) {
for _, key := range []Key{CorrectionSetKey, CorrectionRepairKey, ValidatorDecisionSetKey} {
schema, ok := Lookup(key)
if !ok {
t.Fatalf("missing schema %q", key)
}
sum := sha256.Sum256(schema.JSONSchema)
expected := hex.EncodeToString(sum[:])
if schema.SHA256 != expected {
t.Fatalf("unexpected hash for %q: got %q want %q", key, schema.SHA256, expected)
}
}
}
func TestLookupReturnsSchemaCopy(t *testing.T) {
schema, ok := Lookup(CorrectionSetKey)
if !ok {
t.Fatalf("missing correction-set schema")
}
if len(schema.JSONSchema) == 0 {
t.Fatalf("expected non-empty schema payload")
}
schema.JSONSchema[0] = 'x'
again, ok := Lookup(CorrectionSetKey)
if !ok {
t.Fatalf("missing correction-set schema on second lookup")
}
if len(again.JSONSchema) == 0 {
t.Fatalf("unexpected empty schema payload")
}
if again.JSONSchema[0] != '{' {
t.Fatalf("expected lookup to return independent schema copy")
}
}
func TestDiagnosticsMapIncludesStableSchemaMetadataShapeForAllSchemas(t *testing.T) {
registered := Registered()
if len(registered) == 0 {
t.Fatalf("expected registered response schemas")
}
for _, schema := range registered {
metadataMap := schema.DiagnosticsMap()
if metadataMap["id"] != schema.ID ||
metadataMap["version"] != schema.Version ||
metadataMap["name"] != schema.Name ||
metadataMap["sha256"] != schema.SHA256 {
t.Fatalf("unexpected diagnostics metadata map for %q: %+v", schema.ID, metadataMap)
}
}
}
func TestCorrectionRepairSchema(t *testing.T) {
var document any
if err := json.Unmarshal(MustLookup(CorrectionRepairKey).JSONSchema, &document); err != nil {
raw, err := fs.ReadFile(Filesystem(), AssetRoot+"/correction_repair.v1.json")
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(raw, &document); err != nil {
t.Fatal(err)
}
compiler := jsonschema.NewCompiler()

View File

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

View File

@@ -10,7 +10,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposal_generation"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/validators"
)
@@ -163,7 +162,7 @@ func runRepairBranch(ctx context.Context, branchInput repairBranchInput) (repair
}
proposalIndex, attemptNumber := original.ProposalIndex, branch.AttemptCount+1
return &structuredoutput.Request{PromptID: promptID, Variables: map[string]string{"RepairRequestJSON": payload}, Schema: responseschema.CorrectionRepairKey, CaptureDiagnostics: debug, Context: structuredoutput.DiagnosticContext{StageIndex: &input.Spec.Index, StageID: input.Spec.ID, Role: "correction_repair", ModuleKey: input.Spec.ModuleKey, ModuleInstance: input.Spec.InstanceName, SectionIndex: input.SectionIndex, ProposalIndex: &proposalIndex, RepairAttempt: &attemptNumber}}, nil
return &structuredoutput.Request{PromptID: promptID, Variables: map[string]string{"RepairRequestJSON": payload}, CaptureDiagnostics: debug, Context: structuredoutput.DiagnosticContext{StageIndex: &input.Spec.Index, StageID: input.Spec.ID, Role: "correction_repair", ModuleKey: input.Spec.ModuleKey, ModuleInstance: input.Spec.InstanceName, SectionIndex: input.SectionIndex, ProposalIndex: &proposalIndex, RepairAttempt: &attemptNumber}}, nil
}
exhausted, coordinationErr := input.Spec.RepairCoordinator.Coordinate(ctx, input.Exchange, input.Spec.Settings.LLM.CorrectionRepairAttempts, func(ctx context.Context, turn structuredoutput.Turn) (*structuredoutput.Request, error) {
if turn.Response == nil {

View File

@@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
ck "go.maximumdirect.net/configkit"
"io"
@@ -514,7 +513,7 @@ func (c *repairClient) Coordinate(ctx context.Context, _ *structuredoutput.Excha
t.Fatal(err)
}
var output map[string]any
base, err := client.CompleteStructured(ctx, structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, CaptureExchange: true, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &output)
base, err := client.CompleteStructured(ctx, structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, CaptureExchange: true, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &output)
if err != nil {
return false, err
}

View File

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

View File

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

View File

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

View File

@@ -14,7 +14,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
)
@@ -168,7 +167,7 @@ func TestLLMBackedValidatorApprovalAndRejection(t *testing.T) {
t.Fatalf("expected one LLM call, got %d", len(client.calls))
}
call := client.calls[0]
if call.Schema != responseschema.ValidatorDecisionSetKey || call.PromptID != prompts.PromptIDValidatorSpokenFormPlausibility || call.Context.Role != "validation" || call.Context.ValidatorName != v.Name() || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") {
if call.PromptID != prompts.PromptIDValidatorSpokenFormPlausibility || call.Context.Role != "validation" || call.Context.ValidatorName != v.Name() || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") {
t.Fatalf("unexpected validator call: %+v", call)
}
}
@@ -329,7 +328,7 @@ func TestLLMBackedValidatorOversizedSingleProposalRejectsOnlyThatProposal(t *tes
}
}
func TestLLMBackedValidatorDiagnosticsIncludeSchemaMetadata(t *testing.T) {
func TestLLMBackedValidatorDiagnosticsOmitRegistrySchemaMetadata(t *testing.T) {
client := &fakeStructuredLLMClient{responses: []LLMValidationResponse{{Validations: []LLMValidationDecision{
{CorrectionIndex: "1", Approved: true, Reason: "ok"},
}}}}
@@ -349,13 +348,8 @@ func TestLLMBackedValidatorDiagnosticsIncludeSchemaMetadata(t *testing.T) {
if !ok {
t.Fatalf("expected metadata map, got %T", writer.lastRequestMetadata)
}
schemaMap, ok := metadata["response_schema"].(map[string]any)
if !ok {
t.Fatalf("expected response_schema map, got %T", metadata["response_schema"])
}
want := responseschema.MustLookup(responseschema.ValidatorDecisionSetKey)
if schemaMap["id"] != want.ID || schemaMap["version"] != want.Version || schemaMap["name"] != want.Name || schemaMap["sha256"] != want.SHA256 {
t.Fatalf("unexpected diagnostics schema metadata: got=%v want=%+v", schemaMap, want)
if _, exists := metadata["response_schema"]; exists {
t.Fatal("unexpected registry schema metadata")
}
}
@@ -385,7 +379,7 @@ func TestEveryValidationTypeSelectsEmbeddedPromptAndVariables(t *testing.T) {
t.Fatalf("calls=%d", len(client.calls))
}
call := client.calls[0]
if call.PromptID != tc.prompt || call.Schema != responseschema.ValidatorDecisionSetKey || call.Context.Role != "validation" || call.Context.BatchIndex == nil || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") || !strings.Contains(call.Variables["TranscriptDescriptionBlock"], "Fantasy scene") {
if call.PromptID != tc.prompt || call.Context.Role != "validation" || call.Context.BatchIndex == nil || !strings.Contains(call.Variables["PayloadJSON"], "correction_index") || !strings.Contains(call.Variables["TranscriptDescriptionBlock"], "Fantasy scene") {
t.Fatalf("mapping: %+v", call)
}
})