Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bdeac85e8e | |||
| c554eecaec | |||
| 59f353348b | |||
| ac47c239c2 | |||
| fed190cc97 | |||
| d25d7fa7d4 | |||
| deec32cd4c | |||
| a020d155f4 | |||
| ca06f7c4e3 | |||
| 338e93a7eb | |||
| 58ff21e4df | |||
| 752ec676a6 | |||
| fa5d834f13 | |||
| c477bcc388 | |||
| c167a5e5ab | |||
| 6ca5f89356 | |||
| 9977cd9130 | |||
| 1ca5011049 | |||
| f87c45331c | |||
| 82c52c8e7f | |||
| 12fd2fba6b | |||
| f13db066f2 | |||
| e144c502f6 | |||
| 4dc461f9c9 | |||
| 60a80381a9 | |||
| 231b4c8a14 | |||
| e0471af25a | |||
| 187600eed2 | |||
| 11f45c8812 | |||
| a301ad1f27 | |||
| 92162ba9a6 |
@@ -17,6 +17,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
type repairWireMessage struct {
|
type repairWireMessage struct {
|
||||||
@@ -115,7 +116,7 @@ func (p *correctionProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
raw, _ := json.Marshal(content)
|
raw, _ := json.Marshal(content)
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}]}`, raw)
|
fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSubprocessReportsDefectOnOriginatingRepair(t *testing.T) {
|
func TestSubprocessReportsDefectOnOriginatingRepair(t *testing.T) {
|
||||||
@@ -190,7 +191,7 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
|||||||
provider.mu.Lock()
|
provider.mu.Lock()
|
||||||
provider.decimalReferences = tc.decimalReferences
|
provider.decimalReferences = tc.decimalReferences
|
||||||
provider.mu.Unlock()
|
provider.mu.Unlock()
|
||||||
args := []string{"--verbose"}
|
args := []string{"--verbose", "--show-tokens"}
|
||||||
if tc.debug {
|
if tc.debug {
|
||||||
args = append(args, "--debug")
|
args = append(args, "--debug")
|
||||||
}
|
}
|
||||||
@@ -222,6 +223,9 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
|||||||
provider.mu.Lock()
|
provider.mu.Lock()
|
||||||
requests := append([]repairWireRequest(nil), provider.requests...)
|
requests := append([]repairWireRequest(nil), provider.requests...)
|
||||||
provider.mu.Unlock()
|
provider.mu.Unlock()
|
||||||
|
if !strings.Contains(stderr, fmt.Sprintf("Prompts: %d", len(requests))) || !strings.Contains(stderr, "Total tokens:") {
|
||||||
|
t.Fatalf("native usage did not cover the assembled pipeline: requests=%d stderr=%s", len(requests), stderr)
|
||||||
|
}
|
||||||
var base []repairWireMessage
|
var base []repairWireMessage
|
||||||
var branches [][]repairWireMessage
|
var branches [][]repairWireMessage
|
||||||
for _, req := range requests {
|
for _, req := range requests {
|
||||||
@@ -271,13 +275,13 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var execution struct {
|
var execution struct {
|
||||||
Summary struct {
|
Summary struct {
|
||||||
ProviderAttempts int `json:"provider_attempts"`
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
} `json:"summary"`
|
} `json:"summary"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(data, &execution); err != nil {
|
if err := json.Unmarshal(data, &execution); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if got := execution.Summary.ProviderAttempts; got != len(requests) {
|
if got := execution.Summary.PromptKit.Attempts; got != uint64(len(requests)) {
|
||||||
t.Fatalf("execution provider attempts = %d, captured requests = %d", got, len(requests))
|
t.Fatalf("execution provider attempts = %d, captured requests = %d", got, len(requests))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -336,7 +340,7 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
|
|||||||
f, provider := setupCorrectionFixture(t, 2, false, true)
|
f, provider := setupCorrectionFixture(t, 2, false, true)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug"}
|
args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug", "--show-tokens"}
|
||||||
command := exec.CommandContext(ctx, os.Args[0], args...)
|
command := exec.CommandContext(ctx, os.Args[0], args...)
|
||||||
command.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1")
|
command.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1")
|
||||||
var stderr bytes.Buffer
|
var stderr bytes.Buffer
|
||||||
@@ -356,6 +360,12 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
|
|||||||
if ctx.Err() != nil || err == nil {
|
if ctx.Err() != nil || err == nil {
|
||||||
t.Fatalf("cancellation: %v ctx=%v stderr=%s", err, ctx.Err(), stderr.String())
|
t.Fatalf("cancellation: %v ctx=%v stderr=%s", err, ctx.Err(), stderr.String())
|
||||||
}
|
}
|
||||||
|
provider.mu.Lock()
|
||||||
|
count := len(provider.requests)
|
||||||
|
provider.mu.Unlock()
|
||||||
|
if !strings.Contains(stderr.String(), fmt.Sprintf("Prompts: %d", count)) {
|
||||||
|
t.Fatalf("canceled usage missing executions: requests=%d stderr=%s", count, stderr.String())
|
||||||
|
}
|
||||||
if _, err := os.Stat(f.output); !os.IsNotExist(err) {
|
if _, err := os.Stat(f.output); !os.IsNotExist(err) {
|
||||||
t.Fatalf("transcript published: %v", err)
|
t.Fatalf("transcript published: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"os"
|
"os"
|
||||||
@@ -24,6 +26,8 @@ import (
|
|||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/cli"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/cli"
|
||||||
"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/prompts"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
"go.yaml.in/yaml/v4"
|
"go.yaml.in/yaml/v4"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -195,7 +199,7 @@ func (p *fixtureProvider) serve(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
encoded, _ := json.Marshal(content)
|
encoded, _ := json.Marshal(content)
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
_, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, encoded)
|
_, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5,"completion_tokens_details":{"reasoning_tokens":1},"cost":0.02}}`, encoded)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read the supplied candidate JSON independently of the bundled instruction prose.
|
// Read the supplied candidate JSON independently of the bundled instruction prose.
|
||||||
@@ -261,6 +265,25 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
|
|||||||
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
|
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
|
||||||
repairs = 1
|
repairs = 1
|
||||||
}
|
}
|
||||||
|
if repairs == 0 {
|
||||||
|
promptDir := filepath.Join(dir, "prompts")
|
||||||
|
if err := os.Mkdir(promptDir, 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, meta := range prompts.RegisteredMetadata() {
|
||||||
|
if strings.HasSuffix(meta.PromptID, ".repair") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := fs.ReadFile(prompts.Filesystem(), meta.EmbeddedPath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data = promptfixture.WithRepairAttempts(t, data, 0)
|
||||||
|
if err := os.WriteFile(filepath.Join(promptDir, filepath.Base(meta.EmbeddedPath)), data, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
var stageList []string
|
var stageList []string
|
||||||
for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") {
|
for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") {
|
||||||
if name = strings.TrimSpace(name); name != "" {
|
if name = strings.TrimSpace(name); name != "" {
|
||||||
@@ -271,7 +294,7 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
|
|||||||
if len(stageList) != 0 {
|
if len(stageList) != 0 {
|
||||||
pipeline = " stages:\n" + strings.Join(stageList, "\n") + "\n"
|
pipeline = " stages:\n" + strings.Join(stageList, "\n") + "\n"
|
||||||
}
|
}
|
||||||
configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\n repair_attempts: %d\npipeline:\n%sdiagnostics:\n work_dir: %s\n", repairs, pipeline, filepath.Join(dir, "runs"))
|
configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\npipeline:\n%sdiagnostics:\n work_dir: %s\n", pipeline, filepath.Join(dir, "runs"))
|
||||||
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
|
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
|
||||||
configText += "validation:\n max_prompt_tokens: 4096\nchunking:\n target_sections: 1\n max_section_tokens: 8192\n min_section_tokens: 1\nnormalization:\n max_segment_gap: 0\n"
|
configText += "validation:\n max_prompt_tokens: 4096\nchunking:\n target_sections: 1\n max_section_tokens: 8192\n min_section_tokens: 1\nnormalization:\n max_segment_gap: 0\n"
|
||||||
}
|
}
|
||||||
@@ -311,6 +334,54 @@ func (f processFixture) run(t *testing.T, includeOutput bool, extra ...string) (
|
|||||||
return code, stdout.String(), stderr.String()
|
return code, stdout.String(), stderr.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSubprocessNativeUsageReporting(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name, mode, modules string
|
||||||
|
flags []string
|
||||||
|
fileOutput bool
|
||||||
|
wantPrompts string
|
||||||
|
wantUsage bool
|
||||||
|
}{
|
||||||
|
{"normalization", "normal", "[]", []string{"--show-tokens"}, false, "Prompts: 0", true},
|
||||||
|
{"failed provider", "all-model-failure", "[grammar]", []string{"--show-tokens"}, false, "Prompts: 1", true},
|
||||||
|
{"quiet", "normal", "[grammar]", []string{"--show-tokens", "--quiet"}, true, "", false},
|
||||||
|
} {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
f := newProcessFixture(t, tc.mode, tc.modules)
|
||||||
|
code, stdout, stderr := f.run(t, tc.fileOutput, tc.flags...)
|
||||||
|
if code != 0 || strings.Contains(stdout, "Observed PromptKit execution usage") || strings.Contains(stderr, "Observed PromptKit execution usage") != tc.wantUsage {
|
||||||
|
t.Fatalf("status=%d stdout=%q stderr=%q", code, stdout, stderr)
|
||||||
|
}
|
||||||
|
if tc.wantUsage && !strings.Contains(stderr, tc.wantPrompts) {
|
||||||
|
t.Fatalf("missing usage count %q: %s", tc.wantPrompts, stderr)
|
||||||
|
}
|
||||||
|
if !tc.fileOutput && !json.Valid([]byte(stdout)) {
|
||||||
|
t.Fatalf("stdout is not transcript JSON: %q", stdout)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(f.dir, "report.md")); err != nil {
|
||||||
|
t.Fatalf("ordinary report missing: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSubprocessExplicitProviderUsage(t *testing.T) {
|
||||||
|
f := newProcessFixture(t, "normal", "[grammar]")
|
||||||
|
path := filepath.Join(f.dir, "prompts.yml")
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data = bytes.Replace(data, []byte(" - id: local\n"), []byte(" - id: local\n provider: openrouter\n"), 1)
|
||||||
|
if err := os.WriteFile(path, data, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
code, stdout, stderr := f.run(t, false, "--show-tokens")
|
||||||
|
if code != 0 || !json.Valid([]byte(stdout)) || f.provider.callCount() != 3 || !strings.Contains(stderr, "Reasoning tokens: 3") || !strings.Contains(stderr, "Cost: USD 0.06") {
|
||||||
|
t.Fatalf("provider usage: status=%d calls=%d stdout=%q stderr=%q", code, f.provider.callCount(), stdout, stderr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func (f processFixture) errors(t *testing.T) reporting.ErrorsDocument {
|
func (f processFixture) errors(t *testing.T) reporting.ErrorsDocument {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
raw, err := os.ReadFile(filepath.Join(f.dir, "errors.yml"))
|
raw, err := os.ReadFile(filepath.Join(f.dir, "errors.yml"))
|
||||||
@@ -431,10 +502,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) {
|
|||||||
}
|
}
|
||||||
var execution struct {
|
var execution struct {
|
||||||
Calls []struct {
|
Calls []struct {
|
||||||
Summary struct {
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
ProviderAttempts int `json:"provider_attempts"`
|
|
||||||
StructuralRepairs int `json:"structural_repairs"`
|
|
||||||
} `json:"summary"`
|
|
||||||
} `json:"calls"`
|
} `json:"calls"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &execution); err != nil {
|
if err := json.Unmarshal(raw, &execution); err != nil {
|
||||||
@@ -444,7 +512,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) {
|
|||||||
t.Fatalf("unexpected generation counts: calls=%d provider=%d", len(execution.Calls), f.provider.callCount())
|
t.Fatalf("unexpected generation counts: calls=%d provider=%d", len(execution.Calls), f.provider.callCount())
|
||||||
}
|
}
|
||||||
for _, call := range execution.Calls {
|
for _, call := range execution.Calls {
|
||||||
if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 {
|
if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 {
|
||||||
t.Fatalf("unexpected structural repair: %+v", call)
|
t.Fatalf("unexpected structural repair: %+v", call)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -492,10 +560,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in
|
|||||||
}
|
}
|
||||||
var execution struct {
|
var execution struct {
|
||||||
Calls []struct {
|
Calls []struct {
|
||||||
Summary struct {
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
ProviderAttempts int `json:"provider_attempts"`
|
|
||||||
StructuralRepairs int `json:"structural_repairs"`
|
|
||||||
} `json:"summary"`
|
|
||||||
} `json:"calls"`
|
} `json:"calls"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &execution); err != nil {
|
if err := json.Unmarshal(raw, &execution); err != nil {
|
||||||
@@ -505,7 +570,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in
|
|||||||
t.Fatalf("logical/provider calls: %d/%d", len(execution.Calls), providerCalls)
|
t.Fatalf("logical/provider calls: %d/%d", len(execution.Calls), providerCalls)
|
||||||
}
|
}
|
||||||
for _, call := range execution.Calls {
|
for _, call := range execution.Calls {
|
||||||
if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 {
|
if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 {
|
||||||
t.Fatalf("extra generation or structural repair: %+v", call)
|
t.Fatalf("extra generation or structural repair: %+v", call)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1414,7 +1479,7 @@ func TestSubprocessProfileSources(t *testing.T) {
|
|||||||
f := newProcessFixture(t, "success", "[]")
|
f := newProcessFixture(t, "success", "[]")
|
||||||
// PromptKit uses profile IDs, not filename stems. A report-named profile is
|
// PromptKit uses profile IDs, not filename stems. A report-named profile is
|
||||||
// still an input and must not be overwritten during report initialization.
|
// still an input and must not be overwritten during report initialization.
|
||||||
if err := os.Mkdir(filepath.Join(f.dir, "prompts"), 0700); err != nil {
|
if err := os.MkdirAll(filepath.Join(f.dir, "prompts"), 0700); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded := filepath.Join(f.dir, "prompts", "errors.yml")
|
loaded := filepath.Join(f.dir, "prompts", "errors.yml")
|
||||||
|
|||||||
16
docs/cli.md
16
docs/cli.md
@@ -3,7 +3,7 @@
|
|||||||
Audita uses CommandKit for routing and the ConfigKit and PromptKit integrations
|
Audita uses CommandKit for routing and the ConfigKit and PromptKit integrations
|
||||||
for their standard inspection and request commands. Run `audita --help` or
|
for their standard inspection and request commands. Run `audita --help` or
|
||||||
command-specific `--help` for the installed command inventory. The adopted
|
command-specific `--help` for the installed command inventory. The adopted
|
||||||
[CommandKit consumer guide](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/f369d6a78253b6e6fcb1e023fb2e9c3af1d20ff0/docs/consumers/guide.md)
|
[CommandKit consumer guide](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/docs/consumers/guide.md)
|
||||||
describes the standard command grammar, inspection, comparison, preview,
|
describes the standard command grammar, inspection, comparison, preview,
|
||||||
validation, smoke tests, and their provider-specific caveats. Help and version
|
validation, smoke tests, and their provider-specific caveats. Help and version
|
||||||
do not load application or model configuration.
|
do not load application or model configuration.
|
||||||
@@ -20,6 +20,12 @@ audita process [flags] transcript.json
|
|||||||
messages. Quiet processing requires an output file or `/dev/null`. See
|
messages. Quiet processing requires an output file or `/dev/null`. See
|
||||||
[operations](operations.md) for output and report lifecycle.
|
[operations](operations.md) for output and report lifecycle.
|
||||||
|
|
||||||
|
Use `audita process --show-tokens --config config.yml transcript.json` to
|
||||||
|
request the native execution-usage summary on diagnostics. It works without
|
||||||
|
debug capture or ordinary reports and follows quiet mode. See the
|
||||||
|
[ckprompt guide](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.12.0/docs/consumers/guide.md)
|
||||||
|
for usage and native command details.
|
||||||
|
|
||||||
Progress for processing goes to stderr. Use `--progress` to show stage and
|
Progress for processing goes to stderr. Use `--progress` to show stage and
|
||||||
chunk activity, model proposal, validation and repair operations, and observed
|
chunk activity, model proposal, validation and repair operations, and observed
|
||||||
counts as work completes. Debug mode enables progress by default.
|
counts as work completes. Debug mode enables progress by default.
|
||||||
@@ -43,11 +49,15 @@ own configuration and resource scopes and request preparation, validation, and
|
|||||||
explicit smoke diagnostics. Inspection does not require a processing-ready
|
explicit smoke diagnostics. Inspection does not require a processing-ready
|
||||||
pipeline or contact a provider. Processing preflight separately checks the selected
|
pipeline or contact a provider. Processing preflight separately checks the selected
|
||||||
profiles and glossary entries. Smoke tests can contact providers and are run
|
profiles and glossary entries. Smoke tests can contact providers and are run
|
||||||
only on explicit request.
|
only on explicit request. Request `--format yaml` or `--format json` for
|
||||||
|
machine-readable smoke results; their default is text. Shared loading can run
|
||||||
|
configured secrets bootstrap for inspection as well as processing.
|
||||||
|
|
||||||
Process stdout contains transcript JSON when no output file is selected. Ordinary
|
Process stdout contains transcript JSON when no output file is selected. Ordinary
|
||||||
reports may record recoverable model failures even when processing completes.
|
reports may record recoverable model failures even when processing completes.
|
||||||
Exit status `0` means success, `1` runtime or output failure, `2` invalid usage
|
Exit status `0` means success, `1` runtime or output failure, `2` invalid usage
|
||||||
or input, and native comparison may return `3` for differences. A missing
|
or input, and native comparison may return `3` for differences. ConfigKit
|
||||||
|
classifies native configuration diagnostics; unclassified runtime preparation
|
||||||
|
and bootstrap failures, and cancellation, are operational. A missing
|
||||||
processing profile or required glossary selection is an input failure. See the
|
processing profile or required glossary selection is an input failure. See the
|
||||||
[output contract](integrations/output-files.md) and [subprocess contract](integrations/subprocess.md).
|
[output contract](integrations/output-files.md) and [subprocess contract](integrations/subprocess.md).
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
# Audita Configuration
|
# Audita Configuration
|
||||||
|
|
||||||
Audita uses version 3 application configuration. See the [migration guide](migrations/v3.md)
|
Audita uses version 3 application configuration. See the [migration guide](migrations/v3.md)
|
||||||
and [examples](../examples/) for complete projects. Command syntax is owned by
|
and [v4.1 migration guide](migrations/v4.1.md), and [examples](../examples/)
|
||||||
|
for complete projects. Command syntax is owned by
|
||||||
[the CLI reference](cli.md).
|
[the CLI reference](cli.md).
|
||||||
|
|
||||||
## Loading and composition
|
## Loading and composition
|
||||||
@@ -18,16 +19,33 @@ base for an optional `overlays/<name>.yml`, optional `glossary.yml`, and recursi
|
|||||||
`glossary/` YAML files. Without a main source, automatic companion files are not
|
`glossary/` YAML files. Without a main source, automatic companion files are not
|
||||||
loaded from the working directory. ConfigKit composes sources, resolves native
|
loaded from the working directory. ConfigKit composes sources, resolves native
|
||||||
inheritance, applies explicit overrides, records derived defaults, and validates
|
inheritance, applies explicit overrides, records derived defaults, and validates
|
||||||
the result. Its [configuration reference](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.2.0/docs/config.md)
|
the result. Its [configuration reference](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md)
|
||||||
owns native composition and provenance semantics.
|
owns native composition and provenance semantics.
|
||||||
|
|
||||||
|
Before shared configuration loading, Audita runs configured ConfigKit secrets
|
||||||
|
bootstrap against the selected main source. This can populate the process
|
||||||
|
environment for processing and native inspection; help and version do not load
|
||||||
|
configuration. A bootstrap failure stops the acquisition before transcript and
|
||||||
|
output preparation. See the [ConfigKit secrets documentation](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md)
|
||||||
|
for directory and overwrite controls.
|
||||||
|
|
||||||
### PromptKit profiles and operator prompts
|
### PromptKit profiles and operator prompts
|
||||||
|
|
||||||
PromptKit loads its default catalog and Audita's embedded prompts, followed by
|
The combined result contains native PromptKit settings under `/promptkit`.
|
||||||
optional `prompts.yml` and recursive `prompts/` YAML files beside the application
|
Audita combines the bundled OpenRouter catalog and its embedded prompts and
|
||||||
main. Native imports, resource collections, inheritance, and replacement apply.
|
schemas with optional wrapperless `prompts.yml` and recursive `prompts/` YAML
|
||||||
|
files beside the application main. These companions are mounted at `/promptkit`;
|
||||||
|
a main or overlay may instead contain a `promptkit` section. Native imports,
|
||||||
|
resource collections, inheritance, and replacement apply.
|
||||||
Profiles, backends, models, credentials, admission, and provider parameters belong
|
Profiles, backends, models, credentials, admission, and provider parameters belong
|
||||||
to PromptKit configuration; see its [format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.23.0/docs/formats.md).
|
to PromptKit configuration; see its [format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md).
|
||||||
|
The selected prompt owns its output contract and structural-repair budget;
|
||||||
|
operators replacing a prompt must supply a contract compatible with Audita's
|
||||||
|
expected response. See the [migration guide](migrations/v4.1.md).
|
||||||
|
Declare `provider: openrouter` for custom OpenRouter backends or `provider: vllm`
|
||||||
|
for vLLM; an omitted provider remains generic. Neither an endpoint nor a backend
|
||||||
|
ID implies provider conventions or zero cost. PromptKit owns those settings and
|
||||||
|
their [usage and cost semantics](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/integrations/openai-compatible-chat.md).
|
||||||
The engine captures its sources for an invocation. Edit files and run a new
|
The engine captures its sources for an invocation. Edit files and run a new
|
||||||
invocation to pick up changes. Inspection does not require model credentials.
|
invocation to pick up changes. Inspection does not require model credentials.
|
||||||
|
|
||||||
@@ -74,7 +92,6 @@ specified by the [editorial acceptance boundary](policy/architecture.md#correcti
|
|||||||
| `llm.correction_repair_profile` | effective proposal profile | Profile for correction repair; null clears an inherited selection before fallback. |
|
| `llm.correction_repair_profile` | effective proposal profile | Profile for correction repair; null clears an inherited selection before fallback. |
|
||||||
| `llm.correction_repair_attempts` | `1` | Nonnegative repair attempts per correction; zero disables correction repair. |
|
| `llm.correction_repair_attempts` | `1` | Nonnegative repair attempts per correction; zero disables correction repair. |
|
||||||
| `llm.transient_retries` | `2` | Additional transient attempts per generation. |
|
| `llm.transient_retries` | `2` | Additional transient attempts per generation. |
|
||||||
| `llm.repair_attempts` | `2` | Structural repairs, from zero through three. |
|
|
||||||
| `llm.operation_timeout` | `15m` | Positive duration per logical operation. |
|
| `llm.operation_timeout` | `15m` | Positive duration per logical operation. |
|
||||||
| `validation.max_prompt_tokens` | `2048` | Positive validation batching budget. |
|
| `validation.max_prompt_tokens` | `2048` | Positive validation batching budget. |
|
||||||
| `context.description` | empty | Prompt context; at most 500 bytes after trimming. |
|
| `context.description` | empty | Prompt context; at most 500 bytes after trimming. |
|
||||||
|
|||||||
@@ -1,34 +1,22 @@
|
|||||||
# OpenAI-Compatible LLM Integration
|
# OpenAI-Compatible LLM Integration
|
||||||
|
|
||||||
Audita uses the pinned [PromptKit](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/171fb11f4e967a1da3af57843c6467954b14ba09)
|
Audita uses [PromptKit v0.25.0](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/integrations/openai-compatible-chat.md)
|
||||||
built-in OpenAI-compatible transport. PromptKit owns chat-completions wire framing,
|
for its OpenAI-compatible transport, provider conventions, credentials, retries,
|
||||||
provider envelope parsing, transient retries, per-generation timeouts, and JSON
|
admission, and observed token and cost information. Inspection prepares requests
|
||||||
Schema repair. A backend's configured base endpoint must support the selected
|
without contacting a provider or requiring model credentials.
|
||||||
profile's model and structured JSON-schema responses; local configuration
|
|
||||||
inspection does not contact the provider.
|
|
||||||
|
|
||||||
Audita selects role profiles independently for each pipeline entry and supplies
|
Audita selects a profile for each proposal, validation, and correction-repair
|
||||||
its domain response schema and per-operation budget. PromptKit owns backend and
|
role. The selected prompt supplies the output contract and structural-repair
|
||||||
credential selection, request preparation, transport, retries, repairs, and
|
budget, while Audita retains its operation timeout, transient retry selection,
|
||||||
admission. Audita executes the same prepared handle and retains its own domain
|
semantic correction-repair budget, and domain checks. Operator prompt contracts
|
||||||
validation. Profiles may use native endpoint and credential settings; local
|
must produce the response shapes expected by Audita. See [configuration](../config.md)
|
||||||
inspection does not resolve a credential value or call the provider.
|
and the [migration guide](../migrations/v4.1.md).
|
||||||
|
|
||||||
`llm.transient_retries` counts additional attempts for eligible transient
|
Exhausted structural validation, an incompatible response JSON, a live-parent
|
||||||
failures; explicit zero makes one attempt. `llm.repair_attempts` counts
|
operation timeout, capacity rejection, transport failure, malformed provider
|
||||||
additional generations for schema-invalid model output. The operation timeout
|
response, or provider HTTP failure is recoverable for the affected operation.
|
||||||
covers preparation, capacity waiting, retries, generation, and repair. Caller
|
Proposal generation contributes no candidates from a failed response; a failed
|
||||||
cancellation or an earlier deadline also applies. See [configuration](../config.md#settings)
|
validation batch makes its candidates unavailable while independent work can
|
||||||
for defaults and the [PromptKit consumer contract](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.23.0/docs/consumers/pkg-promptkit.md)
|
continue. Caller cancellation, broken assets or configuration, and internal
|
||||||
for protocol and retry details.
|
programming failures remain fatal. Ordinary reports use safe reason codes and
|
||||||
|
counts. Full interaction content is optional [debug evidence](../operations.md#debug-evidence).
|
||||||
A model operation that exhausts structural repair, a live-parent local operation
|
|
||||||
timeout, capacity rejection, transport failure, malformed provider response,
|
|
||||||
or provider HTTP failure is recoverable for that operation. Proposal generation
|
|
||||||
then contributes no candidates from that response; a failed validation batch
|
|
||||||
marks its candidates unavailable while other batches and later modules can
|
|
||||||
continue. Caller cancellation, broken assets or configuration, and unknown
|
|
||||||
internal failures remain fatal and cancel peers. Audita decodes into domain
|
|
||||||
types only after PromptKit validates the JSON. Ordinary reports use safe reason
|
|
||||||
codes and counts rather than provider messages. Full request/response content
|
|
||||||
is written only with `--debug`; see [operations](../operations.md#debug-evidence).
|
|
||||||
|
|||||||
@@ -105,7 +105,9 @@ transcript excerpts or correction lists.
|
|||||||
|
|
||||||
With `--debug`, `correction-ledger.json` contains proposed candidates and
|
With `--debug`, `correction-ledger.json` contains proposed candidates and
|
||||||
their application, rejection, or interruption details. `llm-execution.json`
|
their application, rejection, or interruption details. `llm-execution.json`
|
||||||
holds logical calls and PromptKit execution events. Interaction request/response
|
holds `summary`, `calls`, and `events` with Audita attribution and nested native
|
||||||
|
PromptKit evidence. Interaction request payloads include the prepared native
|
||||||
|
contract and message hash when preparation succeeded. Interaction request/response
|
||||||
artifacts and input snapshots are also debug-only. Records carry zero-based
|
artifacts and input snapshots are also debug-only. Records carry zero-based
|
||||||
`stage_index` and optional `stage_id` where an entry is identified.
|
`stage_index` and optional `stage_id` where an entry is identified.
|
||||||
These files are diagnostic evidence, not an alternate ordinary report schema.
|
These files are diagnostic evidence, not an alternate ordinary report schema.
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ directory. For stdout output, reports use the effective `reporting.stdout_dir`
|
|||||||
override. A config-file or overlay value for `reporting.stdout_dir` alone does
|
override. A config-file or overlay value for `reporting.stdout_dir` alone does
|
||||||
not redirect file-output reports. `--work-dir` selects a debug root, while
|
not redirect file-output reports. `--work-dir` selects a debug root, while
|
||||||
`--debug` enables capture; the path flag alone does not.
|
`--debug` enables capture; the path flag alone does not.
|
||||||
Supplying a configuration path also makes file selection predictable; only
|
Supplying a configuration path also makes file selection predictable. Configured
|
||||||
explicitly referenced credential variables are read from the environment.
|
secrets bootstrap can populate the child environment before the shared load;
|
||||||
|
see [configuration](../config.md#loading-and-composition).
|
||||||
|
|
||||||
Choose a trusted configuration bundle. An explicit main path still allows
|
Choose a trusted configuration bundle. An explicit main path still allows
|
||||||
its configured imports and automatic overlay, glossary, and prompt companions.
|
its configured imports and automatic overlay, glossary, and prompt companions.
|
||||||
@@ -41,7 +42,8 @@ Interpret the exit result according to the
|
|||||||
Consume transcript/report data through the
|
Consume transcript/report data through the
|
||||||
[output-file contract](output-files.md), and treat stderr as human-readable detail.
|
[output-file contract](output-files.md), and treat stderr as human-readable detail.
|
||||||
Audita loads configuration and parses the input transcript before report
|
Audita loads configuration and parses the input transcript before report
|
||||||
initialization. Early destination failures can also leave no reports. After
|
initialization. Bootstrap failure also occurs before transcript and output
|
||||||
|
preparation and may leave no reports. Early destination failures can also leave no reports. After
|
||||||
initialization, failed reports can describe partial processing or output
|
initialization, failed reports can describe partial processing or output
|
||||||
failures and use the same report directory as successful runs.
|
failures and use the same report directory as successful runs.
|
||||||
Exit `0` can include recoverable model errors and applied
|
Exit `0` can include recoverable model errors and applied
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ CLI wiring, and maintained examples. Definitions of behavior belong to the
|
|||||||
|
|
||||||
## Changing Configuration
|
## Changing Configuration
|
||||||
|
|
||||||
1. Update fields, defaults, loading, and validation in `internal/core/config`.
|
1. Update domain fields, defaults, and validation in `internal/core/config`;
|
||||||
|
update shared source composition in `internal/appconfig` when needed.
|
||||||
2. Update file, selected overlay, credential reference, and CLI mapping as
|
2. Update file, selected overlay, credential reference, and CLI mapping as
|
||||||
applicable. Preserve the precedence defined in the
|
applicable. Preserve the precedence defined in the
|
||||||
[configuration contract](../config.md#loading-and-composition), including the
|
[configuration contract](../config.md#loading-and-composition), including the
|
||||||
|
|||||||
@@ -60,9 +60,11 @@ prompt content. Execution
|
|||||||
position and optional operator ID are carried separately from generated safe
|
position and optional operator ID are carried separately from generated safe
|
||||||
artifact path coordinates.
|
artifact path coordinates.
|
||||||
|
|
||||||
Execution diagnostics include a native-group invocation summary and per-call
|
Execution diagnostics put native group evidence under `promptkit` in the
|
||||||
summaries. Terminal coverage is separate from usage completeness; unknown usage
|
invocation summary and each logical call, and native events under `promptkit`
|
||||||
is distinct from known zero. Overlapping summaries must not be added together.
|
with Audita's call and context attribution. Prepared interaction payloads retain
|
||||||
|
the actual native request under the same key. See [PromptKit's execution guide](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md)
|
||||||
|
for coverage and usage semantics. Overlapping summaries must not be added together.
|
||||||
The collector snapshots after work joins and retains domain labels and stable
|
The collector snapshots after work joins and retains domain labels and stable
|
||||||
presentation order. Prepared evidence comes from `OnPrepared`, so preparation or
|
presentation order. Prepared evidence comes from `OnPrepared`, so preparation or
|
||||||
admission failures may have no request snapshot. Coordinator execution failures
|
admission failures may have no request snapshot. Coordinator execution failures
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
# Audita LLM Runtime
|
# Audita LLM Runtime
|
||||||
|
|
||||||
`llm.NewRuntime` assembles one captured PromptKit engine using its default
|
`internal/appconfig` assembles one shared result and bootstraps configured
|
||||||
catalog, Audita's embedded prompts and schemas, and optional operator sources
|
secrets before loading. `llm.NewRuntime` captures a PromptKit engine from that
|
||||||
anchored to the recorded application main context. Captured host sources and
|
result. Effective host sources and message files are passed to output collision
|
||||||
message files are passed to output collision checks. An embedded-only diagnostic
|
checks. Native errors and source evidence are retained for classification.
|
||||||
construction distinguishes shipped asset failures from operator-source failures;
|
|
||||||
it never replaces the requested engine.
|
|
||||||
|
|
||||||
Each resolved pipeline entry receives role-bound clients with its selected
|
Each resolved pipeline entry receives role-bound clients with its selected
|
||||||
profiles and effective budgets. Clients share engine-local backend admission.
|
profiles and effective budgets. Clients share engine-local backend admission.
|
||||||
The adapter uses ordinary `Run` with `OperationTimeout` and `OnPrepared`, passes
|
The adapter uses ordinary `Run` with `OperationTimeout` and `OnPrepared`, passes
|
||||||
Audita's per-call schema and repair budget, and decodes only validated results.
|
no per-call output override, and decodes the response after the selected prompt's
|
||||||
|
contract has been applied.
|
||||||
The operation budget includes preparation, admission, retries, and structural
|
The operation budget includes preparation, admission, retries, and structural
|
||||||
repair. An expired parent context stops processing and retains any native cause.
|
repair. An expired parent context stops processing and retains any native cause.
|
||||||
With an active parent, PromptKit's operation deadline remains recoverable even
|
With an active parent, PromptKit's operation deadline remains recoverable even
|
||||||
when a preparation error wraps it. A native transport timeout affects the HTTP
|
when a preparation error wraps it. A native transport timeout affects the HTTP
|
||||||
attempt and is recorded as a transport failure. The prepared notification
|
attempt and is recorded as a transport failure. The prepared notification
|
||||||
supplies prompt metadata to observers. With debug capture enabled, it also
|
supplies prompt metadata to observers. With debug capture enabled, it also
|
||||||
supplies the actual request messages when preparation reaches that point.
|
supplies the native prepared request, including the contract and message hash,
|
||||||
|
when preparation reaches that point.
|
||||||
PromptKit owns backend and credential selection. When a required credential is absent,
|
PromptKit owns backend and credential selection. When a required credential is absent,
|
||||||
the CLI identifies the role, profile, and environment variable using the native
|
the CLI identifies the role, profile, and environment variable using the native
|
||||||
diagnostic. See the [integration contract](../integrations/openai-compatible-llm.md)
|
diagnostic. See the [integration contract](../integrations/openai-compatible-llm.md)
|
||||||
@@ -28,8 +28,8 @@ and coordinator before submitting proposal work. The proposal call captures a
|
|||||||
native immutable PromptKit exchange. Each actionable correction starts an independent
|
native immutable PromptKit exchange. Each actionable correction starts an independent
|
||||||
`Engine.Coordinate` branch from that exchange. PromptKit assembles continuation
|
`Engine.Coordinate` branch from that exchange. PromptKit assembles continuation
|
||||||
history, owns the additional-turn budget, and delivers the last permitted response
|
history, owns the additional-turn budget, and delivers the last permitted response
|
||||||
for assessment. Follow-ups select the repair prompt, profile, and output schema
|
for assessment. Follow-ups select the repair prompt and profile; the prompt owns
|
||||||
directly; Audita does not rerender the original proposal or assemble replay messages.
|
its contract. Audita does not rerender the original proposal or assemble replay messages.
|
||||||
An opaque exchange in the structured-output contract keeps provider state outside
|
An opaque exchange in the structured-output contract keeps provider state outside
|
||||||
modules and validators. The adapter shares request construction, notifications,
|
modules and validators. The adapter shares request construction, notifications,
|
||||||
observers, and once-only completion between ordinary and coordinated calls.
|
observers, and once-only completion between ordinary and coordinated calls.
|
||||||
@@ -51,12 +51,11 @@ The bundled prompts separate durable system principles from the initial user
|
|||||||
assignment so later repair instructions can allow acceptable minor cleanup;
|
assignment so later repair instructions can allow acceptable minor cleanup;
|
||||||
see [prompt instruction ownership](prompts.md).
|
see [prompt instruction ownership](prompts.md).
|
||||||
|
|
||||||
The observation collector tracks logical calls and execution events, and enrolls
|
The optional debug collector tracks logical calls and native execution events,
|
||||||
selected runs in a native `ExecutionGroup`. Proposal, repair, and nested validator
|
and replays selected events into a native `ExecutionGroup`. The invocation
|
||||||
clients explicitly share the invocation observer; history reuse adds no extra run.
|
context also carries ckprompt's optional usage observer through proposal, repair,
|
||||||
Native summaries deduplicate terminal totals by run ID and retain terminal coverage
|
and nested validation. See the [PromptKit execution guide](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md)
|
||||||
separately from usage presence and completeness. Logical calls and run membership
|
for native observation and aggregation semantics.
|
||||||
can differ, especially on failures before execution.
|
|
||||||
|
|
||||||
Processing operations retain the failure class, reason, and underlying error.
|
Processing operations retain the failure class, reason, and underlying error.
|
||||||
When a client omits the reason, the operation uses `internal_failure` and keeps
|
When a client omits the reason, the operation uses `internal_failure` and keeps
|
||||||
|
|||||||
@@ -45,8 +45,8 @@ Module packages own:
|
|||||||
|
|
||||||
Each stage prepares the encoded glossary context and protected spellings once.
|
Each stage prepares the encoded glossary context and protected spellings once.
|
||||||
Proposal generation adds the selected transcript section and trimmed description
|
Proposal generation adds the selected transcript section and trimmed description
|
||||||
for each request. PromptKit renders the selected definition and validates the
|
for each request. PromptKit renders the selected definition and applies its
|
||||||
correction-set schema before Audita maps proposals. Domain validators still
|
output contract before Audita decodes and maps proposals. Domain validators still
|
||||||
check applicability, protected glossary terms, and replacement
|
check applicability, protected glossary terms, and replacement
|
||||||
policy. Model-facing segment IDs are one-based positions within the proposal
|
policy. Model-facing segment IDs are one-based positions within the proposal
|
||||||
request. Generation and repair map those references back to the current chunk's actual
|
request. Generation and repair map those references back to the current chunk's actual
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ baseline commands, see the [contributor guide](../development.md).
|
|||||||
Executable and command orchestration:
|
Executable and command orchestration:
|
||||||
- `cmd/audita`: executable entry point.
|
- `cmd/audita`: executable entry point.
|
||||||
- `internal/cli`: argument parsing, config commands, streams, filesystem wiring, and process orchestration.
|
- `internal/cli`: argument parsing, config commands, streams, filesystem wiring, and process orchestration.
|
||||||
|
- `internal/appconfig`: shared application and PromptKit source composition and secrets bootstrap.
|
||||||
|
|
||||||
Core deterministic components:
|
Core deterministic components:
|
||||||
- `internal/core/config`
|
- `internal/core/config`
|
||||||
@@ -67,7 +68,7 @@ artifact lifecycle.
|
|||||||
|
|
||||||
## Component Responsibilities
|
## Component Responsibilities
|
||||||
|
|
||||||
Core components implement configuration defaults, loading, and validation,
|
Core components implement reusable configuration defaults and validation,
|
||||||
transcript schemas and derived glossary views, normalization and chunking, output encoding,
|
transcript schemas and derived glossary views, normalization and chunking, output encoding,
|
||||||
diagnostics artifact helpers, and public report structures.
|
diagnostics artifact helpers, and public report structures.
|
||||||
|
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ PromptKit composes embedded defaults with operator prompt sources. Shared
|
|||||||
instructions come from the embedded fragments in `assets/shared`; the request
|
instructions come from the embedded fragments in `assets/shared`; the request
|
||||||
shared-variable helper fills absent `HardeningPolicy`, `ProposalContract`,
|
shared-variable helper fills absent `HardeningPolicy`, `ProposalContract`,
|
||||||
`RepairContract`, and `ValidationContract` variables. The processing adapter
|
`RepairContract`, and `ValidationContract` variables. The processing adapter
|
||||||
supplies the embedded instruction fragments for those names. Processing supplies
|
supplies the embedded instruction fragments for those names. Each prompt owns
|
||||||
Audita's response-schema contract separately.
|
its output contract and references the shared embedded schema assets.
|
||||||
The operator's prompt definition controls which variables its template uses.
|
The operator's prompt definition controls which variables its template uses.
|
||||||
|
|
||||||
Proposal focus and validator acceptance intentionally differ: minor editorial
|
Proposal focus and validator acceptance intentionally differ: minor editorial
|
||||||
@@ -46,7 +46,7 @@ includes `original_segment_text`; when the correction is applicable, it includes
|
|||||||
not an applied change. An inapplicable correction omits the resulting text and
|
not an applied change. An inapplicable correction omits the resulting text and
|
||||||
retains its findings and available source text. An operator replacement may use
|
retains its findings and available source text. An operator replacement may use
|
||||||
different variables.
|
different variables.
|
||||||
See the [upstream CLI reference](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/f369d6a78253b6e6fcb1e023fb2e9c3af1d20ff0/docs/cli.md)
|
See the [upstream CLI reference](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/v0.8.0/docs/cli.md)
|
||||||
for the standard preview, validation, and smoke commands.
|
for the standard preview, validation, and smoke commands.
|
||||||
|
|
||||||
The correction-set schema requires a string replacement and accepts an empty
|
The correction-set schema requires a string replacement and accepts an empty
|
||||||
@@ -58,13 +58,15 @@ rejection, not a structural schema error.
|
|||||||
`internal/framework/responseschema` remains the only embedded source for
|
`internal/framework/responseschema` remains the only embedded source for
|
||||||
`correction_set.v1.json`, `correction_repair.v1.json`, and
|
`correction_set.v1.json`, `correction_repair.v1.json`, and
|
||||||
`validator_decision_set.v1.json`. It exposes that
|
`validator_decision_set.v1.json`. It exposes that
|
||||||
filesystem to PromptKit and retains Audita's schema-key lookup. PromptKit's
|
filesystem and asset root to PromptKit; each selected prompt owns its output
|
||||||
|
contract. See the [native schema contract](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md) for schema resolution. PromptKit's
|
||||||
prepared execution supplies definition and rendered hashes; Audita does not
|
prepared execution supplies definition and rendered hashes; Audita does not
|
||||||
recompute or promise equality with hashes from the removed template renderer.
|
recompute or promise equality with hashes from the removed template renderer.
|
||||||
The small Audita registry records only prompt ID, source, and embedded path. Prepared runtime metadata belongs in diagnostics rather than the registry.
|
The small Audita registry records only prompt ID, source, and embedded path. Prepared runtime metadata belongs in diagnostics rather than the registry.
|
||||||
|
|
||||||
The structured-call contract carries prompt ID, string variables,
|
The structured-call contract carries prompt ID, string variables,
|
||||||
response-schema key, and logical-call attribution. Module and validator callers
|
and logical-call attribution. Audita decodes the response into its domain types
|
||||||
|
and applies domain validation. Module and validator callers
|
||||||
pass these values through the role-bound adapter. See the
|
pass these values through the role-bound adapter. See the
|
||||||
[LLM runtime](llm-runtime.md) for runtime assembly and
|
[LLM runtime](llm-runtime.md) for runtime assembly and
|
||||||
[configuration](../config.md) for operator-selected profiles.
|
[configuration](../config.md) for operator-selected profiles.
|
||||||
|
|||||||
@@ -71,14 +71,14 @@ LLM validators:
|
|||||||
- build canonical validation request payloads;
|
- build canonical validation request payloads;
|
||||||
- batch using `validation.max_prompt_tokens` and the existing domain token estimator;
|
- batch using `validation.max_prompt_tokens` and the existing domain token estimator;
|
||||||
- select an embedded prompt ID and pass payload/description variables to the
|
- select an embedded prompt ID and pass payload/description variables to the
|
||||||
role-bound structured client with the validator-decision schema.
|
role-bound structured client; the selected prompt supplies its output contract.
|
||||||
|
|
||||||
Oversized single inputs are rejected with a consolidated
|
Oversized single inputs are rejected with a consolidated
|
||||||
`validation_input_too_large` operation, without a provider call. Recoverable
|
`validation_input_too_large` operation, without a provider call. Recoverable
|
||||||
model failures make only their batch candidates unavailable while other
|
model failures make only their batch candidates unavailable while other
|
||||||
batches continue. PromptKit validates each complete response against the
|
batches continue. PromptKit applies the selected prompt's output contract before
|
||||||
validator-decision JSON Schema and performs configured structural repair before
|
Audita decodes decisions. Shipped validator prompts select the validator-decision
|
||||||
Audita receives decoded decisions. Each actual batch presents candidates
|
JSON Schema. Each actual batch presents candidates
|
||||||
numbered from 1, independent of their internal proposal indices. Audita then
|
numbered from 1, independent of their internal proposal indices. Audita then
|
||||||
reconciles those local references: one usable entry keeps its
|
reconciles those local references: one usable entry keeps its
|
||||||
approval or editorial rejection; a missing or duplicate requested entry makes
|
approval or editorial rejection; a missing or duplicate requested entry makes
|
||||||
|
|||||||
65
docs/migrations/v4.1.md
Normal file
65
docs/migrations/v4.1.md
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# Migrating to Audita v4.1
|
||||||
|
|
||||||
|
Audita v4.1 keeps application configuration version `3` and accepts existing
|
||||||
|
wrapperless `prompts.yml` and `prompts/` companions. It changes how structural
|
||||||
|
output contracts, configuration loading, inspection, and debug evidence work.
|
||||||
|
Review the following changes before upgrading scripts or operator prompts.
|
||||||
|
|
||||||
|
## Move structural-repair budgets to prompts
|
||||||
|
|
||||||
|
Remove `llm.repair_attempts` from the root and every pipeline entry. Audita no
|
||||||
|
longer accepts that setting or supplies an output contract at each call. The
|
||||||
|
selected PromptKit prompt now owns its `output` format, validation mode, schema,
|
||||||
|
and structural-repair budget. Shipped definitions omit `output.repair_attempts`;
|
||||||
|
the PromptKit v0.25.0 default for enabled validation is one additional generation,
|
||||||
|
where Audita previously defaulted to two. Set an explicit budget in a complete
|
||||||
|
replacement prompt when needed; zero disables structural repair for that prompt.
|
||||||
|
This is separate from Audita's `llm.correction_repair_attempts`, which controls
|
||||||
|
semantic correction repair, and from transient retries.
|
||||||
|
|
||||||
|
For a working replacement with `output.repair_attempts: 2`, see
|
||||||
|
[`examples/prompt-edit/prompts.yml`](../../examples/prompt-edit/prompts.yml).
|
||||||
|
The example retains the complete grammar proposal definition, including its
|
||||||
|
messages, format, validation mode, and schema path. A same-ID replacement is a
|
||||||
|
whole record, not a field patch. Former per-entry budgets have no automatic
|
||||||
|
one-to-one conversion: select or define prompts with budgets appropriate to each
|
||||||
|
use. See the [PromptKit format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md)
|
||||||
|
for prompt contracts and the [Audita prompt guide](../internal/prompts.md) for
|
||||||
|
required request variables and response shapes.
|
||||||
|
|
||||||
|
Audita no longer replaces an operator prompt's output contract with its own
|
||||||
|
schema. Make operator proposal, validator, and repair prompts produce the
|
||||||
|
appropriate Audita response shapes. Responses that pass a weaker contract but
|
||||||
|
cannot be decoded into the expected JSON types become recoverable invalid-output
|
||||||
|
failures for that operation; domain validation still applies.
|
||||||
|
|
||||||
|
## Update inspection and diagnostics consumers
|
||||||
|
|
||||||
|
The shared application configuration includes native settings under `/promptkit`.
|
||||||
|
Use these paths when inspecting the application scope; the separate PromptKit
|
||||||
|
scope remains available. Existing wrapperless companions are mounted at that
|
||||||
|
path, while main files and overlays can use a `promptkit` section. Configuration
|
||||||
|
inspection now validates the shared result and may run configured secrets
|
||||||
|
bootstrap. See [configuration](../config.md#loading-and-composition).
|
||||||
|
|
||||||
|
Debug `llm-execution.json` retains `summary`, `calls`, and `events`, with native
|
||||||
|
PromptKit evidence nested under `promptkit`. Prepared interaction request payloads
|
||||||
|
also include native contract, schema, and message-hash evidence under that key.
|
||||||
|
Update scripts that read the former projected metric fields; native field names
|
||||||
|
and duration representations differ. Ordinary reports retain their schemas.
|
||||||
|
Native smoke reports now default to text; scripts consuming structured output
|
||||||
|
should request `--format yaml` or `--format json`. See the
|
||||||
|
[CLI reference](../cli.md#inspection-and-outcomes) and
|
||||||
|
[debug output contract](../integrations/output-files.md#debug-only-files).
|
||||||
|
|
||||||
|
## Review startup failures
|
||||||
|
|
||||||
|
Application and PromptKit resources now share configuration loading and
|
||||||
|
validation. Invalid native configuration can be reported during application
|
||||||
|
inspection as well as processing; native configuration usage errors are
|
||||||
|
classified as status `2`, while unclassified runtime preparation and bootstrap
|
||||||
|
failures are status `1`. A failed
|
||||||
|
bootstrap occurs before transcript and output preparation. Help, version, and
|
||||||
|
other help-only paths do not perform the load. See [subprocess integration](../integrations/subprocess.md)
|
||||||
|
for handling results and [ConfigKit bootstrap documentation](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md)
|
||||||
|
for the native controls.
|
||||||
@@ -27,6 +27,11 @@ these sources before running with sensitive transcript data. Native inspection
|
|||||||
describes the loaded configuration and resources. Processing readiness also
|
describes the loaded configuration and resources. Processing readiness also
|
||||||
depends on the profiles and glossaries selected by the pipeline. See
|
depends on the profiles and glossaries selected by the pipeline. See
|
||||||
[configuration loading](config.md#loading-and-composition) for discovery rules.
|
[configuration loading](config.md#loading-and-composition) for discovery rules.
|
||||||
|
Configured secrets bootstrap runs before the shared load for processing and
|
||||||
|
native inspection. If it fails, processing stops before transcript and output
|
||||||
|
preparation; its safe diagnostic details are reported on stderr. Follow the
|
||||||
|
[ConfigKit documentation](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md)
|
||||||
|
for bootstrap configuration and environment effects.
|
||||||
|
|
||||||
## Outputs and lifecycle
|
## Outputs and lifecycle
|
||||||
|
|
||||||
@@ -38,7 +43,7 @@ requires a transcript file or `/dev/null`; it suppresses optional messages, not
|
|||||||
failures. Stdout carries transcript JSON when selected.
|
failures. Stdout carries transcript JSON when selected.
|
||||||
|
|
||||||
Before processing, Audita checks destination collisions against the transcript,
|
Before processing, Audita checks destination collisions against the transcript,
|
||||||
consumed application and PromptKit sources, and effective host message files. An
|
consumed application and PromptKit sources, and effective host message and schema files. An
|
||||||
intentional in-place transcript replacement is allowed. A regular transcript
|
intentional in-place transcript replacement is allowed. A regular transcript
|
||||||
output is prepared in a sibling temporary file, leaving the final destination
|
output is prepared in a sibling temporary file, leaving the final destination
|
||||||
untouched until successful publication. Pipes and devices are opened only for
|
untouched until successful publication. Pipes and devices are opened only for
|
||||||
@@ -68,6 +73,8 @@ Use `--progress` to follow stage, chunk, proposal, validation, and repair
|
|||||||
activity on stderr. Report and transcript files provide the retained outcome.
|
activity on stderr. Report and transcript files provide the retained outcome.
|
||||||
Debug mode enables live progress by default. Use `--progress=false` to keep
|
Debug mode enables live progress by default. Use `--progress=false` to keep
|
||||||
debug evidence with progress disabled.
|
debug evidence with progress disabled.
|
||||||
|
The optional native `--show-tokens` report is independent of debug and ordinary
|
||||||
|
reports; see the [CLI reference](cli.md#processing).
|
||||||
|
|
||||||
## Debug evidence
|
## Debug evidence
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,10 @@
|
|||||||
|
|
||||||
Material: All documents under `docs/policy/`, root `AGENTS.md`, and the Policy
|
Material: All documents under `docs/policy/`, root `AGENTS.md`, and the Policy
|
||||||
Reading Guide in `docs/development.md`, adapted for this repository.
|
Reading Guide in `docs/development.md`, adapted for this repository.
|
||||||
`docs/policy/documentation.md`, `docs/policy/oss.md`, and `docs/policy/release.md`
|
`docs/policy/documentation.md` incorporates revision
|
||||||
incorporate revision `593c9b52273c5c879785ae9e995d21026df467b4`.
|
`5b9088601290564647a9e20c13f95c0da9f4cb15`.
|
||||||
|
`docs/policy/oss.md` and `docs/policy/release.md` incorporate revision
|
||||||
|
`593c9b52273c5c879785ae9e995d21026df467b4`.
|
||||||
The remaining listed material incorporates revision
|
The remaining listed material incorporates revision
|
||||||
`d84a38ebab26f048cafbe59a2246700c35d29843`.
|
`d84a38ebab26f048cafbe59a2246700c35d29843`.
|
||||||
|
|
||||||
@@ -17,15 +19,19 @@ License and notices: [CC BY-SA 4.0](licenses/CC-BY-SA-4.0.txt) |
|
|||||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/COPYRIGHT) |
|
||||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE) |
|
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE) |
|
||||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/COPYRIGHT) |
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/COPYRIGHT) |
|
||||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/LICENSE).
|
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/LICENSE) |
|
||||||
|
[COPYRIGHT](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15/COPYRIGHT) |
|
||||||
|
[LICENSE](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15/LICENSE).
|
||||||
|
|
||||||
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
|
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843).
|
||||||
|
|
||||||
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4).
|
[Source](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4).
|
||||||
|
|
||||||
|
[Source](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15).
|
||||||
|
|
||||||
## ConfigKit
|
## ConfigKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/configkit` at `v1.2.1`.
|
Selected module: `go.maximumdirect.net/configkit` at `v1.4.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
@@ -33,9 +39,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
|||||||
|
|
||||||
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||||
[GPL v3](licenses/GPL-3.0.txt) |
|
[GPL v3](licenses/GPL-3.0.txt) |
|
||||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b/COPYRIGHT).
|
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/COPYRIGHT).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/51ef3144158db1a09fabdbd1c7ae59908c84923b).
|
[Source](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3).
|
||||||
|
|
||||||
## ReleaseKit
|
## ReleaseKit
|
||||||
|
|
||||||
@@ -59,7 +65,7 @@ License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
|||||||
|
|
||||||
## CommandKit
|
## CommandKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/commandkit` at `v0.7.0`.
|
Selected module: `go.maximumdirect.net/commandkit` at `v0.8.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
@@ -67,13 +73,13 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
|||||||
|
|
||||||
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||||
[GPL v3](licenses/GPL-3.0.txt) |
|
[GPL v3](licenses/GPL-3.0.txt) |
|
||||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/b57bfe176cff05a892e6cb07ebb5f350239e55d4/COPYRIGHT).
|
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/0b53a63648c536afe50c46f948159116f776adae/COPYRIGHT).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/b57bfe176cff05a892e6cb07ebb5f350239e55d4).
|
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/0b53a63648c536afe50c46f948159116f776adae).
|
||||||
|
|
||||||
## CommandKit ckconfig
|
## CommandKit ckconfig
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/ckconfig` at `v0.9.0`.
|
Selected module: `go.maximumdirect.net/ckconfig` at `v0.11.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
@@ -81,13 +87,13 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
|||||||
|
|
||||||
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||||
[GPL v3](licenses/GPL-3.0.txt) |
|
[GPL v3](licenses/GPL-3.0.txt) |
|
||||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/9962368f0c1ea1f6ad010638e94621091105d745/integrations/ckconfig/COPYRIGHT).
|
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/cd5cf483a46caeff7ca0a91fb4747d57188a3888/integrations/ckconfig/COPYRIGHT).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/9962368f0c1ea1f6ad010638e94621091105d745).
|
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/cd5cf483a46caeff7ca0a91fb4747d57188a3888).
|
||||||
|
|
||||||
## CommandKit ckprompt
|
## CommandKit ckprompt
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/ckprompt` at `v0.10.0`.
|
Selected module: `go.maximumdirect.net/ckprompt` at `v0.12.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
@@ -95,9 +101,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
|||||||
|
|
||||||
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||||
[GPL v3](licenses/GPL-3.0.txt) |
|
[GPL v3](licenses/GPL-3.0.txt) |
|
||||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/c9a56e1b15f2169881a91fca4e1f4a1c475e057a/integrations/ckprompt/COPYRIGHT).
|
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2422ccf02d6b55756b07f21e66a581202a09fc3f/integrations/ckprompt/COPYRIGHT).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/c9a56e1b15f2169881a91fca4e1f4a1c475e057a).
|
[Source](https://forge.maximumdirect.net/base-layer/commandkit/src/commit/2422ccf02d6b55756b07f21e66a581202a09fc3f).
|
||||||
|
|
||||||
## Go runtime and standard library
|
## Go runtime and standard library
|
||||||
|
|
||||||
@@ -213,7 +219,7 @@ License and notices: [Apache 2.0](licenses/Apache-2.0.txt).
|
|||||||
|
|
||||||
## PromptKit
|
## PromptKit
|
||||||
|
|
||||||
Selected module: `go.maximumdirect.net/promptkit` at `v0.23.2`.
|
Selected module: `go.maximumdirect.net/promptkit` at `v0.25.0`.
|
||||||
|
|
||||||
Copyright (C) 2026 Eric Rakestraw
|
Copyright (C) 2026 Eric Rakestraw
|
||||||
|
|
||||||
@@ -221,9 +227,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
|||||||
|
|
||||||
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||||
[GPL v3](licenses/GPL-3.0.txt) |
|
[GPL v3](licenses/GPL-3.0.txt) |
|
||||||
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71/COPYRIGHT).
|
[COPYRIGHT](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d/COPYRIGHT).
|
||||||
|
|
||||||
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/382ccfb14b9630fd8f48c8364dbe2b6159637d71).
|
[Source](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/207677e9948dc5699073a4d6620d21139033c72d).
|
||||||
|
|
||||||
## Cobra
|
## Cobra
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
# Documentation Policy
|
# Documentation Policy
|
||||||
|
|
||||||
**Base Policy Version:** 1.12
|
**Base Policy Version:** 1.13
|
||||||
|
|
||||||
**Last Updated**: 2026-11-11
|
**Last Updated**: 2026-11-22
|
||||||
**Upstream Source:** [Standard Repository Policies documentation](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/docs/policy/documentation.md)
|
**Upstream Source:** [Standard Repository Policies documentation](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15/docs/policy/documentation.md)
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
|
|
||||||
@@ -132,6 +132,15 @@ semantics. Internal documents explain how this application implements or consume
|
|||||||
contracts. Internal docs may name a field, file, or protocol to identify a
|
contracts. Internal docs may name a field, file, or protocol to identify a
|
||||||
dependency, but must link to its canonical contract for the definition.
|
dependency, but must link to its canonical contract for the definition.
|
||||||
|
|
||||||
|
### Upstream Dependencies
|
||||||
|
|
||||||
|
When documenting an upstream dependency, identify the library and link to its
|
||||||
|
canonical documentation for its features and behavior. Maintain local
|
||||||
|
documentation for application-specific integration, configuration, and
|
||||||
|
adaptations. Brief summaries may orient readers; upstream documentation remains
|
||||||
|
the canonical reference for upstream behavior. Where behavior differs by
|
||||||
|
version, link to documentation applicable to the imported version.
|
||||||
|
|
||||||
### Security Topics
|
### Security Topics
|
||||||
|
|
||||||
This policy owns what documentation and examples may contain. Architecture owns
|
This policy owns what documentation and examples may contain. Architecture owns
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
# Release Notes
|
# Release Notes
|
||||||
|
|
||||||
|
- [Audita v4.1.0](v4.1.0.md)
|
||||||
- [Audita v4.0.0](v4.0.0.md)
|
- [Audita v4.0.0](v4.0.0.md)
|
||||||
- [Audita v3.1.1](v3.1.1.md)
|
- [Audita v3.1.1](v3.1.1.md)
|
||||||
- [Audita v3.1.0](v3.1.0.md)
|
- [Audita v3.1.0](v3.1.0.md)
|
||||||
|
|||||||
38
docs/releases/v4.1.0.md
Normal file
38
docs/releases/v4.1.0.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# Audita v4.1.0
|
||||||
|
|
||||||
|
Audita v4.1.0 upgrades ConfigKit, PromptKit, CommandKit, and their configuration
|
||||||
|
and prompt integrations. Application and prompt settings now share one load,
|
||||||
|
with configured secrets bootstrap available before processing and native
|
||||||
|
inspection. The new `--show-tokens` option reports observed PromptKit usage
|
||||||
|
without requiring debug artifacts or ordinary reports.
|
||||||
|
|
||||||
|
## Upgrade action
|
||||||
|
|
||||||
|
Remove root and pipeline-entry `llm.repair_attempts` settings. Prompt definitions
|
||||||
|
now own their output contracts and structural-repair budgets; the shipped prompts'
|
||||||
|
omitted budget selects one additional generation for enabled validation, where
|
||||||
|
the previous Audita default was two. Operator replacement prompts must specify a
|
||||||
|
contract compatible with Audita's response shapes. The semantic correction-repair
|
||||||
|
budget remains separate. Follow the [v4.1 migration guide](../migrations/v4.1.md)
|
||||||
|
for a complete replacement example and conversion details.
|
||||||
|
|
||||||
|
The application configuration remains version 3, and wrapperless prompt
|
||||||
|
companions remain supported. Native PromptKit settings appear under `/promptkit`
|
||||||
|
in the shared application result. Configured secrets bootstrap can populate the
|
||||||
|
process environment during inspection or processing; bootstrap failures stop
|
||||||
|
before transcript and output preparation. Configuration error classification
|
||||||
|
follows the native diagnostics. See [configuration](../config.md) and
|
||||||
|
[subprocess integration](../integrations/subprocess.md).
|
||||||
|
|
||||||
|
Debug execution and prepared-request payloads now nest native PromptKit evidence
|
||||||
|
under `promptkit`; consumers of the former projected fields must update. Ordinary
|
||||||
|
report schemas are unchanged. Native smoke tests default to text; structured
|
||||||
|
consumers should request `--format yaml` or `--format json`. See the
|
||||||
|
[output contract](../integrations/output-files.md#debug-only-files) and
|
||||||
|
[CLI reference](../cli.md).
|
||||||
|
|
||||||
|
Source builds still require Go 1.27.0 or newer, and the Go module path remains
|
||||||
|
`gitea.maximumdirect.net/eric/audita/v4`. This release selects ConfigKit v1.4.0,
|
||||||
|
PromptKit v0.25.0, CommandKit v0.8.0, ckconfig v0.11.0, and ckprompt v0.12.0.
|
||||||
|
|
||||||
|
[COPYRIGHT](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/COPYRIGHT) | [LICENSE](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/LICENSE) | [ATTRIBUTION](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/docs/oss/attribution.md)
|
||||||
@@ -59,7 +59,11 @@ audita promptkit show prompt audita/modules.grammar.proposal --config config.yml
|
|||||||
|
|
||||||
Edit its message in `prompts.yml`, repeat the inspection, and run `audita process
|
Edit its message in `prompts.yml`, repeat the inspection, and run `audita process
|
||||||
--config config.yml --output corrected.json transcript.json` against a configured
|
--config config.yml --output corrected.json transcript.json` against a configured
|
||||||
local service. Each invocation captures the files anew.
|
local service. Its complete replacement also selects a structural-repair budget;
|
||||||
|
see the [v4.1 migration guide](../docs/migrations/v4.1.md). Each invocation captures
|
||||||
|
the files anew. For native resource formats and commands, see the
|
||||||
|
[PromptKit documentation](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md)
|
||||||
|
and [ckprompt guide](https://forge.maximumdirect.net/base-layer/commandkit/src/tag/integrations/ckprompt/v0.12.0/docs/consumers/guide.md).
|
||||||
|
|
||||||
## Shared glossary library
|
## Shared glossary library
|
||||||
|
|
||||||
|
|||||||
@@ -21,3 +21,4 @@ collections:
|
|||||||
format: json
|
format: json
|
||||||
validation_mode: json_schema
|
validation_mode: json_schema
|
||||||
schema_path: correction_set.v1.json
|
schema_path: correction_set.v1.json
|
||||||
|
repair_attempts: 2
|
||||||
|
|||||||
10
go.mod
10
go.mod
@@ -4,11 +4,11 @@ go 1.27.0
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
|
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
|
||||||
go.maximumdirect.net/ckconfig v0.9.0
|
go.maximumdirect.net/ckconfig v0.11.0
|
||||||
go.maximumdirect.net/ckprompt v0.10.0
|
go.maximumdirect.net/ckprompt v0.12.0
|
||||||
go.maximumdirect.net/commandkit v0.7.0
|
go.maximumdirect.net/commandkit v0.8.0
|
||||||
go.maximumdirect.net/configkit v1.2.1
|
go.maximumdirect.net/configkit v1.4.0
|
||||||
go.maximumdirect.net/promptkit v0.23.2
|
go.maximumdirect.net/promptkit v0.25.0
|
||||||
go.maximumdirect.net/releasekit v0.10.0
|
go.maximumdirect.net/releasekit v0.10.0
|
||||||
go.yaml.in/yaml/v4 v4.0.0
|
go.yaml.in/yaml/v4 v4.0.0
|
||||||
)
|
)
|
||||||
|
|||||||
20
go.sum
20
go.sum
@@ -13,16 +13,16 @@ github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
|||||||
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||||
github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
|
github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
|
||||||
github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
|
github.com/yuin/goldmark/v2 v2.1.16/go.mod h1:G6M4/qOFtfn01/o14BU1UR2Lo5N3S9Qo7xCuz/sHjGQ=
|
||||||
go.maximumdirect.net/ckconfig v0.9.0 h1:s9Ikga4wt4K1NpLCX9bLhm5vbcm1Fgqy9yk2lmO4Sss=
|
go.maximumdirect.net/ckconfig v0.11.0 h1:oTPW5R4vW5TNs97rqgABC/dir723rbGBz0FUyZ9QiNk=
|
||||||
go.maximumdirect.net/ckconfig v0.9.0/go.mod h1:yGjFVr2UzjJjiwDdMwsKehuQfvvtv7rTEOIk5NQOY00=
|
go.maximumdirect.net/ckconfig v0.11.0/go.mod h1:9phvXeLAgQSBKpJWqPyIQASKVJr0nRhiPMIQkfNhaRo=
|
||||||
go.maximumdirect.net/ckprompt v0.10.0 h1:t2UyWSke+bWH9aTDrw5/bteD+TO0y5LD0NWw0y2KniQ=
|
go.maximumdirect.net/ckprompt v0.12.0 h1:TPx4c0ohnG51F5eXk9SLHvkSKGNnWBhzkJAC5LdZCrE=
|
||||||
go.maximumdirect.net/ckprompt v0.10.0/go.mod h1:vx8lZnelASctQtyxY2yV4PuTZfLpE9EqDa+LPj3+SHM=
|
go.maximumdirect.net/ckprompt v0.12.0/go.mod h1:6DsEfIbKsFFzdAAV2TZD2LiwMvEG//s7zFOVe2wDvN0=
|
||||||
go.maximumdirect.net/commandkit v0.7.0 h1:toLDGhHoVe6gBX5HWuzQ/Joz0cBqEhJXolW21m3axBk=
|
go.maximumdirect.net/commandkit v0.8.0 h1:EBDjr7SvfgvVDsA2S95hkOhgZe7oGZdDvURDJxHyX48=
|
||||||
go.maximumdirect.net/commandkit v0.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
go.maximumdirect.net/commandkit v0.8.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
||||||
go.maximumdirect.net/configkit v1.2.1 h1:f+/6WjNl6CULbMr6ZSVwi4aty9rmuDfJlvpeU7I+HZM=
|
go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQD63o=
|
||||||
go.maximumdirect.net/configkit v1.2.1/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
||||||
go.maximumdirect.net/promptkit v0.23.2 h1:nE+Qqqbw5GN4PHD2e5OEWUHXcYkESZm3ryZVBsKWwFQ=
|
go.maximumdirect.net/promptkit v0.25.0 h1:vJOfxauwASllOSDceR2oypJ4NEwIh2s6F8dDexEzdM8=
|
||||||
go.maximumdirect.net/promptkit v0.23.2/go.mod h1:vPFg76VXcffP0JBFMS2WADCHwV5FYvO2O4bvIoiDlwc=
|
go.maximumdirect.net/promptkit v0.25.0/go.mod h1:o2axdkV11KTPDgk81i2vrJ66dtcedXRhau/Ko3YSZ4A=
|
||||||
go.maximumdirect.net/releasekit v0.10.0 h1:3GOgaIigXTkvYaRkntWZASE//2NTR1+IhkoKmt64aJo=
|
go.maximumdirect.net/releasekit v0.10.0 h1:3GOgaIigXTkvYaRkntWZASE//2NTR1+IhkoKmt64aJo=
|
||||||
go.maximumdirect.net/releasekit v0.10.0/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90=
|
go.maximumdirect.net/releasekit v0.10.0/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90=
|
||||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||||
|
|||||||
117
internal/appconfig/config.go
Normal file
117
internal/appconfig/config.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
// Package appconfig composes Audita and PromptKit configuration sources.
|
||||||
|
package appconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"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/prompts"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AssetError reports a failure to access an embedded application resource.
|
||||||
|
type AssetError struct{ Err error }
|
||||||
|
|
||||||
|
func (e *AssetError) Error() string { return e.Err.Error() }
|
||||||
|
func (e *AssetError) Unwrap() error { return e.Err }
|
||||||
|
|
||||||
|
func IsAssetError(err error) bool {
|
||||||
|
var target *AssetError
|
||||||
|
return errors.As(err, &target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Config combines Audita's root settings with native PromptKit settings.
|
||||||
|
type Config struct {
|
||||||
|
Application config.Config `yaml:",inline"`
|
||||||
|
PromptKit pk.Settings `yaml:"promptkit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const glossaryImports = `config:
|
||||||
|
imports:
|
||||||
|
- path: glossary.yml
|
||||||
|
required: false
|
||||||
|
destination: [glossary_collections]
|
||||||
|
- dir: glossary
|
||||||
|
required: false
|
||||||
|
recursive: true
|
||||||
|
pattern: ["*.yml", "*.yaml"]
|
||||||
|
destination: [glossary_collections]
|
||||||
|
`
|
||||||
|
|
||||||
|
const operatorImports = `config:
|
||||||
|
imports:
|
||||||
|
- path: prompts.yml
|
||||||
|
required: false
|
||||||
|
- dir: prompts
|
||||||
|
required: false
|
||||||
|
recursive: true
|
||||||
|
pattern: ["*.yml", "*.yaml"]
|
||||||
|
`
|
||||||
|
|
||||||
|
// Definition combines application rules with PromptKit's native rules.
|
||||||
|
func Definition() ck.Definition[Config] {
|
||||||
|
domain := config.Definition()
|
||||||
|
definition := ck.Definition[Config]{
|
||||||
|
Defaults: func() Config { return Config{Application: domain.Defaults()} },
|
||||||
|
Version: domain.Version,
|
||||||
|
SequenceIdentities: domain.SequenceIdentities,
|
||||||
|
Sensitive: domain.Sensitive,
|
||||||
|
Resolve: func(value *Config, resolution *ck.Resolution) error {
|
||||||
|
return domain.Resolve(&value.Application, resolution)
|
||||||
|
},
|
||||||
|
Validate: func(value *Config, validation *ck.Validation) {
|
||||||
|
domain.Validate(&value.Application, validation)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return pk.Configure(definition, func(value *Config) *pk.Settings { return &value.PromptKit })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load composes built-in resources and optional companions with the selected input.
|
||||||
|
func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], *ck.SecretsReport, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
report, prepared, err := ck.LoadSecretsIntoEnvironmentFromConfig(input.Source, ck.SecretsFromConfigOptions{Filesystem: input.Filesystem})
|
||||||
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
|
return nil, report, errors.Join(err, canceled)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, report, err
|
||||||
|
}
|
||||||
|
input.Source = prepared
|
||||||
|
embedded, err := pk.FilesystemInputs("Audita embedded prompts", prompts.Filesystem(), prompts.AssetRoot)
|
||||||
|
if err != nil {
|
||||||
|
return nil, report, &AssetError{Err: fmt.Errorf("discover embedded prompts: %w", err)}
|
||||||
|
}
|
||||||
|
for i := range embedded {
|
||||||
|
embedded[i].Destination = ck.Keys("promptkit")
|
||||||
|
}
|
||||||
|
schemas := ck.NewFilesystem("Audita embedded schemas", responseschema.Filesystem())
|
||||||
|
embedded = append(embedded, ck.Input{
|
||||||
|
Source: pk.SchemaRootSource("Audita embedded schemas", responseschema.AssetRoot),
|
||||||
|
Destination: ck.Keys("promptkit"),
|
||||||
|
Filesystem: &ck.FilesystemContext{FS: &schemas, Root: ".", BaseDir: "."},
|
||||||
|
})
|
||||||
|
input.Imports = true
|
||||||
|
result, err := ck.LoadLayered(input, ck.LayeredOptions[Config]{
|
||||||
|
Definition: Definition(),
|
||||||
|
Overlay: overlay,
|
||||||
|
Overrides: overrides,
|
||||||
|
Underlays: []ck.Underlay{
|
||||||
|
pk.BundledOpenRouterUnderlay(),
|
||||||
|
{Inputs: embedded},
|
||||||
|
{Inputs: []ck.Input{
|
||||||
|
{Source: ck.Bytes("Audita glossary imports", []byte(glossaryImports)), Imports: true, MainRelative: ck.MainRelative()},
|
||||||
|
{Source: ck.Bytes("Audita automatic prompt imports", []byte(operatorImports)), Destination: ck.Keys("promptkit"), Imports: true, MainRelative: ck.MainRelative()},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
|
return nil, report, errors.Join(err, canceled)
|
||||||
|
}
|
||||||
|
return result, report, err
|
||||||
|
}
|
||||||
77
internal/appconfig/config_test.go
Normal file
77
internal/appconfig/config_test.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
package appconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadCombinesApplicationAndPromptSettings(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for name, data := range map[string]string{
|
||||||
|
"config.yml": "version: 3\nllm:\n transient_retries: 4\n",
|
||||||
|
"prompts.yml": "profiles:\n - id: local\n model: fixture\ncollections:\n example:\n prompts:\n - id: sample\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n",
|
||||||
|
"message.txt": "A source-local message.",
|
||||||
|
"overlays/selected.yml": "context:\n description: overlay\n",
|
||||||
|
} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "selected")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Version != 3 || result.Config.Application.LLM.TransientRetries != 4 {
|
||||||
|
t.Fatalf("application settings: %+v", result.Config.Application)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Context.Description != "overlay" {
|
||||||
|
t.Fatalf("overlay description = %q", result.Config.Application.Context.Description)
|
||||||
|
}
|
||||||
|
settings, ok := result.Value(ck.Keys("promptkit"))
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("missing PromptKit settings")
|
||||||
|
}
|
||||||
|
if _, ok := settings.(pk.Settings); !ok {
|
||||||
|
t.Fatalf("PromptKit settings have type %T", settings)
|
||||||
|
}
|
||||||
|
engine, err := pk.NewFromConfig(result, pk.RuntimeConfig{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
prompt, err := engine.InspectPrompt(context.Background(), "example/sample")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("inspect source-local prompt: %v", err)
|
||||||
|
}
|
||||||
|
if len(prompt.Messages) != 1 || prompt.Messages[0].Content != "A source-local message." {
|
||||||
|
t.Fatalf("captured messages = %+v", prompt.Messages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadWithoutMainDoesNotDiscoverCompanions(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles: [\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Chdir(dir)
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Version != 3 {
|
||||||
|
t.Fatalf("version = %d", result.Config.Application.Version)
|
||||||
|
}
|
||||||
|
for _, source := range result.Sources() {
|
||||||
|
if strings.HasSuffix(source.Path, "prompts.yml") || strings.HasSuffix(source.Path, "glossary.yml") {
|
||||||
|
t.Fatalf("unexpected companion source: %+v", source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package config
|
package appconfig
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -48,25 +49,25 @@ party:
|
|||||||
`)
|
`)
|
||||||
write("shared/extra.yml", "lore:\n entries:\n - id: hero\n name: Ancient\n category: lore\n")
|
write("shared/extra.yml", "lore:\n entries:\n - id: hero\n name: Ancient\n category: lore\n")
|
||||||
write("glossary/nested/spells.yaml", "spells:\n entries:\n - id: bolt\n name: Bolt\n category: spell\n aliases: [Spark]\n plural: Bolts\n extra: {rank: 2}\n")
|
write("glossary/nested/spells.yaml", "spells:\n entries:\n - id: bolt\n name: Bolt\n category: spell\n aliases: [Spark]\n plural: Bolts\n extra: {rank: 2}\n")
|
||||||
result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics())
|
t.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics())
|
||||||
}
|
}
|
||||||
party := result.Config.GlossaryCollections["party"].Entries
|
party := result.Config.Application.GlossaryCollections["party"].Entries
|
||||||
if len(party) != 2 || party[0].Name != "Revised" || len(party[0].Aliases) != 0 || party[1].ID != "other" {
|
if len(party) != 2 || party[0].Name != "Revised" || len(party[0].Aliases) != 0 || party[1].ID != "other" {
|
||||||
t.Fatalf("party=%+v", party)
|
t.Fatalf("party=%+v", party)
|
||||||
}
|
}
|
||||||
if party[0].Extra["level"] == nil {
|
if party[0].Extra["level"] == nil {
|
||||||
t.Fatalf("extension missing: %+v", party[0])
|
t.Fatalf("extension missing: %+v", party[0])
|
||||||
}
|
}
|
||||||
if got := result.Config.GlossaryCollections["lore"].Entries; len(got) != 1 || got[0].ID != "hero" {
|
if got := result.Config.Application.GlossaryCollections["lore"].Entries; len(got) != 1 || got[0].ID != "hero" {
|
||||||
t.Fatalf("lore=%+v", got)
|
t.Fatalf("lore=%+v", got)
|
||||||
}
|
}
|
||||||
discovered, err := Load(ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "")
|
discovered, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "")
|
||||||
if err != nil || len(discovered.Config.GlossaryCollections["party"].Entries) != 2 {
|
if err != nil || len(discovered.Config.Application.GlossaryCollections["party"].Entries) != 2 {
|
||||||
t.Fatalf("discovered glossary: %+v %v", discovered, err)
|
t.Fatalf("discovered glossary: %+v %v", discovered, err)
|
||||||
}
|
}
|
||||||
spells := result.Config.GlossaryCollections["spells"].Entries
|
spells := result.Config.Application.GlossaryCollections["spells"].Entries
|
||||||
if len(spells) != 1 || spells[0].Plural == nil || *spells[0].Plural != "Bolts" || spells[0].Extra["extra"] == nil {
|
if len(spells) != 1 || spells[0].Plural == nil || *spells[0].Plural != "Bolts" || spells[0].Extra["extra"] == nil {
|
||||||
t.Fatalf("spells=%+v", spells)
|
t.Fatalf("spells=%+v", spells)
|
||||||
}
|
}
|
||||||
@@ -97,7 +98,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
|
|||||||
"glossary_collections:\n x:\n entries:\n - {id: 'id with spaces', name: N, category: C}\n",
|
"glossary_collections:\n x:\n entries:\n - {id: 'id with spaces', name: N, category: C}\n",
|
||||||
} {
|
} {
|
||||||
write(main, data)
|
write(main, data)
|
||||||
if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err != nil {
|
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err != nil {
|
||||||
t.Fatalf("valid %q: %v", data, err)
|
t.Fatalf("valid %q: %v", data, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -108,7 +109,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
|
|||||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, plural: ''}\n",
|
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, plural: ''}\n",
|
||||||
} {
|
} {
|
||||||
write(main, data)
|
write(main, data)
|
||||||
if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err == nil {
|
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err == nil {
|
||||||
t.Fatalf("accepted %q", data)
|
t.Fatalf("accepted %q", data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,7 +119,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
write(filepath.Join(dir, "glossary", "other.yml"), "x:\n entries:\n - {id: same, name: Two, category: C}\n")
|
write(filepath.Join(dir, "glossary", "other.yml"), "x:\n entries:\n - {id: same, name: Two, category: C}\n")
|
||||||
if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err == nil {
|
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, ""); err == nil {
|
||||||
t.Fatal("peer conflict accepted")
|
t.Fatal("peer conflict accepted")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,11 +130,11 @@ func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
t.Chdir(dir)
|
t.Chdir(dir)
|
||||||
result, err := Load(ck.Input{Source: ck.NoSource()}, "")
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(result.Config.GlossaryCollections) != 0 {
|
if len(result.Config.Application.GlossaryCollections) != 0 {
|
||||||
t.Fatalf("unanchored glossary loaded: %+v", result.Config.GlossaryCollections)
|
t.Fatalf("unanchored glossary loaded: %+v", result.Config.Application.GlossaryCollections)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
75
internal/appconfig/secrets_test.go
Normal file
75
internal/appconfig/secrets_test.go
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
package appconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLoadBootstrapsSecrets(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
secrets := filepath.Join(dir, "secrets")
|
||||||
|
if err := os.Mkdir(secrets, 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("AUDITA_TEST_BOOTSTRAP", "original")
|
||||||
|
if err := os.WriteFile(filepath.Join(secrets, "AUDITA_TEST_BOOTSTRAP"), []byte("synthetic"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
main := filepath.Join(dir, "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result == nil || os.Getenv("AUDITA_TEST_BOOTSTRAP") != "synthetic" || len(report.Entries()) != 1 || report.Entries()[0].Status != ck.SecretFileLoaded {
|
||||||
|
t.Fatalf("result=%v entries=%+v", result, report.Entries())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadRetainsBootstrapErrorAndCancellation(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
main := filepath.Join(dir, "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
|
var secretsErr *ck.SecretsError
|
||||||
|
if result != nil || report == nil || !errors.As(err, &secretsErr) {
|
||||||
|
t.Fatalf("result=%v report=%v error=%v", result, report, err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
result, _, err = Load(ctx, ck.Input{Source: ck.File(main)}, "")
|
||||||
|
if result != nil || !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("result=%v error=%v", result, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadReusesPreparedMainSnapshot(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
main := filepath.Join(dir, "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\ncontext:\n description: captured\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, prepared, err := ck.LoadSecretsIntoEnvironmentFromConfig(ck.File(main), ck.SecretsFromConfigOptions{Filesystem: &ck.FilesystemContext{Root: dir}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\ncontext:\n description: changed\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: prepared, Filesystem: &ck.FilesystemContext{Root: dir}}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Context.Description != "captured" {
|
||||||
|
t.Fatalf("loaded description = %q", result.Config.Application.Context.Description)
|
||||||
|
}
|
||||||
|
}
|
||||||
115
internal/appconfig/sources_test.go
Normal file
115
internal/appconfig/sources_test.go
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
package appconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestMainContextImportsAndOverlay(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"main.yml": "version: 3\nconfig:\n imports:\n - path: fragment.yml\noutput:\n schema: bare-segments\n",
|
||||||
|
"fragment.yml": "context:\n description: imported\n",
|
||||||
|
"overlays/selected.yml": "context:\n description: overlay\n",
|
||||||
|
} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "selected", ck.Override{Path: ck.Keys("context", "description"), Value: "override", Flag: "--description"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if info, ok := result.Metadata().Lookup(ck.Keys("context", "description")); !ok || info.Origin.Layer != ck.LayerCLI {
|
||||||
|
t.Fatalf("override origin = %+v", info)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Context.Description != "override" {
|
||||||
|
t.Fatalf("description = %q", result.Config.Application.Context.Description)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, source := range result.Sources() {
|
||||||
|
if source.Layer == ck.LayerMain && source.ImportedFrom == nil {
|
||||||
|
context, ok := result.SourceContext(source.ID)
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("main context missing")
|
||||||
|
}
|
||||||
|
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "fragment.yml"))
|
||||||
|
if err != nil || len(data) == 0 {
|
||||||
|
t.Fatalf("main context cannot access companion: %v", err)
|
||||||
|
}
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("main source missing")
|
||||||
|
}
|
||||||
|
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "missing"); err == nil {
|
||||||
|
t.Fatal("missing overlay accepted")
|
||||||
|
}
|
||||||
|
if _, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "selected"); err == nil {
|
||||||
|
t.Fatal("overlay without context accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDiscoveryAndSelectedFailure(t *testing.T) {
|
||||||
|
first, second := t.TempDir(), t.TempDir()
|
||||||
|
search := ck.Searches(ck.SearchDirectory(first), ck.SearchDirectory(second))
|
||||||
|
load := func() (*ck.Result[Config], error) {
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", search)}, "")
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
result, err := load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, source := range result.Sources() {
|
||||||
|
if source.Layer == ck.LayerMain {
|
||||||
|
t.Fatalf("unexpected main source: %+v", source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(second, "config.yml"), []byte("context:\n description: selected\n"), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, err = load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Context.Description != "selected" {
|
||||||
|
t.Fatalf("description = %q", result.Config.Application.Context.Description)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(first, "config.yml"), []byte("version: 2\n"), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := load(); err == nil {
|
||||||
|
t.Fatal("invalid selected file fell through")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOverlayUsesMainDirectoryWithinWiderRoot(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
dir := filepath.Join(root, "project")
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, "overlays"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "config.yml"), []byte("version: 3\n"), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "overlays", "local.yml"), []byte("context:\n description: project\n"), 0644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "local")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if result.Config.Application.Context.Description != "project" {
|
||||||
|
t.Fatalf("description = %q", result.Config.Application.Context.Description)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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/prompts"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||||
"go.maximumdirect.net/ckconfig"
|
"go.maximumdirect.net/ckconfig"
|
||||||
@@ -27,7 +27,7 @@ type engineEntry struct {
|
|||||||
engine *pk.Engine
|
engine *pk.Engine
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct{}, _ *invocationState) (*ck.Result[config.Config], error) {
|
func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct{}, _ *invocationState) (*ck.Result[appconfig.Config], error) {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -40,7 +40,8 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct
|
|||||||
} else {
|
} else {
|
||||||
source = ck.SearchConfig("audita", ck.Searches(ck.WorkingDirectory(), ck.UserConfigDirectory(), ck.UnixSystemDirectories()))
|
source = ck.SearchConfig("audita", ck.Searches(ck.WorkingDirectory(), ck.UserConfigDirectory(), ck.UnixSystemDirectories()))
|
||||||
}
|
}
|
||||||
return config.Load(ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...)
|
loaded, report, err := appconfig.Load(ctx, ck.Input{Source: source}, selection.Overlay.Value, selection.Overrides...)
|
||||||
|
return loaded, reportBootstrap(ctx, report, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) {
|
func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) {
|
||||||
@@ -80,7 +81,8 @@ func buildApplication(extra ...commandkit.Declaration) (*commandkit.App, error)
|
|||||||
func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) {
|
func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) {
|
||||||
appScope := ckconfig.FromConfigKit("app", "Audita application settings.", loadApplication)
|
appScope := ckconfig.FromConfigKit("app", "Audita application settings.", loadApplication)
|
||||||
appScope.Features.Overrides = true
|
appScope.Features.Overrides = true
|
||||||
promptScope := ckprompt.ConfigScope(loadPromptEngine)
|
appScope = withBootstrapContext(appScope)
|
||||||
|
promptScope := withBootstrapContext(ckprompt.ConfigScope(loadPromptEngine))
|
||||||
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}})
|
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}})
|
||||||
definitions := ckprompt.WithNamespaces(ckprompt.FromEngine(capturePromptEngine), pk.Namespaces{})
|
definitions := ckprompt.WithNamespaces(ckprompt.FromEngine(capturePromptEngine), pk.Namespaces{})
|
||||||
definitions.NewState = func() *invocationState { return &invocationState{client: client} }
|
definitions.NewState = func() *invocationState { return &invocationState{client: client} }
|
||||||
@@ -91,7 +93,8 @@ func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declara
|
|||||||
return applicationPromptRequest(seed.Request, seed.Namespaces), nil
|
return applicationPromptRequest(seed.Request, seed.Namespaces), nil
|
||||||
})
|
})
|
||||||
definitions = ckprompt.WithSmokeTesting(definitions, capturePromptEngine, nil)
|
definitions = ckprompt.WithSmokeTesting(definitions, capturePromptEngine, nil)
|
||||||
declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), processCommand()}
|
definitions = withPromptBootstrapContext(definitions)
|
||||||
|
declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), commandkit.WithInvocationFeature(processCommand(), bootstrapFeature())}
|
||||||
declarations = append(declarations, ckprompt.Declarations(definitions)...)
|
declarations = append(declarations, ckprompt.Declarations(definitions)...)
|
||||||
declarations = append(declarations, extra...)
|
declarations = append(declarations, extra...)
|
||||||
return commandkit.New(commandkit.Identity{Name: "audita", Version: buildinfo.Version()}, declarations...)
|
return commandkit.New(commandkit.Identity{Name: "audita", Version: buildinfo.Version()}, declarations...)
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -14,6 +15,7 @@ import (
|
|||||||
"go.maximumdirect.net/ckconfig"
|
"go.maximumdirect.net/ckconfig"
|
||||||
"go.maximumdirect.net/ckprompt"
|
"go.maximumdirect.net/ckprompt"
|
||||||
commandkit "go.maximumdirect.net/commandkit"
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -192,11 +194,15 @@ collections:
|
|||||||
t.Fatalf("validator status=%d out=%q err=%q", outcome.Status, out, stderr)
|
t.Fatalf("validator status=%d out=%q err=%q", outcome.Status, out, stderr)
|
||||||
}
|
}
|
||||||
validatorPreview := append([]string{"promptkit", "show", "prepared", "audita/validators.editorial_review"}, common...)
|
validatorPreview := append([]string{"promptkit", "show", "prepared", "audita/validators.editorial_review"}, common...)
|
||||||
validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=")
|
validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=", "--format=json")
|
||||||
outcome, out, stderr = execute(validatorPreview...)
|
outcome, out, stderr = execute(validatorPreview...)
|
||||||
if outcome.Status != 0 || !strings.Contains(out, "teh cat") {
|
if outcome.Status != 0 || !strings.Contains(out, "teh cat") {
|
||||||
t.Fatalf("validator preview status=%d out=%q err=%q", outcome.Status, out, stderr)
|
t.Fatalf("validator preview status=%d out=%q err=%q", outcome.Status, out, stderr)
|
||||||
}
|
}
|
||||||
|
var prepared pk.PreparedRun
|
||||||
|
if err := json.Unmarshal([]byte(out), &prepared); err != nil || prepared.MessageContentHash == "" || prepared.StructuredOutput == nil || prepared.OutputContract.SchemaPath == "" {
|
||||||
|
t.Fatalf("preview missing prepared contract or hash: %+v, error=%v, output=%s", prepared, err, out)
|
||||||
|
}
|
||||||
if calls != 0 {
|
if calls != 0 {
|
||||||
t.Fatalf("inspection made %d provider calls", calls)
|
t.Fatalf("inspection made %d provider calls", calls)
|
||||||
}
|
}
|
||||||
@@ -230,3 +236,38 @@ func TestRequestDefaultsRespectNamespaceAndCallerVariables(t *testing.T) {
|
|||||||
t.Fatalf("generic request changed: %v", result.Vars)
|
t.Fatalf("generic request changed: %v", result.Vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConfigurationBootstrapReportsAndPreservesFailure(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
secrets := filepath.Join(dir, "secrets")
|
||||||
|
if err := os.Mkdir(secrets, 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("AUDITA_BOOTSTRAP_TEST", "prior")
|
||||||
|
if err := os.WriteFile(filepath.Join(secrets, "AUDITA_BOOTSTRAP_TEST"), []byte("synthetic-secret"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
main := filepath.Join(dir, "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app, err := buildApplication()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out, stderr bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--verbose"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||||
|
if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_TEST") != "synthetic-secret" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_TEST") || strings.Contains(stderr.String(), "synthetic-secret") {
|
||||||
|
t.Fatalf("status=%d stdout=%q stderr=%q", result.Status, out.String(), stderr.String())
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
result = app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--quiet"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "synthetic-secret") {
|
||||||
|
t.Fatalf("status=%d cause=%v stdout=%q stderr=%q", result.Status, result.Cause, out.String(), stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
117
internal/cli/bootstrap.go
Normal file
117
internal/cli/bootstrap.go
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"go.maximumdirect.net/ckconfig"
|
||||||
|
"go.maximumdirect.net/ckprompt"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
type bootstrapReporterKey struct{}
|
||||||
|
|
||||||
|
func bootstrapFeature() commandkit.InvocationFeature {
|
||||||
|
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{
|
||||||
|
Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
|
||||||
|
return context.WithValue(inv.Context, bootstrapReporterKey{}, inv.Reporter()), nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type bootstrapError struct {
|
||||||
|
cause error
|
||||||
|
report *ck.SecretsReport
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *bootstrapError) Error() string {
|
||||||
|
var output bytes.Buffer
|
||||||
|
fmt.Fprintln(&output, e.cause)
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if errors.As(e.cause, &native) {
|
||||||
|
for _, diagnostic := range native.Diagnostics() {
|
||||||
|
fmt.Fprintf(&output, "%s: %s\n", diagnostic.Code, diagnostic.Message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e.report != nil {
|
||||||
|
_, _ = e.report.WriteTo(&output)
|
||||||
|
}
|
||||||
|
return output.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *bootstrapError) Unwrap() error { return e.cause }
|
||||||
|
|
||||||
|
func reportBootstrap(ctx context.Context, report *ck.SecretsReport, err error) error {
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if errors.As(err, &native) {
|
||||||
|
return &bootstrapError{cause: err, report: report}
|
||||||
|
}
|
||||||
|
if report != nil && len(report.Entries()) > 0 {
|
||||||
|
if reporter, ok := ctx.Value(bootstrapReporterKey{}).(*commandkit.Reporter); ok {
|
||||||
|
_ = reporter.Info("Secrets bootstrap", func(w io.Writer) error {
|
||||||
|
_, writeErr := report.WriteTo(w)
|
||||||
|
return writeErr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// withBootstrapContext retains safe bootstrap evidence in configuration outcomes.
|
||||||
|
func withBootstrapContext[I, S any](scope ckconfig.Scope[I, S]) ckconfig.Scope[I, S] {
|
||||||
|
acquire := scope.Acquire
|
||||||
|
scope.Acquire = func(ctx context.Context, request ckconfig.Request, input I, state S) (commandkit.Acquired[ckconfig.View], error) {
|
||||||
|
result, err := acquire(ctx, request, input, state)
|
||||||
|
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
compare := scope.Compare
|
||||||
|
scope.Compare = func(ctx context.Context, request ckconfig.ComparisonRequest[I], state S) (commandkit.Acquired[[]ck.Difference], error) {
|
||||||
|
result, err := compare(ctx, request, state)
|
||||||
|
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
return scope
|
||||||
|
}
|
||||||
|
|
||||||
|
func bootstrapExplanation(explanation commandkit.Explanation, err error) commandkit.Explanation {
|
||||||
|
var failure *bootstrapError
|
||||||
|
if errors.As(err, &failure) {
|
||||||
|
explanation.Details = append(explanation.Details, func(w io.Writer) error {
|
||||||
|
_, writeErr := io.WriteString(w, failure.Error())
|
||||||
|
return writeErr
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return explanation
|
||||||
|
}
|
||||||
|
|
||||||
|
func withBootstrapAcquisition[R, I, S, T any](load func(context.Context, R, I, S) (commandkit.Acquired[T], error)) func(context.Context, R, I, S) (commandkit.Acquired[T], error) {
|
||||||
|
if load == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return func(ctx context.Context, request R, input I, state S) (commandkit.Acquired[T], error) {
|
||||||
|
result, err := load(ctx, request, input, state)
|
||||||
|
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||||
|
return result, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func withPromptBootstrapContext[I, S any](suite ckprompt.Suite[I, S]) ckprompt.Suite[I, S] {
|
||||||
|
suite.InspectPrompt = withBootstrapAcquisition(suite.InspectPrompt)
|
||||||
|
suite.InspectProfile = withBootstrapAcquisition(suite.InspectProfile)
|
||||||
|
suite.InspectBackend = withBootstrapAcquisition(suite.InspectBackend)
|
||||||
|
suite.InspectRequirements = withBootstrapAcquisition(suite.InspectRequirements)
|
||||||
|
suite.ValidateRequest = withBootstrapAcquisition(suite.ValidateRequest)
|
||||||
|
suite.PrepareRequest = withBootstrapAcquisition(suite.PrepareRequest)
|
||||||
|
suite.SmokeTest = withBootstrapAcquisition(suite.SmokeTest)
|
||||||
|
suite.ListPrompts = withBootstrapAcquisition(suite.ListPrompts)
|
||||||
|
suite.ListProfiles = withBootstrapAcquisition(suite.ListProfiles)
|
||||||
|
suite.ListBackends = withBootstrapAcquisition(suite.ListBackends)
|
||||||
|
suite.ListNamespaces = withBootstrapAcquisition(suite.ListNamespaces)
|
||||||
|
suite.ListCollections = withBootstrapAcquisition(suite.ListCollections)
|
||||||
|
return suite
|
||||||
|
}
|
||||||
133
internal/cli/bootstrap_test.go
Normal file
133
internal/cli/bootstrap_test.go
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
|
"go.maximumdirect.net/ckconfig"
|
||||||
|
"go.maximumdirect.net/ckprompt"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBootstrapConfigurationOutcomes(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.Mkdir(filepath.Join(dir, "secrets"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("AUDITA_BOOTSTRAP_OUTCOME", "previous")
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "secrets", "AUDITA_BOOTSTRAP_OUTCOME"), []byte("private-value"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
main := filepath.Join(dir, "config.yml")
|
||||||
|
writeMain := func(directory string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: "+directory+"\n secrets_overwrite: true\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeMain("secrets")
|
||||||
|
loads := 0
|
||||||
|
load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*ck.Result[appconfig.Config], error) {
|
||||||
|
loads++
|
||||||
|
result, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "")
|
||||||
|
return result, reportBootstrap(ctx, report, err)
|
||||||
|
}
|
||||||
|
scope := withBootstrapContext(ckconfig.FromConfigKit("app", "Application settings", load))
|
||||||
|
command := ckconfig.Command(ckconfig.Suite[struct{}, struct{}]{Scopes: []ckconfig.Scope[struct{}, struct{}]{scope}})
|
||||||
|
app, err := commandkit.New(commandkit.Identity{Name: "test"}, commandkit.WithInvocationFeature(command, bootstrapFeature()))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
for _, args := range [][]string{{"--help"}, {"version"}, {"config", "show", "--help"}, {"config", "explain"}} {
|
||||||
|
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &stdout, Err: &stderr})
|
||||||
|
if outcome.Status != 0 || loads != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "previous" {
|
||||||
|
t.Fatalf("help %v: outcome=%+v loads=%d", args, outcome, loads)
|
||||||
|
}
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
}
|
||||||
|
result := app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: &stderr})
|
||||||
|
if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_OUTCOME") != "private-value" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_OUTCOME") || strings.Contains(stderr.String(), "private-value") {
|
||||||
|
t.Fatalf("success: status=%d stderr=%q", result.Status, stderr.String())
|
||||||
|
}
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
before := loads
|
||||||
|
result = app.Execute(context.Background(), []string{"config", "diff", "--scope=app", "--config", main, "--against-config", main}, commandkit.Streams{Out: &stdout, Err: &stderr})
|
||||||
|
if result.Status != 0 || loads-before != 2 {
|
||||||
|
t.Fatalf("comparison: status=%d acquisitions=%d stderr=%q", result.Status, loads-before, stderr.String())
|
||||||
|
}
|
||||||
|
failedWrite := errors.New("diagnostic destination failed")
|
||||||
|
stdout.Reset()
|
||||||
|
result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--verbose"}, commandkit.Streams{Out: &stdout, Err: bootstrapFailWriter{err: failedWrite}})
|
||||||
|
if result.Status != 1 || !errors.Is(result.Presentation.Diagnostics.WriteError, failedWrite) {
|
||||||
|
t.Fatalf("diagnostic write failure: %+v", result)
|
||||||
|
}
|
||||||
|
writeMain("missing")
|
||||||
|
stdout.Reset()
|
||||||
|
stderr.Reset()
|
||||||
|
result = app.Execute(context.Background(), []string{"config", "show", "--scope=app", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr})
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "private-value") {
|
||||||
|
t.Fatalf("failure: status=%d cause=%v stderr=%q", result.Status, result.Cause, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBootstrapPreservesJoinedCancellation(t *testing.T) {
|
||||||
|
main := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, report, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
|
joined := errors.Join(err, context.Canceled)
|
||||||
|
wrapped := reportBootstrap(context.Background(), report, joined)
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if !errors.As(wrapped, &native) || !errors.Is(wrapped, context.Canceled) {
|
||||||
|
t.Fatalf("cause = %v", wrapped)
|
||||||
|
}
|
||||||
|
explanation := bootstrapExplanation(commandkit.Explanation{}, wrapped)
|
||||||
|
var detail bytes.Buffer
|
||||||
|
if len(explanation.Details) != 1 {
|
||||||
|
t.Fatalf("details = %d", len(explanation.Details))
|
||||||
|
}
|
||||||
|
if err := explanation.Details[0](&detail); err != nil || !strings.Contains(detail.String(), "secrets.") {
|
||||||
|
t.Fatalf("detail = %q error = %v", detail.String(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPromptBootstrapFailureReportsTerminalDetails(t *testing.T) {
|
||||||
|
main := filepath.Join(t.TempDir(), "config.yml")
|
||||||
|
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*pk.Engine, error) {
|
||||||
|
_, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "")
|
||||||
|
return nil, reportBootstrap(ctx, report, err)
|
||||||
|
}
|
||||||
|
suite := withPromptBootstrapContext(ckprompt.FromEngine(load))
|
||||||
|
commands := ckprompt.Declarations(suite)
|
||||||
|
commands = append(commands, commandkit.WithInvocationFeature(commandkit.Group("auxiliary", ""), bootstrapFeature()))
|
||||||
|
app, err := commandkit.New(commandkit.Identity{Name: "test"}, commands...)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
outcome := app.Execute(context.Background(), []string{"promptkit", "list", "prompts", "--config", main, "--quiet"}, commandkit.Streams{Out: &stdout, Err: &stderr})
|
||||||
|
var native *ck.SecretsError
|
||||||
|
if outcome.Status != 1 || !errors.As(outcome.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") {
|
||||||
|
t.Fatalf("outcome=%+v stderr=%q", outcome, stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type bootstrapFailWriter struct{ err error }
|
||||||
|
|
||||||
|
func (w bootstrapFailWriter) Write([]byte) (int, error) { return 0, w.err }
|
||||||
@@ -14,10 +14,12 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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/llm"
|
||||||
|
auditaprompts "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||||
ck "go.maximumdirect.net/configkit"
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
||||||
@@ -33,15 +35,44 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
|||||||
} {
|
} {
|
||||||
t.Run(tc.dir+"/"+tc.main, func(t *testing.T) {
|
t.Run(tc.dir+"/"+tc.main, func(t *testing.T) {
|
||||||
main := filepath.Join(root, tc.dir, tc.main)
|
main := filepath.Join(root, tc.dir, tc.main)
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(main)}, tc.overlay)
|
if tc.dir == "service" {
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Mkdir(filepath.Join(dir, "secrets"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"config.yml", "prompts.yml", "overlays/testing.yml"} {
|
||||||
|
data, err := os.ReadFile(filepath.Join(root, tc.dir, name))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded.Config.Reporting.Enabled = false
|
if name == "config.yml" {
|
||||||
|
data = append(data, []byte("\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n")...)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, "secrets", "AUDITA_EXAMPLE_KEY"), []byte("synthetic-bootstrap-key"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Setenv("AUDITA_EXAMPLE_KEY", "")
|
||||||
|
main = filepath.Join(dir, "config.yml")
|
||||||
|
}
|
||||||
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, tc.overlay)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
loaded.Config.Application.Reporting.Enabled = false
|
||||||
var calls atomic.Int32
|
var calls atomic.Int32
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
var models, prompts []string
|
var models, prompts []string
|
||||||
transport := controlledTransport(func(r *http.Request) (*http.Response, error) {
|
transport := controlledTransport(func(r *http.Request) (*http.Response, error) {
|
||||||
|
if tc.dir == "service" && r.Header.Get("Authorization") != "Bearer synthetic-bootstrap-key" {
|
||||||
|
t.Errorf("bootstrap credential was not supplied")
|
||||||
|
}
|
||||||
calls.Add(1)
|
calls.Add(1)
|
||||||
var request struct {
|
var request struct {
|
||||||
Model string `json:"model"`
|
Model string `json:"model"`
|
||||||
@@ -83,12 +114,18 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
|||||||
if _, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil); err != nil {
|
if _, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if int(calls.Load()) != len(loaded.Config.Pipeline.Stages) {
|
if int(calls.Load()) != len(loaded.Config.Application.Pipeline.Stages) {
|
||||||
t.Fatalf("provider calls=%d", calls.Load())
|
t.Fatalf("provider calls=%d", calls.Load())
|
||||||
}
|
}
|
||||||
if tc.dir == "service" && (len(models) != 1 || models[0] != "example-testing-model") {
|
if tc.dir == "service" && (len(models) != 1 || models[0] != "example-testing-model") {
|
||||||
t.Fatalf("overlay models=%v", models)
|
t.Fatalf("overlay models=%v", models)
|
||||||
}
|
}
|
||||||
|
if tc.dir == "prompt-edit" {
|
||||||
|
prepared, err := engine.Engine.Prepare(context.Background(), pk.RunRequest{PromptID: auditaprompts.PromptIDModuleGrammarProposal, ProfileID: "local", Vars: auditaprompts.WithSharedVariables(map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"})})
|
||||||
|
if err != nil || prepared.OutputContract.RepairAttempts != 2 || prepared.StructuredOutput == nil || len(prepared.Messages) != 2 {
|
||||||
|
t.Fatalf("replacement contract: %+v, error=%v", prepared, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
if tc.dir == "campaigns" && tc.main == "first.yml" {
|
if tc.dir == "campaigns" && tc.main == "first.yml" {
|
||||||
if len(prompts) != 3 || !strings.Contains(prompts[0], `"name": "Lyra"`) || strings.Contains(prompts[0], `"name": "Shield"`) || !strings.Contains(prompts[1], `"name": "Shield"`) || strings.Contains(prompts[1], `"name": "Lyra"`) {
|
if len(prompts) != 3 || !strings.Contains(prompts[0], `"name": "Lyra"`) || strings.Contains(prompts[0], `"name": "Shield"`) || !strings.Contains(prompts[1], `"name": "Shield"`) || strings.Contains(prompts[1], `"name": "Lyra"`) {
|
||||||
t.Fatalf("campaign glossary selections: %v", prompts)
|
t.Fatalf("campaign glossary selections: %v", prompts)
|
||||||
@@ -120,7 +157,7 @@ func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
inspect := func() string {
|
inspect := func() string {
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization"
|
||||||
"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"
|
||||||
@@ -37,7 +37,15 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
|
|||||||
}
|
}
|
||||||
return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(err)
|
return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(err)
|
||||||
}
|
}
|
||||||
if inv.Context.Err() != nil || llm.IsAssetError(err) {
|
var secretsErr *bootstrapError
|
||||||
|
if errors.As(err, &secretsErr) {
|
||||||
|
return commandkit.Failure(secretsErr.Error()).WithCause(err)
|
||||||
|
}
|
||||||
|
var runtimeErr *runtimePreparationError
|
||||||
|
if errors.As(err, &runtimeErr) {
|
||||||
|
return commandkit.Failure(err.Error()).WithCause(err)
|
||||||
|
}
|
||||||
|
if inv.Context.Err() != nil || appconfig.IsAssetError(err) {
|
||||||
return commandkit.Failure("Could not prepare processing.").WithCause(err)
|
return commandkit.Failure("Could not prepare processing.").WithCause(err)
|
||||||
}
|
}
|
||||||
return commandkit.Usage(err.Error()).WithCause(err)
|
return commandkit.Usage(err.Error()).WithCause(err)
|
||||||
@@ -65,7 +73,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
|
|||||||
warn(debug.WriteSourceTranscript(loaded.Source, loaded.RawTranscript))
|
warn(debug.WriteSourceTranscript(loaded.Source, loaded.RawTranscript))
|
||||||
}
|
}
|
||||||
loaded.RawTranscript = nil
|
loaded.RawTranscript = nil
|
||||||
cfg := &loaded.Configuration.Config
|
cfg := &loaded.Configuration.Config.Application
|
||||||
normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{
|
normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{
|
||||||
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
|
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
|
||||||
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,
|
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
|
||||||
coreio "gitea.maximumdirect.net/eric/audita/v4/internal/core/io"
|
coreio "gitea.maximumdirect.net/eric/audita/v4/internal/core/io"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
||||||
@@ -26,13 +26,18 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type processInputs struct {
|
type processInputs struct {
|
||||||
Configuration *ck.Result[config.Config]
|
Configuration *ck.Result[appconfig.Config]
|
||||||
Runtime *llm.Runtime
|
Runtime *llm.Runtime
|
||||||
Source *schema.SourceTranscript
|
Source *schema.SourceTranscript
|
||||||
RawTranscript []byte
|
RawTranscript []byte
|
||||||
ProtectedPaths []string
|
ProtectedPaths []string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type runtimePreparationError struct{ cause error }
|
||||||
|
|
||||||
|
func (e *runtimePreparationError) Error() string { return e.cause.Error() }
|
||||||
|
func (e *runtimePreparationError) Unwrap() error { return e.cause }
|
||||||
|
|
||||||
func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) {
|
func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) {
|
||||||
if mode == commandkit.ReportingModeQuiet && input.Output.Value == "" {
|
if mode == commandkit.ReportingModeQuiet && input.Output.Value == "" {
|
||||||
return nil, fmt.Errorf("quiet processing requires an output file or /dev/null")
|
return nil, fmt.Errorf("quiet processing requires an output file or /dev/null")
|
||||||
@@ -44,7 +49,7 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.
|
|||||||
}
|
}
|
||||||
runtime, err := llm.NewRuntime(ctx, loaded, nil)
|
runtime, err := llm.NewRuntime(ctx, loaded, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, &runtimePreparationError{cause: err}
|
||||||
}
|
}
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -80,7 +85,7 @@ type preparedProcess struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) {
|
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) {
|
||||||
cfg := &loaded.Configuration.Config
|
cfg := &loaded.Configuration.Config.Application
|
||||||
reportDir := ""
|
reportDir := ""
|
||||||
reportDirSet := false
|
reportDirSet := false
|
||||||
for _, override := range input.Overrides {
|
for _, override := range input.Overrides {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
|
||||||
"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/llm"
|
||||||
@@ -101,7 +101,7 @@ pipeline:
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -114,8 +114,8 @@ pipeline:
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
||||||
loaded.Config.Diagnostics.WorkDir = dir
|
loaded.Config.Application.Diagnostics.WorkDir = dir
|
||||||
loaded.Config.Reporting.StdoutDir = dir
|
loaded.Config.Application.Reporting.StdoutDir = dir
|
||||||
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(dir, "transcript.json"), Debug: commandkit.Supplied[bool]{Value: true}}, inputs, &bytes.Buffer{})
|
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(dir, "transcript.json"), Debug: commandkit.Supplied[bool]{Value: true}}, inputs, &bytes.Buffer{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -213,7 +213,7 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -229,7 +229,7 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
||||||
loaded.Config.Reporting.StdoutDir = dir
|
loaded.Config.Application.Reporting.StdoutDir = dir
|
||||||
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(dir, "transcript.json")}, inputs, &bytes.Buffer{})
|
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(dir, "transcript.json")}, inputs, &bytes.Buffer{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func executePipeline(ctx context.Context, loaded *processInputs, prepared *preparedProcess, normalized *schema.Transcript, warn func(error), progress func(string)) (processResult, error) {
|
func executePipeline(ctx context.Context, loaded *processInputs, prepared *preparedProcess, normalized *schema.Transcript, warn func(error), progress func(string)) (processResult, error) {
|
||||||
cfg := &loaded.Configuration.Config
|
cfg := &loaded.Configuration.Config.Application
|
||||||
specs := prepared.Prepared.Specs
|
specs := prepared.Prepared.Specs
|
||||||
debug := prepared.Prepared.Debug
|
debug := prepared.Prepared.Debug
|
||||||
evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil}
|
evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil}
|
||||||
|
|||||||
@@ -60,6 +60,19 @@ func TestMalformedCompanionReturnsInputFailure(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRuntimePreparationFailureIsOperational(t *testing.T) {
|
||||||
|
main := writeRuntimeErrorConfig(t, "collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages:\n - role: user\n content: '{{'\n output:\n format: text\n validation_mode: none\n")
|
||||||
|
transcript := filepath.Join(filepath.Dir(main), "transcript.json")
|
||||||
|
if err := os.WriteFile(transcript, []byte("[]\n"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
status := Run(context.Background(), []string{"process", transcript, "--config", main}, &stdout, &stderr)
|
||||||
|
if status != 1 || stdout.Len() != 0 {
|
||||||
|
t.Fatalf("runtime error: status=%d stdout=%q stderr=%q", status, stdout.String(), stderr.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestUnreadableCompanionReturnsOperationalFailure(t *testing.T) {
|
func TestUnreadableCompanionReturnsOperationalFailure(t *testing.T) {
|
||||||
main := writeRuntimeErrorConfig(t, "profiles: []\n")
|
main := writeRuntimeErrorConfig(t, "profiles: []\n")
|
||||||
companion := filepath.Join(filepath.Dir(main), "prompts.yml")
|
companion := filepath.Join(filepath.Dir(main), "prompts.yml")
|
||||||
|
|||||||
72
internal/cli/schema_collision_test.go
Normal file
72
internal/cli/schema_collision_test.go
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
package cli
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
commandkit "go.maximumdirect.net/commandkit"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestProcessingProtectsOperatorSchemas(t *testing.T) {
|
||||||
|
for _, mode := range []string{"transcript", "report", "separate"} {
|
||||||
|
t.Run(mode, func(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
var calls atomic.Int32
|
||||||
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
calls.Add(1)
|
||||||
|
fmt.Fprint(w, `{"choices":[{"message":{"content":"{\"corrections\":[]}"}}]}`)
|
||||||
|
}))
|
||||||
|
defer server.Close()
|
||||||
|
schemaName := "contract.json"
|
||||||
|
if mode == "report" {
|
||||||
|
schemaName = "errors.yml"
|
||||||
|
}
|
||||||
|
schema := filepath.Join(dir, schemaName)
|
||||||
|
original := `{"type":"object","required":["corrections"],"properties":{"corrections":{"type":"array"}}}`
|
||||||
|
files := map[string]string{
|
||||||
|
"config.yml": "version: 3\nllm: {proposal_profile: fixture}\npipeline:\n stages: [{module: grammar}]\n",
|
||||||
|
"input.json": `[{"speaker":"Alice","start":0,"end":1,"text":"Hello."}]`,
|
||||||
|
schemaName: original,
|
||||||
|
"prompts.yml": fmt.Sprintf("profiles:\n - id: fixture\n endpoint: %s/v1\n model: test\n api_key_required: false\ncollections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: [{role: user, content: Return an empty correction set.}]\n output:\n format: json\n validation_mode: json_schema\n schema_file: %s\n", server.URL, schemaName),
|
||||||
|
}
|
||||||
|
for name, data := range files {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
output := filepath.Join(dir, "output.json")
|
||||||
|
if mode == "transcript" {
|
||||||
|
output = schema
|
||||||
|
}
|
||||||
|
app, err := buildApplication()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out, stderr bytes.Buffer
|
||||||
|
result := app.Execute(context.Background(), []string{"process", "--config", filepath.Join(dir, "config.yml"), "--output", output, filepath.Join(dir, "input.json")}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||||
|
if mode == "separate" {
|
||||||
|
if result.Status != 0 || calls.Load() != 1 {
|
||||||
|
t.Fatalf("status=%d calls=%d err=%s", result.Status, calls.Load(), stderr.String())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if result.Status == 0 || calls.Load() != 0 || !strings.Contains(stderr.String(), "conflicts with input") {
|
||||||
|
t.Fatalf("status=%d calls=%d err=%s", result.Status, calls.Load(), stderr.String())
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, "recoveries.yml")); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("report created before collision check: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(schema)
|
||||||
|
if err != nil || string(raw) != original {
|
||||||
|
t.Fatalf("schema changed: %s %v", raw, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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},
|
||||||
@@ -107,25 +106,9 @@ func defaults() Config {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const glossaryImports = `config:
|
// Definition describes the application settings independently of their sources.
|
||||||
imports:
|
func Definition() ck.Definition[Config] {
|
||||||
- path: glossary.yml
|
return ck.Definition[Config]{
|
||||||
required: false
|
|
||||||
destination: [glossary_collections]
|
|
||||||
- dir: glossary
|
|
||||||
required: false
|
|
||||||
recursive: true
|
|
||||||
pattern: ["*.yml", "*.yaml"]
|
|
||||||
destination: [glossary_collections]
|
|
||||||
`
|
|
||||||
|
|
||||||
// Load resolves the selected main source and preserves native source evidence.
|
|
||||||
func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) {
|
|
||||||
input.Imports = true
|
|
||||||
return ck.LoadLayered(input, ck.LayeredOptions[Config]{
|
|
||||||
Overlay: overlay, Overrides: overrides,
|
|
||||||
Underlays: []ck.Underlay{{Inputs: []ck.Input{{Source: ck.Bytes("Audita glossary imports", []byte(glossaryImports)), Imports: true, MainRelative: ck.MainRelative()}}}},
|
|
||||||
Definition: ck.Definition[Config]{
|
|
||||||
Defaults: defaults,
|
Defaults: defaults,
|
||||||
SequenceIdentities: []ck.SequenceIdentity{ck.SequenceIdentityMatching(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections"), ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries")}, "id")},
|
SequenceIdentities: []ck.SequenceIdentity{ck.SequenceIdentityMatching(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections"), ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries")}, "id")},
|
||||||
Version: &ck.VersionRule{Path: ck.Keys("version"), Check: func(version ck.Version, v *ck.Validation) error {
|
Version: &ck.VersionRule{Path: ck.Keys("version"), Check: func(version ck.Version, v *ck.Validation) error {
|
||||||
@@ -136,8 +119,7 @@ func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[
|
|||||||
}},
|
}},
|
||||||
Resolve: resolveSettings,
|
Resolve: resolveSettings,
|
||||||
Validate: validate,
|
Validate: validate,
|
||||||
},
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func validate(c *Config, v *ck.Validation) {
|
func validate(c *Config, v *ck.Validation) {
|
||||||
@@ -193,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")
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"io/fs"
|
|
||||||
"os"
|
"os"
|
||||||
"path"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -40,109 +38,6 @@ func TestDefaultsAndVersion(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMainContextImportsAndOverlay(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
for name, contents := range map[string]string{
|
|
||||||
"main.yml": "version: 3\nconfig:\n imports:\n - path: fragment.yml\noutput:\n schema: bare-segments\n",
|
|
||||||
"fragment.yml": "context:\n description: imported\n",
|
|
||||||
"overlays/selected.yml": "context:\n description: overlay\n",
|
|
||||||
} {
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "selected", ck.Override{Path: ck.Keys("context", "description"), Value: "override", Flag: "--description"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if info, ok := result.Metadata().Lookup(ck.Keys("context", "description")); !ok || info.Origin.Layer != ck.LayerCLI {
|
|
||||||
t.Fatalf("override origin = %+v", info)
|
|
||||||
}
|
|
||||||
if result.Config.Context.Description != "override" {
|
|
||||||
t.Fatalf("description = %q", result.Config.Context.Description)
|
|
||||||
}
|
|
||||||
found := false
|
|
||||||
for _, source := range result.Sources() {
|
|
||||||
if source.Layer == ck.LayerMain && source.ImportedFrom == nil {
|
|
||||||
context, ok := result.SourceContext(source.ID)
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("main context missing")
|
|
||||||
}
|
|
||||||
data, err := fs.ReadFile(context.FS, path.Join(context.BaseDir, "fragment.yml"))
|
|
||||||
if err != nil || len(data) == 0 {
|
|
||||||
t.Fatalf("main context cannot access companion: %v", err)
|
|
||||||
}
|
|
||||||
found = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !found {
|
|
||||||
t.Fatal("main source missing")
|
|
||||||
}
|
|
||||||
if _, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "missing"); err == nil {
|
|
||||||
t.Fatal("missing overlay accepted")
|
|
||||||
}
|
|
||||||
if _, err := Load(ck.Input{Source: ck.NoSource()}, "selected"); err == nil {
|
|
||||||
t.Fatal("overlay without context accepted")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDiscoveryAndSelectedFailure(t *testing.T) {
|
|
||||||
first, second := t.TempDir(), t.TempDir()
|
|
||||||
search := ck.Searches(ck.SearchDirectory(first), ck.SearchDirectory(second))
|
|
||||||
load := func() (*ck.Result[Config], error) {
|
|
||||||
return Load(ck.Input{Source: ck.SearchConfig("audita", search)}, "")
|
|
||||||
}
|
|
||||||
result, err := load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
for _, source := range result.Sources() {
|
|
||||||
if source.Layer == ck.LayerMain {
|
|
||||||
t.Fatalf("unexpected main source: %+v", source)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(second, "config.yml"), []byte("context:\n description: selected\n"), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
result, err = load()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if result.Config.Context.Description != "selected" {
|
|
||||||
t.Fatalf("description = %q", result.Config.Context.Description)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(first, "config.yml"), []byte("version: 2\n"), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, err := load(); err == nil {
|
|
||||||
t.Fatal("invalid selected file fell through")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestOverlayUsesMainDirectoryWithinWiderRoot(t *testing.T) {
|
|
||||||
root := t.TempDir()
|
|
||||||
dir := filepath.Join(root, "project")
|
|
||||||
if err := os.MkdirAll(filepath.Join(dir, "overlays"), 0755); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "config.yml"), []byte("version: 3\n"), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "overlays", "local.yml"), []byte("context:\n description: project\n"), 0644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "local")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if result.Config.Context.Description != "project" {
|
|
||||||
t.Fatalf("description = %q", result.Config.Context.Description)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSchemaConstraintsAndExplicitValues(t *testing.T) {
|
func TestSchemaConstraintsAndExplicitValues(t *testing.T) {
|
||||||
path := filepath.Join(t.TempDir(), "config.yml")
|
path := filepath.Join(t.TempDir(), "config.yml")
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
@@ -156,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 {
|
||||||
|
|||||||
12
internal/core/config/loader_test.go
Normal file
12
internal/core/config/loader_test.go
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import ck "go.maximumdirect.net/configkit"
|
||||||
|
|
||||||
|
func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) {
|
||||||
|
input.Imports = true
|
||||||
|
return ck.LoadLayered(input, ck.LayeredOptions[Config]{
|
||||||
|
Definition: Definition(),
|
||||||
|
Overlay: overlay,
|
||||||
|
Overrides: overrides,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -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"))
|
||||||
|
|||||||
@@ -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" {
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package reporting
|
|
||||||
|
|
||||||
// TokenMetric distinguishes measured zero from unavailable provider usage.
|
|
||||||
type TokenMetric struct {
|
|
||||||
Value int `json:"value"`
|
|
||||||
Known bool `json:"known"`
|
|
||||||
Complete bool `json:"complete"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LLMUsage struct {
|
|
||||||
Prompt TokenMetric `json:"prompt"`
|
|
||||||
Completion TokenMetric `json:"completion"`
|
|
||||||
Total TokenMetric `json:"total"`
|
|
||||||
Cached TokenMetric `json:"cached"`
|
|
||||||
CacheWrite TokenMetric `json:"cache_write"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LLMSummary struct {
|
|
||||||
LogicalCalls uint64 `json:"logical_calls"`
|
|
||||||
ProviderAttempts uint64 `json:"provider_attempts"`
|
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage LLMUsage `json:"usage"`
|
|
||||||
}
|
|
||||||
@@ -5,12 +5,12 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"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"
|
||||||
@@ -55,6 +55,39 @@ type pendingCall struct {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// preparedEvidence keeps the native prepared run while allowing repair
|
||||||
|
// histories to retain a shared prefix of their append-only messages.
|
||||||
|
type preparedEvidence struct {
|
||||||
|
run pk.PreparedRun
|
||||||
|
history *preparedMessageHistory
|
||||||
|
}
|
||||||
|
|
||||||
|
type preparedMessageHistory struct{ messages []pk.RenderedMessage }
|
||||||
|
|
||||||
|
func (e preparedEvidence) MarshalJSON() ([]byte, error) { return json.Marshal(e.run) }
|
||||||
|
|
||||||
|
func (e preparedEvidence) ShareMessages(previous any) any {
|
||||||
|
prior, ok := previous.(preparedEvidence)
|
||||||
|
if !ok || prior.history == nil || len(prior.history.messages) > len(e.run.Messages) || !slices.EqualFunc(prior.history.messages, e.run.Messages[:len(prior.history.messages)], sameRenderedMessage) {
|
||||||
|
e.history = &preparedMessageHistory{messages: e.run.Messages}
|
||||||
|
} else {
|
||||||
|
e.history = prior.history
|
||||||
|
e.history.messages = append(e.history.messages, e.run.Messages[len(e.history.messages):]...)
|
||||||
|
}
|
||||||
|
e.run.Messages = slices.Clip(e.history.messages)
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameRenderedMessage(a, b pk.RenderedMessage) bool {
|
||||||
|
if a.Role != b.Role || a.Content != b.Content {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if a.CacheControl == nil || b.CacheControl == nil {
|
||||||
|
return a.CacheControl == b.CacheControl
|
||||||
|
}
|
||||||
|
return *a.CacheControl == *b.CacheControl
|
||||||
|
}
|
||||||
|
|
||||||
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
||||||
p.once.Do(func() {
|
p.once.Do(func() {
|
||||||
p.response, p.err = p.complete(result, err)
|
p.response, p.err = p.complete(result, err)
|
||||||
@@ -139,15 +172,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()
|
||||||
@@ -165,7 +193,7 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
|||||||
metadata := promptMetadata(details)
|
metadata := promptMetadata(details)
|
||||||
var snapshot *structuredoutput.PreparedSnapshot
|
var snapshot *structuredoutput.PreparedSnapshot
|
||||||
if req.CaptureDiagnostics {
|
if req.CaptureDiagnostics {
|
||||||
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata}
|
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata, PromptKit: preparedEvidence{run: details}}
|
||||||
}
|
}
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
prepared, prompt = snapshot, metadata
|
prepared, prompt = snapshot, metadata
|
||||||
@@ -195,7 +223,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 +245,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 {
|
||||||
|
|||||||
@@ -11,8 +11,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -24,7 +24,7 @@ func capacityFixture(t *testing.T, resources string, transport http.RoundTripper
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -62,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{})
|
||||||
@@ -112,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{})
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -15,9 +17,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
@@ -64,11 +66,16 @@ func TestCanceledCallSkipsProgress(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func adapterFixture(t *testing.T, replies []reply, retries, repairs int, hook func(*http.Request)) (*Runtime, *atomic.Int32, string) {
|
type testRuntime struct {
|
||||||
|
*Runtime
|
||||||
|
Config config.Config
|
||||||
|
}
|
||||||
|
|
||||||
|
func adapterFixture(t *testing.T, replies []reply, retries, repairs int, hook func(*http.Request)) (*testRuntime, *atomic.Int32, string) {
|
||||||
return adapterFixtureWithPrompt(t, replies, retries, repairs, hook, "")
|
return adapterFixtureWithPrompt(t, replies, retries, repairs, hook, "")
|
||||||
}
|
}
|
||||||
|
|
||||||
func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs int, hook func(*http.Request), operatorPrompt string) (*Runtime, *atomic.Int32, string) {
|
func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs int, hook func(*http.Request), operatorPrompt string) (*testRuntime, *atomic.Int32, string) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
var count atomic.Int32
|
var count atomic.Int32
|
||||||
t.Setenv("ADAPTER_KEY", "adapter-secret")
|
t.Setenv("ADAPTER_KEY", "adapter-secret")
|
||||||
@@ -79,7 +86,26 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
|
// 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 = promptfixture.WithRepairAttempts(t, data, 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 {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -109,28 +135,28 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
runtime.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 runtime, &count, dir
|
return &testRuntime{Runtime: runtime, Config: settings}, &count, dir
|
||||||
}
|
}
|
||||||
|
|
||||||
func operatorPromptDocument(system, user string) string {
|
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 {
|
||||||
@@ -155,7 +181,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
|
||||||
@@ -245,7 +271,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)
|
||||||
}
|
}
|
||||||
@@ -290,7 +316,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)
|
||||||
@@ -300,6 +326,17 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
|||||||
if !requestSeen || count.Load() != 1 || response.Prepared == nil || len(response.Prepared.Messages) == 0 {
|
if !requestSeen || count.Load() != 1 || response.Prepared == nil || len(response.Prepared.Messages) == 0 {
|
||||||
t.Fatal("prepared call missing")
|
t.Fatal("prepared call missing")
|
||||||
}
|
}
|
||||||
|
encoded, err := json.Marshal(response.Prepared.PromptKit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var native pk.PreparedRun
|
||||||
|
if err := json.Unmarshal(encoded, &native); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if native.MessageContentHash == "" || native.OutputContract.SchemaPath == "" || native.StructuredOutput == nil || native.StructuredOutput.JSONSchema == nil {
|
||||||
|
t.Fatalf("missing native prepared contract or hash: %+v", native)
|
||||||
|
}
|
||||||
if len(posted.Messages) != len(response.Prepared.Messages) {
|
if len(posted.Messages) != len(response.Prepared.Messages) {
|
||||||
t.Fatal("prepared and dispatched message counts differ")
|
t.Fatal("prepared and dispatched message counts differ")
|
||||||
}
|
}
|
||||||
@@ -323,7 +360,41 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing.T) {
|
func TestPreparedEvidenceSharesGrowingMessageHistory(t *testing.T) {
|
||||||
|
first := preparedEvidence{run: pk.PreparedRun{Messages: make([]pk.RenderedMessage, 1, 4)}}
|
||||||
|
first.run.Messages[0] = pk.RenderedMessage{Role: "user", Content: "first"}
|
||||||
|
first = first.ShareMessages(nil).(preparedEvidence)
|
||||||
|
second := preparedEvidence{run: pk.PreparedRun{Messages: []pk.RenderedMessage{{Role: "user", Content: "first"}, {Role: "assistant", Content: "reply"}}}}
|
||||||
|
second = second.ShareMessages(first).(preparedEvidence)
|
||||||
|
if &first.run.Messages[0] != &second.run.Messages[0] || len(first.run.Messages) != 1 || second.run.Messages[1].Content != "reply" {
|
||||||
|
t.Fatal("growing histories did not share an unchanged prefix")
|
||||||
|
}
|
||||||
|
changed := preparedEvidence{run: pk.PreparedRun{Messages: []pk.RenderedMessage{{Role: "user", Content: "changed"}}}}
|
||||||
|
changed = changed.ShareMessages(second).(preparedEvidence)
|
||||||
|
if changed.run.Messages[0].Content != "changed" || first.run.Messages[0].Content != "first" {
|
||||||
|
t.Fatal("changed history corrupted an earlier snapshot")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreparedEvidenceIsOptional(t *testing.T) {
|
||||||
|
runtime, _, _ := adapterFixture(t, []reply{{200, `{"corrections":[]}`}}, 0, 0, nil)
|
||||||
|
client, err := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, CallHooks{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := adapterRequest("proposal")
|
||||||
|
req.CaptureDiagnostics = false
|
||||||
|
var out map[string]any
|
||||||
|
response, err := client.CompleteStructured(context.Background(), req, &out)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.Prepared != nil {
|
||||||
|
t.Fatal("prepared evidence retained without diagnostic capture")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOperatorPromptUsesOwnContractAndOptionalSharedText(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
system string
|
system string
|
||||||
@@ -337,8 +408,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.",
|
||||||
},
|
},
|
||||||
@@ -370,7 +440,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"
|
||||||
}
|
}
|
||||||
@@ -410,7 +480,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 {
|
||||||
@@ -432,7 +502,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())
|
||||||
}
|
}
|
||||||
@@ -447,7 +517,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)
|
||||||
@@ -455,7 +525,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)
|
||||||
}
|
}
|
||||||
@@ -482,7 +552,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) ||
|
||||||
@@ -504,7 +574,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") ||
|
||||||
@@ -524,21 +594,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 {
|
||||||
@@ -553,7 +618,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)
|
||||||
@@ -580,3 +645,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())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
@@ -31,7 +31,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -70,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)
|
||||||
}
|
}
|
||||||
@@ -86,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)
|
||||||
@@ -111,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") {
|
||||||
@@ -136,7 +136,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -158,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)
|
||||||
}
|
}
|
||||||
@@ -172,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)
|
||||||
|
|||||||
@@ -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,14 +54,14 @@ 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)
|
||||||
}
|
}
|
||||||
snapshot := collector.Snapshot()
|
snapshot := collector.Snapshot()
|
||||||
summary := Summarize(snapshot)
|
summary := Summarize(snapshot)
|
||||||
if len(snapshot.Calls) != 2 || summary.ProviderAttempts != 2 || !summary.TerminalCoverageComplete {
|
if len(snapshot.Calls) != 2 || summary.PromptKit.Attempts != 2 || !summary.PromptKit.TerminalCoverageComplete {
|
||||||
t.Fatalf("summary=%+v calls=%+v", summary, snapshot.Calls)
|
t.Fatalf("summary=%+v calls=%+v", summary, snapshot.Calls)
|
||||||
}
|
}
|
||||||
for _, call := range snapshot.Calls {
|
for _, call := range snapshot.Calls {
|
||||||
@@ -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,12 +101,12 @@ 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)
|
||||||
}
|
}
|
||||||
if got := Summarize(collector.Snapshot()); got.ProviderAttempts != 2 || !got.TerminalCoverageComplete {
|
if got := Summarize(collector.Snapshot()); got.PromptKit.Attempts != 2 || !got.PromptKit.TerminalCoverageComplete {
|
||||||
t.Fatalf("summary=%+v", got)
|
t.Fatalf("summary=%+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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.PromptKit.Attempts != 3 || summary.LogicalCalls != 3 || !summary.PromptKit.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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import (
|
|||||||
"slices"
|
"slices"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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"
|
||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
@@ -29,7 +29,7 @@ func TestEngineCapturesAutomaticPromptSources(t *testing.T) {
|
|||||||
write("prompts.yml", "collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n")
|
write("prompts.yml", "collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n")
|
||||||
write("message.txt", "first")
|
write("message.txt", "first")
|
||||||
write("prompts/nested/extra.yml", "prompts:\n - id: extra\n messages:\n - role: user\n content: extra\n output:\n format: text\n validation_mode: none\n")
|
write("prompts/nested/extra.yml", "prompts:\n - id: extra\n messages:\n - role: user\n content: extra\n output:\n format: text\n validation_mode: none\n")
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(main)}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -70,7 +70,7 @@ func TestEngineCapturesAutomaticPromptSources(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestEngineWithoutMainUsesEmbeddedPrompts(t *testing.T) {
|
func TestEngineWithoutMainUsesEmbeddedPrompts(t *testing.T) {
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.NoSource()}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -103,7 +103,7 @@ func TestEngineCapturesInheritedMessageAndRejectsPeerConflicts(t *testing.T) {
|
|||||||
write("shared/catalog.yml", "prompts:\n - id: parent\n messages:\n - role: user\n content_file: instruction.md\n output:\n format: text\n validation_mode: none\n")
|
write("shared/catalog.yml", "prompts:\n - id: parent\n messages:\n - role: user\n content_file: instruction.md\n output:\n format: text\n validation_mode: none\n")
|
||||||
write("shared/instruction.md", "inherited content")
|
write("shared/instruction.md", "inherited content")
|
||||||
write("prompts/child.yml", "prompts:\n - id: child\n extends: {id: parent}\n")
|
write("prompts/child.yml", "prompts:\n - id: child\n extends: {id: parent}\n")
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -121,7 +121,7 @@ func TestEngineCapturesInheritedMessageAndRejectsPeerConflicts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
write("prompts/duplicate.yml", "prompts:\n - id: parent\n messages:\n - role: user\n content: duplicate\n output:\n format: text\n validation_mode: none\n")
|
write("prompts/duplicate.yml", "prompts:\n - id: parent\n messages:\n - role: user\n content: duplicate\n output:\n format: text\n validation_mode: none\n")
|
||||||
if _, err := NewRuntime(context.Background(), loaded, nil); err == nil || IsAssetError(err) {
|
if _, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, ""); err == nil || appconfig.IsAssetError(err) {
|
||||||
t.Fatalf("peer conflict classification: %v", err)
|
t.Fatalf("peer conflict classification: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -144,7 +144,7 @@ func TestEngineUsesRecordedContextWithWiderRoot(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
source := ck.SearchConfig("audita", ck.SearchDirectory(project))
|
source := ck.SearchConfig("audita", ck.SearchDirectory(project))
|
||||||
loaded, err := config.Load(ck.Input{Source: source, Filesystem: &ck.FilesystemContext{Root: root}}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: source, Filesystem: &ck.FilesystemContext{Root: root}}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -181,7 +181,7 @@ func TestEngineResolvesLinkedPromptMessageBesideDefinition(t *testing.T) {
|
|||||||
if err := os.Symlink("defs/resources.yml", filepath.Join(root, "prompts.yml")); err != nil {
|
if err := os.Symlink("defs/resources.yml", filepath.Join(root, "prompts.yml")); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(filepath.Join(root, "config.yml"))}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(root, "config.yml"))}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -211,7 +211,7 @@ func TestRepairPromptReplacementUsesMessageFile(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||||
"io"
|
"io"
|
||||||
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
@@ -13,9 +15,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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"
|
||||||
@@ -35,7 +37,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(document), 0644); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(document), 0644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -57,7 +59,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)
|
||||||
}
|
}
|
||||||
@@ -73,11 +75,11 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
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
|
||||||
@@ -90,6 +92,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 = promptfixture.WithRepairAttempts(t, prompt, 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)]
|
||||||
@@ -98,11 +116,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)
|
||||||
}
|
}
|
||||||
@@ -151,7 +169,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -175,7 +193,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{})
|
||||||
@@ -200,7 +218,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -221,7 +239,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)
|
||||||
@@ -241,7 +259,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -255,7 +273,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{})
|
||||||
|
|||||||
@@ -9,47 +9,11 @@ import (
|
|||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TokenCount retains the distinction between zero and unavailable usage.
|
// ExecutionObservation combines an Audita logical call with native execution evidence.
|
||||||
type TokenCount struct {
|
|
||||||
Value int `json:"value"`
|
|
||||||
Known bool `json:"known"`
|
|
||||||
Complete bool `json:"complete"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type Usage struct {
|
|
||||||
Prompt TokenCount `json:"prompt"`
|
|
||||||
Completion TokenCount `json:"completion"`
|
|
||||||
Total TokenCount `json:"total"`
|
|
||||||
Cached TokenCount `json:"cached"`
|
|
||||||
CacheWrite TokenCount `json:"cache_write"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExecutionObservation contains execution metadata only. It never contains
|
|
||||||
// endpoint URLs, credentials, messages, provider errors, or generated text.
|
|
||||||
type ExecutionObservation struct {
|
type ExecutionObservation struct {
|
||||||
CallID uint64 `json:"call_id"`
|
CallID uint64 `json:"call_id"`
|
||||||
Context structuredoutput.DiagnosticContext `json:"context"`
|
Context structuredoutput.DiagnosticContext `json:"context"`
|
||||||
Kind string `json:"kind"`
|
PromptKit pk.ExecutionEvent `json:"promptkit"`
|
||||||
RunID string `json:"run_id,omitempty"`
|
|
||||||
Time time.Time `json:"time"`
|
|
||||||
BackendID string `json:"backend_id,omitempty"`
|
|
||||||
ProfileID string `json:"profile_id,omitempty"`
|
|
||||||
Model string `json:"model,omitempty"`
|
|
||||||
Generation uint64 `json:"generation,omitempty"`
|
|
||||||
Attempt uint64 `json:"attempt,omitempty"`
|
|
||||||
Dispatched bool `json:"dispatched"`
|
|
||||||
CapacityWait time.Duration `json:"capacity_wait_ns"`
|
|
||||||
GenerationDuration time.Duration `json:"generation_duration_ns"`
|
|
||||||
RetryDelay time.Duration `json:"retry_delay_ns"`
|
|
||||||
Duration time.Duration `json:"duration_ns"`
|
|
||||||
Outcome string `json:"outcome,omitempty"`
|
|
||||||
Failure string `json:"failure,omitempty"`
|
|
||||||
StatusCode int `json:"status_code,omitempty"`
|
|
||||||
RetriesExhausted bool `json:"retries_exhausted,omitempty"`
|
|
||||||
Attempts uint64 `json:"attempts"`
|
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage Usage `json:"usage"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LogicalCall struct {
|
type LogicalCall struct {
|
||||||
@@ -70,12 +34,8 @@ type ObservationSnapshot struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ExecutionSummary struct {
|
type ExecutionSummary struct {
|
||||||
TerminalCoverageComplete bool `json:"terminal_coverage_complete"`
|
|
||||||
LogicalCalls uint64 `json:"logical_calls"`
|
LogicalCalls uint64 `json:"logical_calls"`
|
||||||
ProviderAttempts uint64 `json:"provider_attempts"`
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage Usage `json:"usage"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ObservationCollector accepts short synchronous callbacks from parallel calls.
|
// ObservationCollector accepts short synchronous callbacks from parallel calls.
|
||||||
@@ -140,22 +100,10 @@ func (c *ObservationCollector) recordEvent(callID uint64, context structuredoutp
|
|||||||
if c == nil {
|
if c == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.group.Observe(event)
|
|
||||||
count := func(value pk.ObservedTokenCount) TokenCount {
|
|
||||||
return TokenCount{Value: value.Value, Known: value.Known, Complete: value.Complete}
|
|
||||||
}
|
|
||||||
observation := ExecutionObservation{
|
|
||||||
CallID: callID, Context: copyContext(context), Kind: string(event.Kind), RunID: event.RunID,
|
|
||||||
Time: event.Time, BackendID: event.BackendID, ProfileID: event.ProfileID, Model: event.Model,
|
|
||||||
Generation: event.Generation, Attempt: event.Attempt, Dispatched: event.Dispatched,
|
|
||||||
CapacityWait: event.CapacityWait, GenerationDuration: event.GenerationDuration, RetryDelay: event.RetryDelay, Duration: event.Duration,
|
|
||||||
Outcome: string(event.Outcome), Failure: string(event.Failure), StatusCode: event.StatusCode, RetriesExhausted: event.RetriesExhausted,
|
|
||||||
Attempts: event.Attempts, TransientRetries: event.TransientRetries, StructuralRepairs: event.RepairCalls,
|
|
||||||
Usage: Usage{Prompt: count(event.Usage.PromptTokens), Completion: count(event.Usage.CompletionTokens), Total: count(event.Usage.TotalTokens), Cached: count(event.Usage.CachedTokens), CacheWrite: count(event.Usage.CacheWriteTokens)},
|
|
||||||
}
|
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
c.events = append(c.events, observation)
|
defer c.mu.Unlock()
|
||||||
c.mu.Unlock()
|
c.group.Observe(event)
|
||||||
|
c.events = append(c.events, ExecutionObservation{CallID: callID, Context: copyContext(context), PromptKit: event})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ObservationCollector) Snapshot() ObservationSnapshot {
|
func (c *ObservationCollector) Snapshot() ObservationSnapshot {
|
||||||
@@ -178,7 +126,7 @@ func (c *ObservationCollector) Snapshot() ObservationSnapshot {
|
|||||||
if snapshot.Events[i].CallID != snapshot.Events[j].CallID {
|
if snapshot.Events[i].CallID != snapshot.Events[j].CallID {
|
||||||
return snapshot.Events[i].CallID < snapshot.Events[j].CallID
|
return snapshot.Events[i].CallID < snapshot.Events[j].CallID
|
||||||
}
|
}
|
||||||
return snapshot.Events[i].Time.Before(snapshot.Events[j].Time)
|
return snapshot.Events[i].PromptKit.Time.Before(snapshot.Events[j].PromptKit.Time)
|
||||||
})
|
})
|
||||||
group := c.group.Snapshot()
|
group := c.group.Snapshot()
|
||||||
snapshot.Group = &group
|
snapshot.Group = &group
|
||||||
@@ -188,20 +136,14 @@ func (c *ObservationCollector) Snapshot() ObservationSnapshot {
|
|||||||
// Summarize delegates deduplication and terminal accounting to PromptKit. A
|
// Summarize delegates deduplication and terminal accounting to PromptKit. A
|
||||||
// filtered diagnostic view selects its own group; overlapping views are not additive.
|
// filtered diagnostic view selects its own group; overlapping views are not additive.
|
||||||
func Summarize(snapshot ObservationSnapshot) ExecutionSummary {
|
func Summarize(snapshot ObservationSnapshot) ExecutionSummary {
|
||||||
summary := snapshot.Group
|
if snapshot.Group != nil {
|
||||||
if summary == nil {
|
group := *snapshot.Group
|
||||||
|
group.Members = append([]pk.ExecutionGroupMember(nil), group.Members...)
|
||||||
|
return ExecutionSummary{LogicalCalls: uint64(len(snapshot.Calls)), PromptKit: group}
|
||||||
|
}
|
||||||
var group pk.ExecutionGroup
|
var group pk.ExecutionGroup
|
||||||
count := func(c TokenCount) pk.ObservedTokenCount {
|
|
||||||
return pk.ObservedTokenCount{Value: c.Value, Known: c.Known, Complete: c.Complete}
|
|
||||||
}
|
|
||||||
for _, event := range snapshot.Events {
|
for _, event := range snapshot.Events {
|
||||||
group.Observe(pk.ExecutionEvent{Kind: pk.ExecutionEventKind(event.Kind), RunID: event.RunID, Attempts: event.Attempts, TransientRetries: event.TransientRetries, RepairCalls: event.StructuralRepairs, Usage: pk.ObservedTokenUsage{PromptTokens: count(event.Usage.Prompt), CompletionTokens: count(event.Usage.Completion), TotalTokens: count(event.Usage.Total), CachedTokens: count(event.Usage.Cached), CacheWriteTokens: count(event.Usage.CacheWrite)}})
|
group.Observe(event.PromptKit)
|
||||||
}
|
}
|
||||||
value := group.Snapshot()
|
return ExecutionSummary{LogicalCalls: uint64(len(snapshot.Calls)), PromptKit: group.Snapshot()}
|
||||||
summary = &value
|
|
||||||
}
|
|
||||||
count := func(c pk.ObservedTokenCount) TokenCount {
|
|
||||||
return TokenCount{Value: c.Value, Known: c.Known, Complete: c.Complete}
|
|
||||||
}
|
|
||||||
return ExecutionSummary{LogicalCalls: uint64(len(snapshot.Calls)), TerminalCoverageComplete: summary.TerminalCoverageComplete, ProviderAttempts: summary.Attempts, TransientRetries: summary.TransientRetries, StructuralRepairs: summary.RepairCalls, Usage: Usage{Prompt: count(summary.Usage.PromptTokens), Completion: count(summary.Usage.CompletionTokens), Total: count(summary.Usage.TotalTokens), Cached: count(summary.Usage.CachedTokens), CacheWrite: count(summary.Usage.CacheWriteTokens)}}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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"
|
||||||
)
|
)
|
||||||
@@ -27,7 +26,7 @@ func TestObservationSummarySeparatesLogicalCallsAttemptsAndUsage(t *testing.T) {
|
|||||||
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{Role: "proposal"}, pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionAttempt, Dispatched: false})
|
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{Role: "proposal"}, pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionAttempt, Dispatched: false})
|
||||||
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{Role: "proposal"}, pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionFinished, Attempts: 0, Usage: pk.ObservedTokenUsage{PromptTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CompletionTokens: pk.ObservedTokenCount{Known: true, Complete: true}, TotalTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CachedTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CacheWriteTokens: pk.ObservedTokenCount{Known: true, Complete: true}}})
|
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{Role: "proposal"}, pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionFinished, Attempts: 0, Usage: pk.ObservedTokenUsage{PromptTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CompletionTokens: pk.ObservedTokenCount{Known: true, Complete: true}, TotalTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CachedTokens: pk.ObservedTokenCount{Known: true, Complete: true}, CacheWriteTokens: pk.ObservedTokenCount{Known: true, Complete: true}}})
|
||||||
summary := Summarize(collector.Snapshot())
|
summary := Summarize(collector.Snapshot())
|
||||||
if summary.LogicalCalls != 2 || summary.ProviderAttempts != 0 || summary.Usage.Total != (TokenCount{Known: true, Complete: true}) {
|
if summary.LogicalCalls != 2 || summary.PromptKit.Attempts != 0 || summary.PromptKit.Usage.TotalTokens != (pk.ObservedTokenCount{Known: true, Complete: true}) {
|
||||||
t.Fatalf("zero-attempt accounting: %+v", summary)
|
t.Fatalf("zero-attempt accounting: %+v", summary)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +41,7 @@ func TestObservationSummarySeparatesLogicalCallsAttemptsAndUsage(t *testing.T) {
|
|||||||
hooks.OnEventWithCall(4, context, pk.ExecutionEvent{RunID: "run-4", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{PromptTokens: pk.ObservedTokenCount{Known: false, Complete: false}, TotalTokens: pk.ObservedTokenCount{Known: false, Complete: false}}})
|
hooks.OnEventWithCall(4, context, pk.ExecutionEvent{RunID: "run-4", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{PromptTokens: pk.ObservedTokenCount{Known: false, Complete: false}, TotalTokens: pk.ObservedTokenCount{Known: false, Complete: false}}})
|
||||||
snapshot := collector.Snapshot()
|
snapshot := collector.Snapshot()
|
||||||
summary = Summarize(snapshot)
|
summary = Summarize(snapshot)
|
||||||
if summary.LogicalCalls != 4 || summary.ProviderAttempts != 4 || summary.TransientRetries != 1 || summary.StructuralRepairs != 1 || summary.Usage.Total.Value != 8 || !summary.Usage.Total.Known || summary.Usage.Total.Complete || summary.Usage.Prompt.Value != 5 || !summary.Usage.Prompt.Known || summary.Usage.Prompt.Complete || !summary.Usage.Cached.Known || summary.Usage.Cached.Complete {
|
if summary.LogicalCalls != 4 || summary.PromptKit.Attempts != 4 || summary.PromptKit.TransientRetries != 1 || summary.PromptKit.RepairCalls != 1 || summary.PromptKit.Usage.TotalTokens.Value != 8 || !summary.PromptKit.Usage.TotalTokens.Known || summary.PromptKit.Usage.TotalTokens.Complete || summary.PromptKit.Usage.PromptTokens.Value != 5 || !summary.PromptKit.Usage.PromptTokens.Known || summary.PromptKit.Usage.PromptTokens.Complete || !summary.PromptKit.Usage.CachedTokens.Known || summary.PromptKit.Usage.CachedTokens.Complete {
|
||||||
t.Fatalf("partial usage or double count: %+v", summary)
|
t.Fatalf("partial usage or double count: %+v", summary)
|
||||||
}
|
}
|
||||||
raw, err := json.Marshal(snapshot)
|
raw, err := json.Marshal(snapshot)
|
||||||
@@ -76,7 +75,7 @@ func TestObservationCollectorConcurrentAttributionAndSnapshotCopy(t *testing.T)
|
|||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
snapshot := collector.Snapshot()
|
snapshot := collector.Snapshot()
|
||||||
if len(snapshot.Calls) != calls || len(snapshot.Events) != calls || Summarize(snapshot).ProviderAttempts != calls {
|
if len(snapshot.Calls) != calls || len(snapshot.Events) != calls || Summarize(snapshot).PromptKit.Attempts != calls {
|
||||||
t.Fatalf("parallel records: calls=%d events=%d", len(snapshot.Calls), len(snapshot.Events))
|
t.Fatalf("parallel records: calls=%d events=%d", len(snapshot.Calls), len(snapshot.Events))
|
||||||
}
|
}
|
||||||
for _, call := range snapshot.Calls {
|
for _, call := range snapshot.Calls {
|
||||||
@@ -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
|
||||||
@@ -113,7 +112,7 @@ func TestRoleClientFeedsCollectorAcrossPreparationFailure(t *testing.T) {
|
|||||||
}
|
}
|
||||||
snapshot := collector.Snapshot()
|
snapshot := collector.Snapshot()
|
||||||
summary := Summarize(snapshot)
|
summary := Summarize(snapshot)
|
||||||
if count.Load() != 1 || summary.LogicalCalls != 2 || summary.ProviderAttempts != 1 || len(snapshot.Events) == 0 {
|
if count.Load() != 1 || summary.LogicalCalls != 2 || summary.PromptKit.Attempts != 1 || len(snapshot.Events) == 0 {
|
||||||
t.Fatalf("collector accounting: %+v", summary)
|
t.Fatalf("collector accounting: %+v", summary)
|
||||||
}
|
}
|
||||||
for _, event := range snapshot.Events {
|
for _, event := range snapshot.Events {
|
||||||
@@ -131,12 +130,37 @@ func TestObservationCoverageIsIndependentOfUsage(t *testing.T) {
|
|||||||
hooks := collector.Hooks()
|
hooks := collector.Hooks()
|
||||||
hooks.OnEventWithCall(1, structuredoutput.DiagnosticContext{}, pk.ExecutionEvent{RunID: "pending", Kind: pk.ExecutionAttempt})
|
hooks.OnEventWithCall(1, structuredoutput.DiagnosticContext{}, pk.ExecutionEvent{RunID: "pending", Kind: pk.ExecutionAttempt})
|
||||||
got := Summarize(collector.Snapshot())
|
got := Summarize(collector.Snapshot())
|
||||||
if got.TerminalCoverageComplete || got.Usage.Total.Known || got.Usage.Total.Complete {
|
if got.PromptKit.TerminalCoverageComplete || got.PromptKit.Usage.TotalTokens.Known || got.PromptKit.Usage.TotalTokens.Complete {
|
||||||
t.Fatalf("incomplete group=%+v", got)
|
t.Fatalf("incomplete group=%+v", got)
|
||||||
}
|
}
|
||||||
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{}, pk.ExecutionEvent{RunID: "finished", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{TotalTokens: pk.ObservedTokenCount{Value: 7, Known: true, Complete: true}}})
|
hooks.OnEventWithCall(2, structuredoutput.DiagnosticContext{}, pk.ExecutionEvent{RunID: "finished", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{TotalTokens: pk.ObservedTokenCount{Value: 7, Known: true, Complete: true}}})
|
||||||
got = Summarize(collector.Snapshot())
|
got = Summarize(collector.Snapshot())
|
||||||
if got.TerminalCoverageComplete || !got.Usage.Total.Known || !got.Usage.Total.Complete || got.Usage.Total.Value != 7 {
|
if got.PromptKit.TerminalCoverageComplete || !got.PromptKit.Usage.TotalTokens.Known || !got.PromptKit.Usage.TotalTokens.Complete || got.PromptKit.Usage.TotalTokens.Value != 7 {
|
||||||
t.Fatalf("partial coverage=%+v", got)
|
t.Fatalf("partial coverage=%+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestObservationRetainsNativeEvidence(t *testing.T) {
|
||||||
|
collector := NewObservationCollector()
|
||||||
|
event := pk.ExecutionEvent{
|
||||||
|
Kind: pk.ExecutionFinished, RunID: "native-run", ParentRunID: "parent",
|
||||||
|
Usage: pk.ObservedTokenUsage{
|
||||||
|
ReasoningTokens: pk.ObservedTokenCount{Value: 3, Known: true, Complete: true},
|
||||||
|
CachedTokens: pk.ObservedTokenCount{Value: 0, Known: true, Complete: true},
|
||||||
|
},
|
||||||
|
CostUSD: pk.ObservedCost{Value: 0.25, Known: true, Complete: true, Source: pk.CostSourceProvider},
|
||||||
|
}
|
||||||
|
collector.Hooks().OnEventWithCall(7, structuredoutput.DiagnosticContext{Role: "repair"}, event)
|
||||||
|
snapshot := collector.Snapshot()
|
||||||
|
if len(snapshot.Events) != 1 || snapshot.Events[0].CallID != 7 || snapshot.Events[0].PromptKit != event {
|
||||||
|
t.Fatalf("events = %+v", snapshot.Events)
|
||||||
|
}
|
||||||
|
summary := Summarize(snapshot).PromptKit
|
||||||
|
if !summary.TerminalCoverageComplete || summary.Usage.ReasoningTokens.Value != 3 || !summary.Usage.CachedTokens.Known || summary.CostUSD != event.CostUSD {
|
||||||
|
t.Fatalf("native summary = %+v", summary)
|
||||||
|
}
|
||||||
|
replayed := Summarize(ObservationSnapshot{Events: snapshot.Events}).PromptKit
|
||||||
|
if replayed.CostUSD != summary.CostUSD || replayed.Usage.ReasoningTokens != summary.Usage.ReasoningTokens {
|
||||||
|
t.Fatalf("replayed = %+v", replayed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,16 +2,11 @@ package llm
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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"
|
||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
@@ -19,115 +14,36 @@ import (
|
|||||||
|
|
||||||
// Runtime owns the captured engine shared by all processing clients.
|
// Runtime owns the captured engine shared by all processing clients.
|
||||||
type Runtime struct {
|
type Runtime struct {
|
||||||
Config config.Config
|
|
||||||
Engine *pk.Engine
|
Engine *pk.Engine
|
||||||
SourcePaths []string
|
SourcePaths []string
|
||||||
nextCallID atomic.Uint64
|
nextCallID atomic.Uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
type AssetError struct{ Err error }
|
func NewRuntime(ctx context.Context, loaded *ck.Result[appconfig.Config], client *http.Client) (*Runtime, error) {
|
||||||
|
|
||||||
func (e *AssetError) Error() string { return e.Err.Error() }
|
|
||||||
func (e *AssetError) Unwrap() error { return e.Err }
|
|
||||||
|
|
||||||
const operatorImports = `config:
|
|
||||||
imports:
|
|
||||||
- path: prompts.yml
|
|
||||||
required: false
|
|
||||||
- dir: prompts
|
|
||||||
required: false
|
|
||||||
recursive: true
|
|
||||||
pattern: ["*.yml", "*.yaml"]
|
|
||||||
`
|
|
||||||
|
|
||||||
func NewRuntime(ctx context.Context, loaded *ck.Result[config.Config], client *http.Client) (*Runtime, error) {
|
|
||||||
engine, err := NewEngine(ctx, loaded, client)
|
engine, err := NewEngine(ctx, loaded, client)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
paths, err := capturedSourcePaths(engine)
|
paths, err := capturedSourcePaths(loaded)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("inspect captured LLM sources: %w", err)
|
return nil, fmt.Errorf("inspect captured LLM sources: %w", err)
|
||||||
}
|
}
|
||||||
return &Runtime{Config: loaded.Config, Engine: engine, SourcePaths: paths}, nil
|
return &Runtime{Engine: engine, SourcePaths: paths}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewEngine loads the captured PromptKit resources without processing collision checks.
|
// NewEngine captures PromptKit resources from the completed configuration.
|
||||||
func NewEngine(ctx context.Context, loaded *ck.Result[config.Config], client *http.Client) (*pk.Engine, error) {
|
func NewEngine(ctx context.Context, loaded pk.Configuration, client *http.Client) (*pk.Engine, error) {
|
||||||
return newEngineWithPromptFS(ctx, loaded, client, prompts.Filesystem())
|
|
||||||
}
|
|
||||||
|
|
||||||
func newEngineWithPromptFS(ctx context.Context, loaded *ck.Result[config.Config], client *http.Client, promptFS fs.FS) (*pk.Engine, error) {
|
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if loaded == nil {
|
engine, err := pk.NewFromConfig(loaded, pk.RuntimeConfig{HTTPClient: client})
|
||||||
return nil, fmt.Errorf("application configuration is required")
|
|
||||||
}
|
|
||||||
embedded, err := pk.FilesystemInputs("Audita embedded prompts", promptFS, prompts.AssetRoot)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, &AssetError{Err: fmt.Errorf("discover embedded prompts: %w", err)}
|
return nil, err
|
||||||
}
|
|
||||||
sources := pk.ConfigurationSources{Underlays: []ck.Underlay{{Inputs: embedded}}}
|
|
||||||
for _, source := range loaded.Sources() {
|
|
||||||
if source.Layer != ck.LayerMain || source.ImportedFrom != nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
context, ok := loaded.SourceContext(source.ID)
|
|
||||||
if !ok {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
var filesystemContext ck.FilesystemContext
|
|
||||||
if source.Kind == ck.SourceKindFile && source.Path != "" {
|
|
||||||
base := filepath.Dir(source.Path)
|
|
||||||
root := base
|
|
||||||
if context.BaseDir != "." {
|
|
||||||
for range strings.Split(context.BaseDir, "/") {
|
|
||||||
root = filepath.Dir(root)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
filesystemContext = ck.FilesystemContext{Root: root, BaseDir: base}
|
|
||||||
} else {
|
|
||||||
filesystem := ck.NewFilesystem("Audita operator prompts", context.FS)
|
|
||||||
filesystemContext = ck.FilesystemContext{FS: &filesystem, Root: ".", BaseDir: context.BaseDir}
|
|
||||||
}
|
|
||||||
sources.Underlays = append(sources.Underlays, ck.Underlay{Inputs: []ck.Input{{
|
|
||||||
Source: ck.Bytes("Audita automatic prompt imports", []byte(operatorImports)), Imports: true,
|
|
||||||
Filesystem: &filesystemContext,
|
|
||||||
}}})
|
|
||||||
break
|
|
||||||
}
|
|
||||||
engine, err := pk.NewEngine(pk.Config{Sources: sources, HTTPClient: client}, pk.WithSchemaFS(responseschema.Filesystem(), responseschema.AssetRoot))
|
|
||||||
if err != nil {
|
|
||||||
return nil, embeddedAssetOrInputError(ctx, embedded, fmt.Errorf("assemble LLM runtime: %w", err))
|
|
||||||
}
|
}
|
||||||
for _, meta := range prompts.RegisteredMetadata() {
|
for _, meta := range prompts.RegisteredMetadata() {
|
||||||
if _, err := engine.InspectPrompt(ctx, meta.PromptID); err != nil {
|
if _, err := engine.InspectPrompt(ctx, meta.PromptID); err != nil {
|
||||||
return nil, embeddedAssetOrInputError(ctx, embedded, fmt.Errorf("inspect prompt %s: %w", meta.PromptID, err))
|
return nil, fmt.Errorf("inspect prompt %s: %w", meta.PromptID, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return engine, nil
|
return engine, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func embeddedAssetOrInputError(ctx context.Context, inputs []ck.Input, cause error) error {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
engine, err := pk.NewEngine(pk.Config{Sources: pk.ConfigurationSources{Underlays: []ck.Underlay{{Inputs: inputs}}}}, pk.WithSchemaFS(responseschema.Filesystem(), responseschema.AssetRoot))
|
|
||||||
if err == nil {
|
|
||||||
for _, meta := range prompts.RegisteredMetadata() {
|
|
||||||
if _, err = engine.InspectPrompt(ctx, meta.PromptID); err != nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return &AssetError{Err: fmt.Errorf("validate embedded prompt assets: %w", err)}
|
|
||||||
}
|
|
||||||
return cause
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsAssetError(err error) bool { var target *AssetError; return errors.As(err, &target) }
|
|
||||||
|
|||||||
@@ -3,92 +3,30 @@ package llm
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"io/fs"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
"testing"
|
||||||
"testing/fstest"
|
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
func copyEmbeddedPromptFilesystem(t *testing.T) fstest.MapFS {
|
func TestRuntimeCapturesShippedPromptsAndHonorsCancellation(t *testing.T) {
|
||||||
t.Helper()
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
|
||||||
source := prompts.Filesystem()
|
|
||||||
files := make(fstest.MapFS)
|
|
||||||
err := fs.WalkDir(source, prompts.AssetRoot, func(name string, entry fs.DirEntry, err error) error {
|
|
||||||
if err != nil || entry.IsDir() {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data, err := fs.ReadFile(source, name)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
files[name] = &fstest.MapFile{Data: data}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return files
|
engine, err := NewEngine(context.Background(), loaded, nil)
|
||||||
}
|
|
||||||
|
|
||||||
func TestRuntimeClassifiesEmbeddedAssetsAndHonorsCancellation(t *testing.T) {
|
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.NoSource()}, "")
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
_, err = newEngineWithPromptFS(context.Background(), loaded, nil, fstest.MapFS{})
|
for _, meta := range prompts.RegisteredMetadata() {
|
||||||
if err == nil || !IsAssetError(err) || !errors.Is(err, fs.ErrNotExist) {
|
if _, err := engine.InspectPrompt(context.Background(), meta.PromptID); err != nil {
|
||||||
t.Fatalf("embedded discovery error was not preserved as an asset error: %v", err)
|
t.Errorf("inspect %s: %v", meta.PromptID, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
cancel()
|
cancel()
|
||||||
_, err = newEngineWithPromptFS(ctx, loaded, nil, fstest.MapFS{})
|
if _, err := NewEngine(ctx, loaded, nil); !errors.Is(err, context.Canceled) {
|
||||||
if !errors.Is(err, context.Canceled) || IsAssetError(err) {
|
t.Fatalf("cancellation: %v", err)
|
||||||
t.Fatalf("caller cancellation classification: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestBrokenEmbeddedPromptFailsEmbeddedOnlyConstruction(t *testing.T) {
|
|
||||||
promptFS := copyEmbeddedPromptFilesystem(t)
|
|
||||||
assetPath := path.Join(prompts.AssetRoot, "modules.grammar.proposal.yaml")
|
|
||||||
promptFS[assetPath] = &fstest.MapFile{Data: []byte("collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: []\n")}
|
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.NoSource()}, "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
_, err = newEngineWithPromptFS(context.Background(), loaded, nil, promptFS)
|
|
||||||
if err == nil || !IsAssetError(err) {
|
|
||||||
t.Fatalf("broken embedded prompt was not classified as an asset error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestOperatorPromptCanRepairInvalidEmbeddedPrompt(t *testing.T) {
|
|
||||||
promptFS := copyEmbeddedPromptFilesystem(t)
|
|
||||||
assetPath := path.Join(prompts.AssetRoot, "modules.grammar.proposal.yaml")
|
|
||||||
promptFS[assetPath] = &fstest.MapFile{Data: []byte("collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: []\n")}
|
|
||||||
dir := t.TempDir()
|
|
||||||
for name, content := range map[string]string{
|
|
||||||
"config.yml": "version: 3\n",
|
|
||||||
"prompts.yml": "collections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages:\n - role: user\n content: operator message\n output:\n format: text\n validation_mode: none\n",
|
|
||||||
} {
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0600); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
engine, err := newEngineWithPromptFS(context.Background(), loaded, nil, promptFS)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("valid final configuration rejected: %v", err)
|
|
||||||
}
|
|
||||||
if engine == nil {
|
|
||||||
t.Fatal("engine was not retained")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
ck "go.maximumdirect.net/configkit"
|
ck "go.maximumdirect.net/configkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@ func (r rejectingTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestRuntimeInspectionDoesNotRequireCredentialsOrProvider(t *testing.T) {
|
func TestRuntimeInspectionDoesNotRequireCredentialsOrProvider(t *testing.T) {
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.NoSource()}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
42
internal/framework/llm/shared_sources_test.go
Normal file
42
internal/framework/llm/shared_sources_test.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package llm
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
|
ck "go.maximumdirect.net/configkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRuntimeCapturesSharedSources(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
project := filepath.Join(root, "project")
|
||||||
|
if err := os.MkdirAll(filepath.Join(project, "prompts", "nested"), 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for name, contents := range map[string]string{
|
||||||
|
"config.yml": "version: 3\n",
|
||||||
|
"prompts/nested/catalog.yml": "collections:\n sample:\n prompts:\n - id: fixture\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n",
|
||||||
|
"prompts/nested/message.txt": "source-local",
|
||||||
|
} {
|
||||||
|
if err := os.WriteFile(filepath.Join(project, name), []byte(contents), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(project, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"config.yml", "prompts/nested/catalog.yml", "prompts/nested/message.txt"} {
|
||||||
|
if !slices.Contains(runtime.SourcePaths, filepath.Join(project, name)) {
|
||||||
|
t.Errorf("missing %s in %v", name, runtime.SourcePaths)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,16 @@
|
|||||||
package llm
|
package llm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
ck "go.maximumdirect.net/configkit"
|
ck "go.maximumdirect.net/configkit"
|
||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
"go.yaml.in/yaml/v4"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func capturedSourcePaths(engine *pk.Engine) ([]string, error) {
|
func capturedSourcePaths(loaded *ck.Result[appconfig.Config]) ([]string, error) {
|
||||||
inspection, err := engine.InspectConfiguration()
|
sources := loaded.Sources()
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("inspect configuration: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
sources := inspection.Sources()
|
|
||||||
hostByID := make(map[string]string, len(sources))
|
hostByID := make(map[string]string, len(sources))
|
||||||
paths := make(map[string]struct{}, len(sources))
|
paths := make(map[string]struct{}, len(sources))
|
||||||
for _, source := range sources {
|
for _, source := range sources {
|
||||||
@@ -26,52 +19,36 @@ func capturedSourcePaths(engine *pk.Engine) ([]string, error) {
|
|||||||
paths[source.Path] = struct{}{}
|
paths[source.Path] = struct{}{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
metadata := loaded.Metadata()
|
||||||
if len(hostByID) == 0 {
|
captureFile := func(fieldPath ck.Path, filename *string) {
|
||||||
return []string{}, nil
|
if filename == nil {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
field, ok := metadata.Lookup(fieldPath)
|
||||||
type promptList []struct {
|
if !ok {
|
||||||
Messages []struct {
|
return
|
||||||
ContentFile *string `yaml:"content_file"`
|
|
||||||
} `yaml:"messages"`
|
|
||||||
}
|
}
|
||||||
var effective struct {
|
for _, location := range field.Origin.Locations {
|
||||||
Prompts promptList `yaml:"prompts"`
|
if host := hostByID[location.SourceID]; host != "" {
|
||||||
Collections map[string]struct {
|
paths[filepath.Join(filepath.Dir(host), filepath.FromSlash(*filename))] = struct{}{}
|
||||||
Prompts promptList `yaml:"prompts"`
|
|
||||||
} `yaml:"collections"`
|
|
||||||
}
|
}
|
||||||
var projection bytes.Buffer
|
|
||||||
if err := inspection.WriteEffective(&projection); err != nil {
|
|
||||||
return nil, fmt.Errorf("write effective PromptKit configuration: %w", err)
|
|
||||||
}
|
}
|
||||||
if err := yaml.Unmarshal(projection.Bytes(), &effective); err != nil {
|
|
||||||
return nil, fmt.Errorf("decode effective PromptKit message paths: %w", err)
|
|
||||||
}
|
}
|
||||||
metadata := inspection.Metadata()
|
capture := func(base ck.Path, prompts []pk.PromptSettings) {
|
||||||
capture := func(base ck.Path, prompts promptList) {
|
|
||||||
for i, prompt := range prompts {
|
for i, prompt := range prompts {
|
||||||
messages := base.Index(i).Key("messages")
|
record := base.Index(i)
|
||||||
|
if prompt.Output != nil {
|
||||||
|
captureFile(record.Key("output").Key("schema_file"), prompt.Output.SchemaFile)
|
||||||
|
}
|
||||||
for j, message := range prompt.Messages {
|
for j, message := range prompt.Messages {
|
||||||
if message.ContentFile == nil {
|
captureFile(record.Key("messages").Index(j).Key("content_file"), message.ContentFile)
|
||||||
continue
|
|
||||||
}
|
|
||||||
field, ok := metadata.Lookup(messages.Index(j).Key("content_file"))
|
|
||||||
if !ok || len(field.Origin.Locations) != 1 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if host := hostByID[field.Origin.Locations[0].SourceID]; host != "" {
|
|
||||||
paths[filepath.Join(filepath.Dir(host), filepath.FromSlash(*message.ContentFile))] = struct{}{}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
capture(ck.Keys("promptkit", "prompts"), loaded.Config.PromptKit.Prompts)
|
||||||
|
for name, collection := range loaded.Config.PromptKit.Collections {
|
||||||
|
capture(ck.Keys("promptkit", "collections", name, "prompts"), collection.Prompts)
|
||||||
}
|
}
|
||||||
capture(ck.Keys("prompts"), effective.Prompts)
|
|
||||||
for name, collection := range effective.Collections {
|
|
||||||
capture(ck.Keys("collections", name, "prompts"), collection.Prompts)
|
|
||||||
}
|
|
||||||
|
|
||||||
result := make([]string, 0, len(paths))
|
result := make([]string, 0, len(paths))
|
||||||
for path := range paths {
|
for path := range paths {
|
||||||
result = append(result, path)
|
result = append(result, path)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"sort"
|
"sort"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
ck "go.maximumdirect.net/configkit"
|
ck "go.maximumdirect.net/configkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -17,10 +17,12 @@ func TestRuntimeTracksCapturedConfigurationAndInheritedMessageFiles(t *testing.T
|
|||||||
for name, content := range map[string]string{
|
for name, content := range map[string]string{
|
||||||
"config.yml": "version: 3\n",
|
"config.yml": "version: 3\n",
|
||||||
"prompts.yml": "config:\n imports:\n - path: catalog/arbitrary-name.yaml\n required: true\n",
|
"prompts.yml": "config:\n imports:\n - path: catalog/arbitrary-name.yaml\n required: true\n",
|
||||||
"catalog/arbitrary-name.yaml": "prompts:\n - id: source\n messages:\n - role: user\n content_file: instruction.md\n output:\n format: text\n validation_mode: none\n",
|
"catalog/arbitrary-name.yaml": "prompts:\n - id: source\n messages:\n - role: user\n content_file: instruction.md\n output:\n format: json\n validation_mode: json_schema\n schema_file: schema.json\n",
|
||||||
|
"catalog/schema.json": "{}",
|
||||||
|
"prompts/shared/schema.json": "{}",
|
||||||
"catalog/instruction.md": "Captured operator message.\n",
|
"catalog/instruction.md": "Captured operator message.\n",
|
||||||
"prompts/nested/override.yaml": "prompts:\n - id: literal-child\n extends: {id: source}\n",
|
"prompts/nested/override.yaml": "prompts:\n - id: literal-child\n extends: {id: source}\n",
|
||||||
"prompts/nested/collection.yml": "collections:\n operator:\n prompts:\n - id: local\n messages:\n - role: user\n content_file: ../shared/collection.md\n output:\n format: text\n validation_mode: none\n",
|
"prompts/nested/collection.yml": "collections:\n operator:\n prompts:\n - id: local\n messages:\n - role: user\n content_file: ../shared/collection.md\n output:\n format: json\n validation_mode: json_schema\n schema_file: ../shared/schema.json\n",
|
||||||
"prompts/shared/collection.md": "Message in a collection.\n",
|
"prompts/shared/collection.md": "Message in a collection.\n",
|
||||||
} {
|
} {
|
||||||
file := filepath.Join(dir, name)
|
file := filepath.Join(dir, name)
|
||||||
@@ -31,7 +33,7 @@ func TestRuntimeTracksCapturedConfigurationAndInheritedMessageFiles(t *testing.T
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -40,9 +42,12 @@ func TestRuntimeTracksCapturedConfigurationAndInheritedMessageFiles(t *testing.T
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
want := []string{
|
want := []string{
|
||||||
|
filepath.Join(dir, "config.yml"),
|
||||||
filepath.Join(dir, "prompts.yml"),
|
filepath.Join(dir, "prompts.yml"),
|
||||||
filepath.Join(dir, "catalog/arbitrary-name.yaml"),
|
filepath.Join(dir, "catalog/arbitrary-name.yaml"),
|
||||||
filepath.Join(dir, "catalog/instruction.md"),
|
filepath.Join(dir, "catalog/instruction.md"),
|
||||||
|
filepath.Join(dir, "catalog/schema.json"),
|
||||||
|
filepath.Join(dir, "prompts/shared/schema.json"),
|
||||||
filepath.Join(dir, "prompts/nested/override.yaml"),
|
filepath.Join(dir, "prompts/nested/override.yaml"),
|
||||||
filepath.Join(dir, "prompts/nested/collection.yml"),
|
filepath.Join(dir, "prompts/nested/collection.yml"),
|
||||||
filepath.Join(dir, "prompts/shared/collection.md"),
|
filepath.Join(dir, "prompts/shared/collection.md"),
|
||||||
|
|||||||
@@ -1,27 +1,17 @@
|
|||||||
package processreport
|
package processreport
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
|
||||||
"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/runner"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
func mapLLMSummary(source llm.ExecutionSummary) reporting.LLMSummary {
|
|
||||||
metric := func(value llm.TokenCount) reporting.TokenMetric {
|
|
||||||
return reporting.TokenMetric{Value: value.Value, Known: value.Known, Complete: value.Complete}
|
|
||||||
}
|
|
||||||
return reporting.LLMSummary{
|
|
||||||
LogicalCalls: source.LogicalCalls, ProviderAttempts: source.ProviderAttempts,
|
|
||||||
TransientRetries: source.TransientRetries, StructuralRepairs: source.StructuralRepairs,
|
|
||||||
Usage: reporting.LLMUsage{Prompt: metric(source.Usage.Prompt), Completion: metric(source.Usage.Completion), Total: metric(source.Usage.Total), Cached: metric(source.Usage.Cached), CacheWrite: metric(source.Usage.CacheWrite)},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type executionCall struct {
|
type executionCall struct {
|
||||||
TerminalCoverageComplete bool `json:"terminal_coverage_complete"`
|
|
||||||
RequestedPromptID string `json:"requested_prompt_id,omitempty"`
|
RequestedPromptID string `json:"requested_prompt_id,omitempty"`
|
||||||
CallID uint64 `json:"call_id"`
|
CallID uint64 `json:"call_id"`
|
||||||
Context structuredoutput.DiagnosticContext `json:"context"`
|
Context structuredoutput.DiagnosticContext `json:"context"`
|
||||||
@@ -30,70 +20,58 @@ type executionCall struct {
|
|||||||
Finished *time.Time `json:"finished,omitempty"`
|
Finished *time.Time `json:"finished,omitempty"`
|
||||||
ElapsedMS int64 `json:"elapsed_ms"`
|
ElapsedMS int64 `json:"elapsed_ms"`
|
||||||
Failure structuredoutput.FailureKind `json:"failure,omitempty"`
|
Failure structuredoutput.FailureKind `json:"failure,omitempty"`
|
||||||
Summary reporting.LLMSummary `json:"summary"`
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type executionEvent struct {
|
// BuildLLMExecution preserves native evidence with Audita's logical-call context.
|
||||||
CallID uint64 `json:"call_id"`
|
|
||||||
Context structuredoutput.DiagnosticContext `json:"context"`
|
|
||||||
Kind string `json:"kind"`
|
|
||||||
RunID string `json:"run_id,omitempty"`
|
|
||||||
Time time.Time `json:"time"`
|
|
||||||
BackendID string `json:"backend_id,omitempty"`
|
|
||||||
ProfileID string `json:"profile_id,omitempty"`
|
|
||||||
Model string `json:"model,omitempty"`
|
|
||||||
Generation *uint64 `json:"generation,omitempty"`
|
|
||||||
Attempt *uint64 `json:"attempt,omitempty"`
|
|
||||||
Dispatched bool `json:"dispatched"`
|
|
||||||
CapacityWaitMS int64 `json:"capacity_wait_ms"`
|
|
||||||
GenerationMS int64 `json:"generation_ms"`
|
|
||||||
RetryDelayMS int64 `json:"retry_delay_ms"`
|
|
||||||
DurationMS int64 `json:"duration_ms"`
|
|
||||||
Outcome string `json:"outcome,omitempty"`
|
|
||||||
Failure string `json:"failure,omitempty"`
|
|
||||||
StatusCode int `json:"status_code,omitempty"`
|
|
||||||
RetriesExhausted bool `json:"retries_exhausted,omitempty"`
|
|
||||||
Attempts uint64 `json:"attempts"`
|
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage reporting.LLMUsage `json:"usage"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildLLMExecution serializes only safe observation fields and millisecond durations.
|
|
||||||
func BuildLLMExecution(snapshot llm.ObservationSnapshot) any {
|
func BuildLLMExecution(snapshot llm.ObservationSnapshot) any {
|
||||||
calls := make([]executionCall, 0, len(snapshot.Calls))
|
calls := make([]executionCall, 0, len(snapshot.Calls))
|
||||||
events := make([]executionEvent, 0, len(snapshot.Events))
|
events := make([]llm.ExecutionObservation, len(snapshot.Events))
|
||||||
eventsByCall := make(map[uint64][]llm.ExecutionObservation, len(snapshot.Calls))
|
copy(events, snapshot.Events)
|
||||||
for _, event := range snapshot.Events {
|
groups := make(map[uint64]*pk.ExecutionGroup, len(snapshot.Calls))
|
||||||
eventsByCall[event.CallID] = append(eventsByCall[event.CallID], event)
|
for _, event := range events {
|
||||||
|
group := groups[event.CallID]
|
||||||
|
if group == nil {
|
||||||
|
group = &pk.ExecutionGroup{}
|
||||||
|
groups[event.CallID] = group
|
||||||
|
}
|
||||||
|
group.Observe(event.PromptKit)
|
||||||
}
|
}
|
||||||
for _, call := range snapshot.Calls {
|
for _, call := range snapshot.Calls {
|
||||||
group := llm.ObservationSnapshot{Calls: []llm.LogicalCall{call}, Events: eventsByCall[call.CallID]}
|
group := groups[call.CallID]
|
||||||
summary := llm.Summarize(group)
|
if group == nil {
|
||||||
|
group = &pk.ExecutionGroup{}
|
||||||
|
}
|
||||||
var finished *time.Time
|
var finished *time.Time
|
||||||
if !call.Finished.IsZero() {
|
if !call.Finished.IsZero() {
|
||||||
value := call.Finished
|
value := call.Finished
|
||||||
finished = &value
|
finished = &value
|
||||||
}
|
}
|
||||||
calls = append(calls, executionCall{TerminalCoverageComplete: summary.TerminalCoverageComplete, RequestedPromptID: call.RequestedPromptID, CallID: call.CallID, Context: call.Context, Prompt: call.Prompt, Started: call.Started, Finished: finished, ElapsedMS: call.WallDuration.Milliseconds(), Failure: call.Failure, Summary: mapLLMSummary(summary)})
|
calls = append(calls, executionCall{
|
||||||
}
|
RequestedPromptID: call.RequestedPromptID, CallID: call.CallID, Context: call.Context,
|
||||||
for _, event := range snapshot.Events {
|
Prompt: call.Prompt, Started: call.Started, Finished: finished,
|
||||||
var generation, attempt *uint64
|
ElapsedMS: call.WallDuration.Milliseconds(), Failure: call.Failure,
|
||||||
if event.Generation != 0 {
|
PromptKit: orderedMembers(group.Snapshot()),
|
||||||
value := event.Generation
|
})
|
||||||
generation = &value
|
|
||||||
}
|
|
||||||
if event.Attempt != 0 {
|
|
||||||
value := event.Attempt
|
|
||||||
attempt = &value
|
|
||||||
}
|
|
||||||
events = append(events, executionEvent{CallID: event.CallID, Context: event.Context, Kind: event.Kind, RunID: event.RunID, Time: event.Time, BackendID: event.BackendID, ProfileID: event.ProfileID, Model: event.Model, Generation: generation, Attempt: attempt, Dispatched: event.Dispatched, CapacityWaitMS: event.CapacityWait.Milliseconds(), GenerationMS: event.GenerationDuration.Milliseconds(), RetryDelayMS: event.RetryDelay.Milliseconds(), DurationMS: event.Duration.Milliseconds(), Outcome: event.Outcome, Failure: event.Failure, StatusCode: event.StatusCode, RetriesExhausted: event.RetriesExhausted, Attempts: event.Attempts, TransientRetries: event.TransientRetries, StructuralRepairs: event.StructuralRepairs, Usage: mapLLMSummary(llm.ExecutionSummary{Usage: event.Usage}).Usage})
|
|
||||||
}
|
}
|
||||||
return struct {
|
return struct {
|
||||||
Summary llm.ExecutionSummary `json:"summary"`
|
Summary llm.ExecutionSummary `json:"summary"`
|
||||||
Calls []executionCall `json:"calls"`
|
Calls []executionCall `json:"calls"`
|
||||||
Events []executionEvent `json:"events"`
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
}{llm.Summarize(snapshot), calls, events}
|
}{orderedExecutionSummary(snapshot), calls, events}
|
||||||
|
}
|
||||||
|
|
||||||
|
// orderedMembers changes only the detached diagnostic presentation.
|
||||||
|
func orderedMembers(summary pk.ExecutionGroupSummary) pk.ExecutionGroupSummary {
|
||||||
|
summary.Members = slices.Clone(summary.Members)
|
||||||
|
slices.SortFunc(summary.Members, func(a, b pk.ExecutionGroupMember) int { return strings.Compare(a.RunID, b.RunID) })
|
||||||
|
return summary
|
||||||
|
}
|
||||||
|
|
||||||
|
func orderedExecutionSummary(snapshot llm.ObservationSnapshot) llm.ExecutionSummary {
|
||||||
|
summary := llm.Summarize(snapshot)
|
||||||
|
summary.PromptKit = orderedMembers(summary.PromptKit)
|
||||||
|
return summary
|
||||||
}
|
}
|
||||||
|
|
||||||
// IndexLLMObservations assigns the same proposal identities used by the ledger.
|
// IndexLLMObservations assigns the same proposal identities used by the ledger.
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
||||||
"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/runner"
|
||||||
"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"
|
||||||
)
|
)
|
||||||
@@ -19,14 +21,14 @@ func TestExecutionReportingKeepsSafeMilliseconds(t *testing.T) {
|
|||||||
{CallID: 1, Context: structuredoutput.DiagnosticContext{Role: "proposal", ModuleInstance: "grammar-1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "primary", ProfileID: "draft", Model: "m"}, Started: start, Finished: start.Add(1500 * time.Millisecond), WallDuration: 1500 * time.Millisecond},
|
{CallID: 1, Context: structuredoutput.DiagnosticContext{Role: "proposal", ModuleInstance: "grammar-1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "primary", ProfileID: "draft", Model: "m"}, Started: start, Finished: start.Add(1500 * time.Millisecond), WallDuration: 1500 * time.Millisecond},
|
||||||
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation"}, Prompt: structuredoutput.PromptMetadata{BackendID: "secondary"}, Started: start, Finished: start.Add(5 * time.Millisecond), WallDuration: 5 * time.Millisecond, Failure: structuredoutput.FailureRuntime},
|
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation"}, Prompt: structuredoutput.PromptMetadata{BackendID: "secondary"}, Started: start, Finished: start.Add(5 * time.Millisecond), WallDuration: 5 * time.Millisecond, Failure: structuredoutput.FailureRuntime},
|
||||||
},
|
},
|
||||||
Events: []llm.ExecutionObservation{{CallID: 1, RunID: "run-1", Kind: string(pk.ExecutionFinished), BackendID: "primary", Attempts: 2, TransientRetries: 1, CapacityWait: 20 * time.Millisecond, GenerationDuration: 500 * time.Millisecond, RetryDelay: 100 * time.Millisecond}},
|
Events: []llm.ExecutionObservation{{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "run-1", Kind: pk.ExecutionFinished, BackendID: "primary", Attempts: 2, TransientRetries: 1, CapacityWait: 20 * time.Millisecond, GenerationDuration: 500 * time.Millisecond, RetryDelay: 100 * time.Millisecond}}},
|
||||||
}
|
}
|
||||||
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
serialized := string(raw)
|
serialized := string(raw)
|
||||||
if !strings.Contains(serialized, `"elapsed_ms":1500`) || !strings.Contains(serialized, `"generation_ms":500`) || strings.Contains(serialized, "_ns") || strings.Contains(serialized, `"attempt":0`) || strings.Contains(serialized, `"section_index":0`) {
|
if !strings.Contains(serialized, `"elapsed_ms":1500`) || !strings.Contains(serialized, `"promptkit"`) || !strings.Contains(serialized, `"run-1"`) {
|
||||||
t.Fatalf("execution serialization: %s", serialized)
|
t.Fatalf("execution serialization: %s", serialized)
|
||||||
}
|
}
|
||||||
if !strings.Contains(serialized, `"calls"`) || !strings.Contains(serialized, `"events"`) {
|
if !strings.Contains(serialized, `"calls"`) || !strings.Contains(serialized, `"events"`) {
|
||||||
@@ -34,9 +36,37 @@ func TestExecutionReportingKeepsSafeMilliseconds(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIndexedExecutionRetainsNativeEvidence(t *testing.T) {
|
||||||
|
section, proposal := 2, 1
|
||||||
|
ctx := structuredoutput.DiagnosticContext{ModuleInstance: "grammar", SectionIndex: §ion, ProposalIndex: &proposal}
|
||||||
|
event := pk.ExecutionEvent{RunID: "native", Kind: pk.ExecutionFinished,
|
||||||
|
Usage: pk.ObservedTokenUsage{ReasoningTokens: pk.ObservedTokenCount{Value: 3, Known: true, Complete: true}, CachedTokens: pk.ObservedTokenCount{Known: true, Complete: true}},
|
||||||
|
CostUSD: pk.ObservedCost{Value: 0.25, Known: true, Complete: true, Source: pk.CostSourceProvider}}
|
||||||
|
snapshot := llm.ObservationSnapshot{Calls: []llm.LogicalCall{{CallID: 1, Context: ctx}}, Events: []llm.ExecutionObservation{{CallID: 1, Context: ctx, PromptKit: event}}}
|
||||||
|
indexed := IndexLLMObservations(snapshot, []runner.WorkUnitOutcome{{ModuleInstance: "grammar", Section: contracts.SectionMetadata{Index: section}, ProposalIndexOffset: 4}})
|
||||||
|
if *indexed.Calls[0].Context.ProposalIndex != 5 || *indexed.Events[0].Context.ProposalIndex != 5 || indexed.Events[0].PromptKit != event {
|
||||||
|
t.Fatalf("indexed evidence = %+v", indexed)
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(BuildLLMExecution(indexed))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var decoded struct {
|
||||||
|
Summary llm.ExecutionSummary `json:"summary"`
|
||||||
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
usage := decoded.Summary.PromptKit.Usage
|
||||||
|
if usage.ReasoningTokens.Value != 3 || !usage.ReasoningTokens.Known || !usage.CachedTokens.Known || usage.CachedTokens.Value != 0 || decoded.Summary.PromptKit.CostUSD != event.CostUSD || decoded.Events[0].PromptKit.RunID != "native" {
|
||||||
|
t.Fatalf("serialized native evidence = %+v", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestReportSummaryAvailability(t *testing.T) {
|
func TestReportSummaryAvailability(t *testing.T) {
|
||||||
got := mapLLMSummary(llm.Summarize(llm.ObservationSnapshot{}))
|
got := llm.Summarize(llm.ObservationSnapshot{})
|
||||||
if got.LogicalCalls != 0 || !got.Usage.Total.Known || !got.Usage.Total.Complete {
|
if got.LogicalCalls != 0 || !got.PromptKit.Usage.TotalTokens.Known || !got.PromptKit.Usage.TotalTokens.Complete {
|
||||||
t.Fatalf("initialized empty summary: %+v", got)
|
t.Fatalf("initialized empty summary: %+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +76,7 @@ func BenchmarkExecutionReports(b *testing.B) {
|
|||||||
snapshot := llm.ObservationSnapshot{}
|
snapshot := llm.ObservationSnapshot{}
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
snapshot.Calls = append(snapshot.Calls, llm.LogicalCall{CallID: uint64(i + 1), Prompt: structuredoutput.PromptMetadata{BackendID: "local"}, Context: structuredoutput.DiagnosticContext{ModuleInstance: "grammar", Role: "proposal"}})
|
snapshot.Calls = append(snapshot.Calls, llm.LogicalCall{CallID: uint64(i + 1), Prompt: structuredoutput.PromptMetadata{BackendID: "local"}, Context: structuredoutput.DiagnosticContext{ModuleInstance: "grammar", Role: "proposal"}})
|
||||||
snapshot.Events = append(snapshot.Events, llm.ExecutionObservation{RunID: fmt.Sprint(i), CallID: uint64(i + 1), Kind: string(pk.ExecutionFinished), Attempts: 1})
|
snapshot.Events = append(snapshot.Events, llm.ExecutionObservation{CallID: uint64(i + 1), PromptKit: pk.ExecutionEvent{RunID: fmt.Sprint(i), Kind: pk.ExecutionFinished, Attempts: 1}})
|
||||||
}
|
}
|
||||||
b.Run(fmt.Sprintf("execution/%d", n), func(b *testing.B) {
|
b.Run(fmt.Sprintf("execution/%d", n), func(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
@@ -64,9 +94,9 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation", ModuleInstance: "grammar_1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "a"}},
|
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation", ModuleInstance: "grammar_1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "a"}},
|
||||||
},
|
},
|
||||||
Events: []llm.ExecutionObservation{
|
Events: []llm.ExecutionObservation{
|
||||||
{CallID: 1, RunID: "run-1", Kind: string(pk.ExecutionFinished), Attempts: 1, Usage: llm.Usage{Total: llm.TokenCount{Value: 7, Known: true, Complete: true}}},
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "run-1", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{TotalTokens: pk.ObservedTokenCount{Value: 7, Known: true, Complete: true}}}},
|
||||||
{CallID: 3, RunID: "run-3", Kind: string(pk.ExecutionFinished), Attempts: 1},
|
{CallID: 3, PromptKit: pk.ExecutionEvent{RunID: "run-3", Kind: pk.ExecutionFinished, Attempts: 1}},
|
||||||
{CallID: 2, RunID: "run-2", Kind: string(pk.ExecutionFinished), Attempts: 1},
|
{CallID: 2, PromptKit: pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionFinished, Attempts: 1}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
@@ -75,7 +105,7 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var execution struct {
|
var execution struct {
|
||||||
Calls []executionCall `json:"calls"`
|
Calls []executionCall `json:"calls"`
|
||||||
Events []executionEvent `json:"events"`
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &execution); err != nil {
|
if err := json.Unmarshal(raw, &execution); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -90,7 +120,83 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
t.Fatal("event order changed")
|
t.Fatal("event order changed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if execution.Calls[1].Summary.Usage.Total.Value != 7 || !execution.Calls[1].Summary.Usage.Total.Complete || execution.Calls[0].Summary.Usage.Total.Known {
|
if execution.Calls[1].PromptKit.Usage.TotalTokens.Value != 7 || !execution.Calls[1].PromptKit.Usage.TotalTokens.Complete || execution.Calls[0].PromptKit.Usage.TotalTokens.Known {
|
||||||
t.Fatalf("call usage: %+v", execution.Calls)
|
t.Fatalf("call usage: %+v", execution.Calls)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPerCallGroupsRetainCoverageAndDeduplicateTerminals(t *testing.T) {
|
||||||
|
terminal := pk.ExecutionEvent{RunID: "complete", Kind: pk.ExecutionFinished, Attempts: 2, TransientRetries: 1}
|
||||||
|
snapshot := llm.ObservationSnapshot{
|
||||||
|
Calls: []llm.LogicalCall{{CallID: 3}, {CallID: 1}, {CallID: 2}},
|
||||||
|
Events: []llm.ExecutionObservation{
|
||||||
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "pending", Kind: pk.ExecutionAttempt}},
|
||||||
|
{CallID: 2, PromptKit: terminal}, {CallID: 2, PromptKit: terminal},
|
||||||
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "pending", Kind: pk.ExecutionAttempt}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var report struct {
|
||||||
|
Calls []executionCall
|
||||||
|
Events []llm.ExecutionObservation
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &report); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(report.Events) != 4 || len(report.Calls) != 3 {
|
||||||
|
t.Fatal(string(raw))
|
||||||
|
}
|
||||||
|
empty, pending, complete := report.Calls[0], report.Calls[1], report.Calls[2]
|
||||||
|
if empty.CallID != 3 || len(empty.PromptKit.Members) != 0 || !empty.PromptKit.TerminalCoverageComplete || !empty.PromptKit.Usage.TotalTokens.Known {
|
||||||
|
t.Fatalf("empty: %+v", empty)
|
||||||
|
}
|
||||||
|
if pending.CallID != 1 || pending.PromptKit.TerminalCoverageComplete || pending.PromptKit.Usage.TotalTokens.Known {
|
||||||
|
t.Fatalf("pending: %+v", pending)
|
||||||
|
}
|
||||||
|
if complete.CallID != 2 || complete.PromptKit.Attempts != 2 || complete.PromptKit.TransientRetries != 1 || !complete.PromptKit.TerminalCoverageComplete {
|
||||||
|
t.Fatalf("complete: %+v", complete)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeMembersHaveStableDetachedPresentation(t *testing.T) {
|
||||||
|
members := []pk.ExecutionGroupMember{{RunID: "z", TerminalObserved: true}, {RunID: "a"}}
|
||||||
|
snapshot := llm.ObservationSnapshot{
|
||||||
|
Calls: []llm.LogicalCall{{CallID: 1}},
|
||||||
|
Group: &pk.ExecutionGroupSummary{Members: members, Attempts: 7},
|
||||||
|
Events: []llm.ExecutionObservation{
|
||||||
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "z", Kind: pk.ExecutionFinished, Attempts: 2}},
|
||||||
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "a", Kind: pk.ExecutionAttempt}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var report struct {
|
||||||
|
Summary llm.ExecutionSummary
|
||||||
|
Calls []executionCall
|
||||||
|
Events []llm.ExecutionObservation
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &report); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, summary := range []pk.ExecutionGroupSummary{report.Summary.PromptKit, report.Calls[0].PromptKit} {
|
||||||
|
if len(summary.Members) != 2 || summary.Members[0].RunID != "a" || summary.Members[1].RunID != "z" || summary.Members[0].TerminalObserved || !summary.Members[1].TerminalObserved {
|
||||||
|
t.Fatalf("members: %+v", summary.Members)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if members[0].RunID != "z" || report.Summary.PromptKit.Attempts != 7 || report.Calls[0].PromptKit.Attempts != 2 || report.Events[0].PromptKit.RunID != "z" {
|
||||||
|
t.Fatal("rendering changed evidence or input")
|
||||||
|
}
|
||||||
|
snapshot.Group.Members = []pk.ExecutionGroupMember{members[1], members[0]}
|
||||||
|
again, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if string(raw) != string(again) {
|
||||||
|
t.Fatal("membership permutation changed presentation")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"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/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/llm"
|
||||||
@@ -46,7 +47,7 @@ func TestRepairedProposalStillFacesDomainChecks(t *testing.T) {
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles:\n - {id: base, endpoint: 'https://example.invalid/v1', model: local-model, api_key_required: false}\n"), 0600); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles:\n - {id: base, endpoint: 'https://example.invalid/v1', model: local-model, api_key_required: false}\n"), 0600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(main)}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -54,8 +55,8 @@ func TestRepairedProposalStillFacesDomainChecks(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
settings := loaded.Config.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)
|
||||||
|
|||||||
@@ -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,7 +85,7 @@ 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
|
||||||
@@ -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},
|
||||||
|
|||||||
@@ -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"`
|
||||||
|
|||||||
@@ -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[:]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -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()
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
|
||||||
"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/schema"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
|
||||||
@@ -17,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"
|
||||||
@@ -56,7 +56,7 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) {
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(resources), 0600); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(resources), 0600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(main)}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -100,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
|
||||||
}}
|
}}
|
||||||
@@ -158,7 +157,7 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) {
|
|||||||
t.Fatalf("unfinished/cause lost: %+v", call)
|
t.Fatalf("unfinished/cause lost: %+v", call)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if got := llm.Summarize(snapshot); got.ProviderAttempts != 1 {
|
if got := llm.Summarize(snapshot); got.PromptKit.Attempts != 1 {
|
||||||
t.Fatalf("attempt count: %+v", got)
|
t.Fatalf("attempt count: %+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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"
|
||||||
@@ -16,6 +15,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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/core/schema"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
||||||
@@ -488,7 +488,7 @@ func (c *repairClient) Coordinate(ctx context.Context, _ *structuredoutput.Excha
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(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)
|
||||||
}
|
}
|
||||||
@@ -513,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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ func (s *sectionInteractions) write(offset int) {
|
|||||||
// Earlier snapshots keep their own lengths while additional turns add messages.
|
// Earlier snapshots keep their own lengths while additional turns add messages.
|
||||||
type repairHistory struct {
|
type repairHistory struct {
|
||||||
messages []structuredoutput.Message
|
messages []structuredoutput.Message
|
||||||
|
native any
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *structuredoutput.PreparedSnapshot {
|
func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *structuredoutput.PreparedSnapshot {
|
||||||
@@ -55,6 +56,10 @@ func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *str
|
|||||||
}
|
}
|
||||||
snapshot := *prepared
|
snapshot := *prepared
|
||||||
snapshot.Messages = slices.Clip(h.messages)
|
snapshot.Messages = slices.Clip(h.messages)
|
||||||
|
if shareable, ok := prepared.PromptKit.(interface{ ShareMessages(any) any }); ok {
|
||||||
|
snapshot.PromptKit = shareable.ShareMessages(h.native)
|
||||||
|
}
|
||||||
|
h.native = snapshot.PromptKit
|
||||||
return &snapshot
|
return &snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"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/core/schema"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
||||||
@@ -61,7 +62,7 @@ func TestLaterSectionsValidateWhileEarlierProposalUsesSharedBackend(t *testing.T
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(resources), 0600); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(resources), 0600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(path)}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(path)}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -259,7 +260,22 @@ func TestLaterRepairArtifactsUseOrderedProposalIndices(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var request structuredoutput.PreparedSnapshot
|
var request structuredoutput.PreparedSnapshot
|
||||||
readInteraction(t, attempt.Artifacts.RequestPayloadPath, &request)
|
readInteraction(t, attempt.Artifacts.RequestPayloadPath, &request)
|
||||||
if !reflect.DeepEqual(&request, captured[i]) {
|
want, err := json.Marshal(captured[i])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := json.Marshal(&request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var gotValue, wantValue any
|
||||||
|
if err := json.Unmarshal(got, &gotValue); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(want, &wantValue); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(gotValue, wantValue) {
|
||||||
t.Fatalf("request %d did not preserve prepared evidence", i+1)
|
t.Fatalf("request %d did not preserve prepared evidence", i+1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,12 +22,11 @@ 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:"-"`
|
||||||
@@ -62,6 +60,7 @@ type Response struct {
|
|||||||
// PreparedSnapshot is the exact rendered request snapshot. Its messages may
|
// PreparedSnapshot is the exact rendered request snapshot. Its messages may
|
||||||
// contain transcript and glossary content and belong only in protected diagnostics.
|
// contain transcript and glossary content and belong only in protected diagnostics.
|
||||||
type PreparedSnapshot struct {
|
type PreparedSnapshot struct {
|
||||||
|
PromptKit any `json:"promptkit,omitempty"`
|
||||||
Messages []Message `json:"messages"`
|
Messages []Message `json:"messages"`
|
||||||
Prompt PromptMetadata `json:"prompt"`
|
Prompt PromptMetadata `json:"prompt"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
|
||||||
"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"
|
||||||
@@ -84,7 +84,7 @@ func testValidationClient(t *testing.T, transport http.RoundTripper) structuredo
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles:\n - {id: base, endpoint: 'https://example.invalid/v1', model: local-model, api_key_required: false}\n"), 0600); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles:\n - {id: base, endpoint: 'https://example.invalid/v1', model: local-model, api_key_required: false}\n"), 0600); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
loaded, err := config.Load(ck.Input{Source: ck.File(main)}, "")
|
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -92,8 +92,8 @@ func testValidationClient(t *testing.T, transport http.RoundTripper) structuredo
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
settings := loaded.Config.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)
|
||||||
|
|||||||
@@ -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,7 +129,7 @@ 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
|
||||||
@@ -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),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
|||||||
35
internal/testsupport/promptfixture/budget.go
Normal file
35
internal/testsupport/promptfixture/budget.go
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
// Package promptfixture adapts complete prompt documents for controlled tests.
|
||||||
|
package promptfixture
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go.yaml.in/yaml/v4"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WithRepairAttempts changes prompt-owned budgets without depending on YAML layout.
|
||||||
|
func WithRepairAttempts(t testing.TB, data []byte, attempts int) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var document map[string]any
|
||||||
|
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var update func(map[string]any)
|
||||||
|
update = func(scope map[string]any) {
|
||||||
|
records, _ := scope["prompts"].([]any)
|
||||||
|
for _, record := range records {
|
||||||
|
prompt := record.(map[string]any)
|
||||||
|
output := prompt["output"].(map[string]any)
|
||||||
|
output["repair_attempts"] = attempts
|
||||||
|
}
|
||||||
|
collections, _ := scope["collections"].(map[string]any)
|
||||||
|
for _, collection := range collections {
|
||||||
|
update(collection.(map[string]any))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
update(document)
|
||||||
|
result, err := yaml.Marshal(document)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
42
internal/testsupport/promptfixture/budget_test.go
Normal file
42
internal/testsupport/promptfixture/budget_test.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package promptfixture
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go.yaml.in/yaml/v4"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBudgetIgnoresLayoutAndPreservesContract(t *testing.T) {
|
||||||
|
for _, input := range []string{
|
||||||
|
`prompts: [{output: {format: json, repair_attempts: 9}, id: test, messages: [{role: user, content: hello}]}]`,
|
||||||
|
"collections:\n test:\n prompts:\n - output:\n format: json\n messages: [{role: user, content: hello}]\n id: test\n",
|
||||||
|
} {
|
||||||
|
result := WithRepairAttempts(t, []byte(input), 2)
|
||||||
|
var doc struct {
|
||||||
|
Prompts []struct {
|
||||||
|
Output struct {
|
||||||
|
Format string
|
||||||
|
RepairAttempts int `yaml:"repair_attempts"`
|
||||||
|
}
|
||||||
|
Messages []struct{ Content string }
|
||||||
|
}
|
||||||
|
Collections map[string]struct {
|
||||||
|
Prompts []struct {
|
||||||
|
Output struct {
|
||||||
|
RepairAttempts int `yaml:"repair_attempts"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := yaml.Unmarshal(result, &doc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(doc.Prompts) > 0 {
|
||||||
|
p := doc.Prompts[0]
|
||||||
|
if p.Output.RepairAttempts != 2 || p.Output.Format != "json" || p.Messages[0].Content != "hello" {
|
||||||
|
t.Fatalf("lost contract: %s", result)
|
||||||
|
}
|
||||||
|
} else if doc.Collections["test"].Prompts[0].Output.RepairAttempts != 2 {
|
||||||
|
t.Fatalf("budget: %s", result)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user