68 Commits

Author SHA1 Message Date
973b24e466 Configure ignored local ReleaseKit token
All checks were successful
ci/woodpecker/tag/release Pipeline was successful
2026-11-27 04:25:36 +00:00
cbb2f768be Prepare v4.2.0 notes and retire completed plans 2026-11-27 04:19:36 +00:00
b96eeb57ba Report preflight smoke usage with its correct scope 2026-11-27 04:12:41 +00:00
f5cef61bb5 Update preflight roadmap completion status 2026-11-27 04:04:48 +00:00
7ba1846e63 Show progress for each preflight profile 2026-11-27 04:04:30 +00:00
2eae2a4af2 Explain native preflight failures 2026-11-27 04:03:24 +00:00
bed9424329 Record preflight usage reporting integration gap 2026-11-27 03:56:36 +00:00
330044b207 Record preflight review findings 2026-11-27 03:43:43 +00:00
7874ea648b Document and validate preflight readiness 2026-11-27 01:26:07 +00:00
a9ab8e59b3 Report preflight provider verification and usage 2026-11-27 01:22:58 +00:00
a0292a3ba0 Verify structured output for selected profiles 2026-11-27 01:21:08 +00:00
a980fbbb09 Add preflight command and run alias 2026-11-27 01:19:17 +00:00
b4bc5e5640 Run processing from the prepared invocation 2026-11-27 01:17:45 +00:00
2dc057b97e Prepare normalized processing plans and fixed chunks 2026-11-27 01:15:40 +00:00
e761512c1c Probe output destinations with temporary files 2026-11-27 01:11:57 +00:00
bd3a22754a Separate output checks from session creation 2026-11-27 01:10:44 +00:00
645931c5e3 Plan shared preflight preparation and provider checks 2026-11-27 01:06:24 +00:00
604ae631b3 Record preflight destination requirements and write probes 2026-11-26 23:57:36 +00:00
9dadd97ee6 Plan run as an alias for process 2026-11-26 23:03:11 +00:00
be2846847b Plan standalone preflight with shared readiness preparation 2026-11-26 23:02:45 +00:00
8411a69187 Record completed D&D overlay implementation 2026-11-26 21:30:08 +00:00
33d9e0428d Retire completed runtime glossary planning documents 2026-11-26 21:20:41 +00:00
1ebf39bd6f Document runtime glossary inheritance boundaries 2026-11-26 21:16:22 +00:00
51cb6b2059 Clarify collection guidance during correction repair 2026-11-26 21:15:29 +00:00
4b1812995f Preserve native glossary loading error classifications 2026-11-26 21:14:32 +00:00
bf3184cf0a Record runtime glossary review findings 2026-11-26 19:40:47 +00:00
889ac766a5 Document and verify runtime glossary workflows 2026-11-26 18:25:43 +00:00
e0445abe48 Include glossary guidance in proposal conversations 2026-11-26 18:22:52 +00:00
20db09bd2a Share runtime glossaries with inspection commands 2026-11-26 18:20:54 +00:00
39087675e1 Accept and protect processing glossary files 2026-11-26 18:18:34 +00:00
a4b8fd0976 Compose runtime glossary files with native configuration 2026-11-26 18:17:16 +00:00
b1cde637a2 Retain selected glossary instructions 2026-11-26 18:14:27 +00:00
d2c4c63580 Plan runtime glossary input implementation 2026-11-26 16:02:21 +00:00
f85a07c14d Plan optional collection instructions for proposals and repair 2026-11-26 15:54:03 +00:00
3a5ea78b80 Record agreed D&D overlay contracts and model profiles 2026-11-26 15:48:34 +00:00
178b0cfa9c Separate D&D recipe ownership from Audita 2026-11-26 15:33:10 +00:00
892cff8088 Plan runtime glossary inputs and overlay recipes 2026-11-26 15:26:19 +00:00
bdeac85e8e Remove completed library upgrade planning documents
All checks were successful
ci/woodpecker/tag/release Pipeline was successful
2026-11-23 17:18:18 +00:00
c554eecaec Keep native execution membership presentation stable 2026-11-23 16:58:46 +00:00
59f353348b Accumulate per-call usage without copying event histories 2026-11-23 16:56:44 +00:00
ac47c239c2 Protect operator schema files from output collisions 2026-11-23 16:56:17 +00:00
fed190cc97 Align prompt documentation with the implemented contracts 2026-11-23 16:54:56 +00:00
d25d7fa7d4 Edit fixture repair budgets structurally 2026-11-23 16:54:56 +00:00
deec32cd4c Record the algorithm audit findings 2026-11-23 16:33:22 +00:00
a020d155f4 Record the schema file output collision gap 2026-11-23 14:30:52 +00:00
ca06f7c4e3 Record the library adoption review findings 2026-11-23 14:24:24 +00:00
338e93a7eb Complete library adoption validation and cleanup 2026-11-23 04:51:51 +00:00
58ff21e4df Prepare attribution and v4.1.0 release notes 2026-11-23 04:48:35 +00:00
752ec676a6 Document the library migration and update examples 2026-11-23 04:47:06 +00:00
fa5d834f13 Verify native usage reporting across the pipeline 2026-11-23 04:42:54 +00:00
c477bcc388 Preserve native diagnostic evidence 2026-11-23 04:39:00 +00:00
c167a5e5ab Retain native prompt execution evidence 2026-11-23 04:33:53 +00:00
6ca5f89356 Use prompt-defined structured output contracts 2026-11-23 04:32:15 +00:00
9977cd9130 Construct prompt engines from shared configuration 2026-11-23 04:23:59 +00:00
1ca5011049 Bootstrap secrets for shared configuration acquisition 2026-11-23 04:20:31 +00:00
f87c45331c Compose application and prompt configuration together 2026-11-23 04:14:15 +00:00
82c52c8e7f Plan the coordinated library adoption sprint 2026-11-23 03:07:00 +00:00
12fd2fba6b Clarify recoverable response decoding failures in the roadmap 2026-11-23 02:51:58 +00:00
f13db066f2 Record maintainer authorization for v4.1.0 adoption release 2026-11-23 02:46:06 +00:00
e144c502f6 Make prompt definitions own output contracts and repair budgets 2026-11-23 02:41:01 +00:00
4dc461f9c9 Finalize library adoption decisions and native repair defaults 2026-11-23 02:35:15 +00:00
60a80381a9 Record simplified runtime failure classification 2026-11-23 02:32:58 +00:00
231b4c8a14 Record native execution evidence decision 2026-11-23 02:30:54 +00:00
e0471af25a Refine library upgrade guidance and record open decisions 2026-11-23 02:24:51 +00:00
187600eed2 Adopt the upstream dependency documentation policy 2026-11-23 02:05:13 +00:00
11f45c8812 Plan to replace duplicated library documentation with upstream links 2026-11-23 01:03:42 +00:00
a301ad1f27 Include ConfigKit secrets bootstrap in the upgrade roadmap 2026-11-23 00:59:18 +00:00
92162ba9a6 Document the coordinated library upgrade recommendations 2026-11-23 00:51:16 +00:00
132 changed files with 4519 additions and 1655 deletions

1
.gitignore vendored
View File

@@ -47,6 +47,7 @@ pipeline.yml
bin/ bin/
# Local run artifacts # Local run artifacts
.releasekit/
.audita-runs/ .audita-runs/
report.json report.json
corrected.json corrected.json

View File

@@ -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)
} }

View File

@@ -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)
} }
} }
@@ -1213,8 +1278,10 @@ func TestSubprocessInfeasibleSectionTargetIsAnInputFailure(t *testing.T) {
if _, err := os.Stat(f.output); !os.IsNotExist(err) { if _, err := os.Stat(f.output); !os.IsNotExist(err) {
t.Fatalf("unexpected transcript output: %v", err) t.Fatalf("unexpected transcript output: %v", err)
} }
if document := f.errors(t); document.Status != reporting.StatusFailed { for _, name := range []string{"errors.yml", "recoveries.yml", "report.md"} {
t.Fatalf("report status: %+v", document) if _, err := os.Stat(filepath.Join(f.dir, name)); !os.IsNotExist(err) {
t.Fatalf("unexpected report %s: %v", name, err)
}
} }
} }
@@ -1414,7 +1481,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")

View File

@@ -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.
@@ -14,12 +14,21 @@ do not load application or model configuration.
audita process [flags] transcript.json audita process [flags] transcript.json
``` ```
`audita run` is an alias of `audita process` and uses the same arguments,
flags, and outcomes.
`--config` selects a main configuration and `--overlay` selects its overlay. `--config` selects a main configuration and `--overlay` selects its overlay.
`--output` writes the transcript to a file; omission selects stdout. The shared `--output` writes the transcript to a file; omission selects stdout. The shared
`--debug` flag enables retained debug artifacts, and `--quiet` suppresses optional `--debug` flag enables retained debug artifacts, and `--quiet` suppresses optional
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.
@@ -35,19 +44,60 @@ work directory. `audita process --help` lists the available flags. An omitted fl
does not contribute an override. [Configuration](config.md) defines their values does not contribute an override. [Configuration](config.md) defines their values
and inheritance. and inheritance.
`--glossary-file PATH` supplies a wrapperless runtime glossary file. Repeat it
to compose files in argument order. Each occurrence is a single path resolved
from the invocation working directory. This flag does not select collections:
use configured selections or `--glossaries`. It is also accepted by configuration
inspection and configuration-consuming PromptKit resource, request, and smoke
commands. Configuration comparison applies the same ordered files to both sides.
See the [input format](integrations/transcript-glossary-files.md) and native
command help for the available operations.
## Preflight
```sh
audita preflight --config config.yml --output corrected.json transcript.json
audita preflight --smoke=false --config config.yml --output corrected.json transcript.json
```
`preflight` accepts the same transcript argument and intended processing flags,
including overlays, runtime glossary files, output/report destinations, and debug
settings. It checks local preparation and destination readiness without producing
the corrected transcript, ordinary reports, or debug artifacts. The default
`--smoke=true` also checks structured output for each distinct selected profile;
`--smoke=false` limits the command to local readiness. An empty pipeline selects
no profiles. `process` and `run` do not run these smoke checks. Quiet mode requires
an intended output file or `/dev/null` and suppresses optional summaries.
Provider checks can contact services. Success requires a completed supported
check with positive generation, JSON, and schema observations; it does not prove
compatibility with every prompt or provider-side schema enforcement. Per-profile
smoke usage appears on diagnostics even in ordinary mode, subject to quiet mode,
and preserves native unknown and incomplete values. Any `--show-tokens` execution
summary excludes these smoke calls; the preflight report states that distinction.
See the
[PromptKit diagnostic guide](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md)
and [operations](operations.md#preflight) for scope and side effects.
## Inspection and outcomes ## Inspection and outcomes
The application configuration scope uses ConfigKit's native effective values, The application configuration scope uses ConfigKit's native effective values,
source evidence, explanation, comparison, and redaction. PromptKit supplies its source evidence, explanation, comparison, and redaction. PromptKit supplies its
own configuration and resource scopes and request preparation, validation, and 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 and standalone preflight separately
profiles and glossary entries. Smoke tests can contact providers and are run check selected profiles and glossary entries. Native PromptKit smoke commands
only on explicit request. can produce machine-readable results; standalone preflight presents human-readable
readiness diagnostics. 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
processing profile or required glossary selection is an input failure. See the classifies native configuration diagnostics; unclassified runtime preparation
and bootstrap failures, and cancellation, are operational. A missing
processing profile, required glossary selection, or infeasible requested section
count is an input failure. A failed, unsupported, or inconclusive preflight
provider check is an operational 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).

View File

@@ -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,22 +19,61 @@ 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.
Runtime files supplied with `--glossary-file` are first composed separately in
argument order using native imports and entry identities. Imports are resolved
beside their declaring files. The resolved wrapperless mapping is then assigned
to `glossary_collections` as one CLI override in the application load. Supplied
entry lists replace configured lists at that boundary; unrelated configured
collections remain. Omitted fields retain configured values, while explicit
empty and null values follow native assignment and decoding. Application and
overlay parsing and validation still apply. Final explanation records the CLI
assignment, while original runtime file and import source records belong to the
preliminary load rather than final provenance. See the [runtime file contract](integrations/transcript-glossary-files.md).
Runtime glossary inheritance resolves only among the supplied files and their
imports; it cannot name a parent defined only in application configuration.
Application structural inheritance resolves before CLI assignment and does not
rerun afterward. Replacing a configured parent through runtime inputs therefore
does not update fields already inherited by a configured child. Audita's ordinary
root/stage setting resolution still runs after assignment on the final values.
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.
## Pipeline and glossary selections ## Pipeline and glossary selections
`glossary_collections` maps names to collections with an ordered `entries` list. `glossary_collections` maps names to collections with an ordered `entries` list
and optional `instruction` string. Instructions from the effective selected
glossaries, in selection order, guide proposal generation and remain in the
proposal conversation during repair. Protection-only collections do not add
guidance, and instructions do not add deterministic validation rules.
Each entry has an `id`, `name`, and `category`; `description`, `aliases`, and Each entry has an `id`, `name`, and `category`; `description`, `aliases`, and
`plural` provide optional context. Entries are identified within their collection `plural` provide optional context. Entries are identified within their collection
by `id`. Root `glossaries` and `protected_terms` select collection names. If root by `id`. Root `glossaries` and `protected_terms` select collection names. If root
@@ -74,7 +114,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. |

View File

@@ -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).

View File

@@ -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.

View File

@@ -15,8 +15,17 @@ 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).
For prepared vocabulary, write one or more wrapperless collection files and
pass each path as a separate `--glossary-file` argument. Select the main
configuration and overlay that define the desired pipeline and collection
selections; supplying files does not select them. The same arguments can be
used to inspect the effective configuration before processing. See the
[input format](transcript-glossary-files.md#glossary-collections) and
[CLI reference](../cli.md#processing) for composition and error outcomes.
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.
@@ -34,14 +43,30 @@ operations and completions. Debug enables progress by default, and
`--progress=false` or quiet mode suppresses it. Consume progress as `--progress=false` or quiet mode suppresses it. Consume progress as
human-readable telemetry. Stdout remains the transcript stream. human-readable telemetry. Stdout remains the transcript stream.
## Readiness before processing
A parent can invoke `audita preflight` with the same explicit configuration,
transcript, glossary selections, and intended output arguments it will later pass
to `process`. Use `--smoke=false` for local-only readiness; the default also
contacts selected providers. Interpret exit 0 as success for the checked scope,
2 as invalid usage or input, and 1 as an operational, output, cancellation, or
provider-verification failure. Diagnostics are human-readable, not a stable
machine report. See [preflight](../cli.md#preflight) and
[operations](../operations.md#preflight) for details and side effects.
The subsequent invocation reacquires its inputs and resources. Files, credentials,
service availability, and write readiness can change between the two commands;
preflight does not reserve the destination or guarantee that processing succeeds.
## Result Handling ## Result Handling
Interpret the exit result according to the Interpret the exit result according to the
[CLI output and exit contract](../cli.md#inspection-and-outcomes). [CLI output and exit contract](../cli.md#inspection-and-outcomes).
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, parses and normalizes the transcript, and plans
initialization. Early destination failures can also leave no reports. After chunks before report 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

View File

@@ -36,3 +36,23 @@ The [local example](../../examples/local/glossary.yml) provides a complete
collection. Configuration may contain empty collections; processing preflight collection. Configuration may contain empty collections; processing preflight
requires every glossary-correction entry to select at least one glossary entry. requires every glossary-correction entry to select at least one glossary entry.
The previous standalone `glossary` file format is not a processing input. The previous standalone `glossary` file format is not a processing input.
Runtime files supplied with `--glossary-file` are YAML mappings keyed directly
by collection name, without a `glossary_collections` wrapper. Each collection
may contain `instruction` and `entries`; entries retain additional fields as
extensions. For example:
```yaml
people:
instruction: Prefer the speaker's stated name when supported by context.
entries:
- id: speaker
name: Mira Chen
category: person
aliases: [Mira]
source_note: Prepared for this recording
```
See the [complete runtime glossary example](../../examples/README.md#runtime-glossary-input)
and [composition and selection rules](../config.md#loading-and-composition).
Files and their imports are protected by the existing output collision checks.

View File

@@ -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
@@ -32,12 +33,20 @@ the [CLI contract](../cli.md) when changing the command; the
adoption decision is recorded in [ADR 0001](../adr/0001-releasekit.md). adoption decision is recorded in [ADR 0001](../adr/0001-releasekit.md).
Processing preflight checks glossary selections before inspecting proposal, Processing preflight checks glossary selections before inspecting proposal,
validation, and enabled repair profiles in pipeline order. The checked plan validation, and enabled repair profiles in pipeline order. The local plan
carries the resolved module specs and glossary views into execution. It reuses carries resolved module specs, glossary views, normalized content, and fixed
sections into execution; the prepared invocation also retains checked output
destinations and source evidence. The standalone route uses the same bindings
and local preparation, while `run` is a native alias of `process`. It reuses
profile and backend inspections and equivalent glossary views within the profile and backend inspections and equivalent glossary views within the
invocation. Native inspection commands continue to inspect configuration invocation. Native inspection commands continue to inspect configuration
without running processing readiness checks. without running processing readiness checks.
Runtime glossary files use a preliminary ConfigKit load before the shared
application load. Processing retains its acquired source paths for output
collision checks; inspection receives the final native result and CLI origin.
Both sides of a native comparison use the same invocation file list.
## Validating Examples ## Validating Examples
Keep complete copyable files in [examples](../../examples/) and link to them from Keep complete copyable files in [examples](../../examples/) and link to them from

View File

@@ -20,15 +20,17 @@ validator entries yield `validation_decisions_filtered` only for a successful
operation; they do not count as filtered correction proposals. Failed operations operation; they do not count as filtered correction proposals. Failed operations
retain their execution counts and never produce a recovery record. retain their execution counts and never produce a recovery record.
`internal/core/diagnostics.OutputSession` owns destination selection, report `internal/core/diagnostics` checks destinations without opening resources and
initialization, and publication. Transcript and report files share a staging can probe regular-file targets with temporary siblings. `OutputSession` consumes
the checked paths and owns report initialization and publication. Transcript and report files share a staging
primitive that writes beside the resolved destination. Streams are opened for primitive that writes beside the resolved destination. Streams are opened for
delivery. Transcript input is protected from early report writes but delivery. Transcript input is protected from early report writes but
may be the final transcript destination. The LLM runtime records consumed PromptKit sources and effective host message may be the final transcript destination. The LLM runtime records consumed PromptKit sources and effective host message
files and supplies those source paths to CLI; files and supplies those source paths to CLI;
no second filename-based discovery rule is used. no second filename-based discovery rule is used.
CLI composes it after configuration, transcript acquisition, and preflight CLI constructs it after local plan and destination checks and before dispatching
readiness and before dispatching model work. It does not create ordinary report parents. model work. Standalone preflight uses the checker and probes without a session;
its provider observations remain in the LLM adapter. It does not create ordinary report parents.
Final report rendering includes delivery and cleanup errors observed so far. Final report rendering includes delivery and cleanup errors observed so far.
When another failure becomes known, later writes use updated failed reports. When another failure becomes known, later writes use updated failed reports.
One best-effort pass refreshes earlier reports with stale evidence. A published One best-effort pass refreshes earlier reports with stale evidence. A published
@@ -60,9 +62,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

View File

@@ -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

View File

@@ -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

View File

@@ -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`
@@ -58,16 +59,17 @@ These are current implementation boundaries, not bans on future work.
## Main Execution Path (`audita process`) ## Main Execution Path (`audita process`)
The CLI inspects configuration and profiles, preflights and initializes active The CLI prepares an invocation-local plan and checked destinations, initializes
outputs, optionally creates debug evidence, invokes the runner, and finalizes active outputs, optionally creates debug evidence, invokes the runner, and
transcript and reports. finalizes transcript and reports. Standalone preflight shares local preparation
and can perform provider diagnostics without creating a processing session.
The [pipeline](pipeline.md) owns detailed state transitions; the The [pipeline](pipeline.md) owns detailed state transitions; the
[operations guide](../operations.md) owns the operator workflow and physical [operations guide](../operations.md) owns the operator workflow and physical
artifact lifecycle. 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.

View File

@@ -4,14 +4,14 @@ The [input contract](../integrations/transcript-glossary-files.md) owns input
formats; [configuration](../config.md) owns settings; the formats; [configuration](../config.md) owns settings; the
[output contract](../integrations/output-files.md) owns serialized results. [output contract](../integrations/output-files.md) owns serialized results.
1. CLI loads resolved configuration and transcript input. Preflight checks all 1. CLI acquires configuration and transcript input. `framework/preflight` checks
selected glossary views and roles before the output session prepares resources. selected glossary views and roles, normalizes the canonical transcript, and
Transcript segments then enter canonical normalization. returns an invocation-local plan with fixed sections and ordered profile IDs.
2. Normalization sorts segments by start time and preserves input order for 2. Normalization sorts segments by start time and preserves input order for
ties. It evaluates merge limits using the later end time and the same token ties. It evaluates merge limits using the later end time and the same token
estimate as chunking, then reassigns IDs where needed. estimate as chunking, then reassigns IDs where needed.
3. The runner partitions the normalized transcript exactly once before its 3. The core chunker partitions the normalized transcript during preparation.
module loop. Initial section identity, segment membership, and token The runner consumes those sections: initial identity, membership, and token
estimates stay fixed while text evolves. estimates stay fixed while text evolves.
4. Module instances execute in configured order. Each section hands its decoded 4. Module instances execute in configured order. Each section hands its decoded
proposals and original local segment references to the runner along with proposals and original local segment references to the runner along with
@@ -64,3 +64,9 @@ for invariants.
Key tests: `internal/framework/runner/*_test.go`, Key tests: `internal/framework/runner/*_test.go`,
`internal/framework/validators/*_test.go`, and `internal/framework/validators/*_test.go`, and
`cmd/audita/main_integration_test.go`. `cmd/audita/main_integration_test.go`.
Standalone preflight uses the same local plan and checked destinations, probes
regular output parents, and optionally invokes native structured-output smoke
checks through `framework/llm`. It does not start the runner or an output
session. Processing does not invoke smoke checks. See the
[CLI contract](../cli.md#preflight) for the observable behavior.

View File

@@ -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
@@ -34,7 +34,11 @@ these roles, including the transition from a correction set to one repair result
For a standard request preview or validation, select a native PromptKit profile For a standard request preview or validation, select a native PromptKit profile
and supply the template variables used by the selected prompt. The shipped and supply the template variables used by the selected prompt. The shipped
proposal definitions use `TranscriptDescriptionBlock`, `GlossaryJSON`, proposal definitions use `TranscriptDescriptionBlock`, `GlossaryJSON`,
`ProtectedTermsJSON`, and `SectionJSON`. Glossary entries provide context, `ProtectedTermsJSON`, `GlossaryInstructionsBlock`, and `SectionJSON`. Selected
collection instructions are labeled and ordered in the guidance block; empty
instructions are omitted. The block defaults to empty in previews when omitted,
and caller-provided values are retained. The original proposal conversation
retains that guidance during correction repair. Glossary entries provide context,
and the separate spelling list defines protection. Preview defaults the and the separate spelling list defines protection. Preview defaults the
spelling list to `[]` when omitted. The validator definitions use `TranscriptDescriptionBlock` and spelling list to `[]` when omitted. The validator definitions use `TranscriptDescriptionBlock` and
`PayloadJSON`. The latter is supplied candidate JSON and does not require a `PayloadJSON`. The latter is supplied candidate JSON and does not require a
@@ -46,7 +50,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 +62,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.

View File

@@ -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
View 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.

View File

@@ -17,6 +17,24 @@ history to the selected repair provider. A provider rejection ends that branch
as unavailable; other approved edits can still be applied. See as unavailable; other approved edits can still be applied. See
[configuration](config.md#settings) for the attempt budget and profile selection. [configuration](config.md#settings) for the attempt budget and profile selection.
## Preflight
Standalone preflight shares processing's configuration acquisition, profile and
glossary checks, normalization, chunk planning, and destination checks. It
creates, closes, and removes a temporary file beside each active regular-file
output or report destination; it does not write the final destinations. Disabled
reports, stdout, pipes, and devices are not probed. Parents must already exist.
A successful probe describes current readiness and cannot guarantee a later write.
No ordinary report or debug run directory is created by preflight.
Configuration acquisition can run secrets bootstrap. Default provider checks
send PromptKit's diagnostic request to each selected profile and can consume
service usage; they do not send the transcript. Local-only mode skips those
provider checks. Native smoke usage is reported per profile independently of the
ordinary execution-observer summary. See the [CLI reference](cli.md#preflight)
for invocation and [PromptKit diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md)
for native diagnostic behavior.
## Configuration trust ## Configuration trust
Treat the selected main file, imports, overlay, and automatically loaded Treat the selected main file, imports, overlay, and automatically loaded
@@ -27,6 +45,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 +61,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
@@ -51,6 +74,8 @@ choose separate report directories when retaining reports from multiple runs.
The caller owns these directories and their retention. Later runs can replace The caller owns these directories and their retention. Later runs can replace
ordinary report files at the same destination. ordinary report files at the same destination.
Local readiness, normalization, and chunk planning finish before a processing
reporting session begins. Failures at that boundary need not leave reports.
Enabled reports are initialized as `in_progress` before processing. The Enabled reports are initialized as `in_progress` before processing. The
transcript is published before final reports; the files do not form a single transcript is published before final reports; the files do not form a single
transaction. A late report failure may therefore leave a published transcript. transaction. A late report failure may therefore leave a published transcript.
@@ -68,6 +93,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

View File

@@ -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

View File

@@ -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

View File

@@ -12,6 +12,13 @@ remote is `origin`, which must point to `ssh://git@forge.maximumdirect.net:22222
primary branch is `main`. Source publication needs no delivery credential. primary branch is `main`. Source publication needs no delivery credential.
Woodpecker uses the existing `GITEA_RELEASE_TOKEN` secret for delivery. Woodpecker uses the existing `GITEA_RELEASE_TOKEN` secret for delivery.
For local delivery, `releasekit.json` selects `.releasekit/gitea-token` as the
fallback when `RELEASEKIT_GITEA_TOKEN` is unset or blank. Keep the token file
owner-readable only. The `.releasekit/` directory is git-ignored, and the
candidate's forbidden-file check rejects a committed token file. Native token
selection is described in the pinned
[ReleaseKit configuration reference](https://forge.maximumdirect.net/base-layer/releasekit/src/tag/v0.10.0/docs/config.md).
The source-build minimum is Go 1.27.0, declared in [go.mod](../go.mod). The source-build minimum is Go 1.27.0, declared in [go.mod](../go.mod).
This minimum is required by the selected application dependencies. This minimum is required by the selected application dependencies.
Distributed executables do not require a Go installation. The selected release Distributed executables do not require a Go installation. The selected release

View File

@@ -1,5 +1,7 @@
# Release Notes # Release Notes
- [Audita v4.2.0](v4.2.0.md)
- [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
View 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)

66
docs/releases/v4.2.0.md Normal file
View File

@@ -0,0 +1,66 @@
# Audita v4.2.0
Audita v4.2.0 adds runtime glossary inputs and a standalone readiness command.
Applications can supply session-specific vocabulary and check a planned
processing invocation before running the correction pipeline.
## Runtime glossary inputs
Use repeatable `--glossary-file PATH` arguments to compose native glossary
collection files in argument order. Runtime files supplement the selected
configuration; collection selection still comes from configuration or explicit
CLI overrides. The same inputs are available to configuration inspection and
configuration-consuming PromptKit commands.
Glossary collections can now include optional `instruction` guidance. Selected
context collections contribute that guidance to all four bundled proposal
prompts, and correction repair retains it in the original conversation.
Protection-only selections do not contribute guidance. Runtime glossary sources
participate in output collision checks.
See the [input contract](../integrations/transcript-glossary-files.md#glossary-collections)
and [configuration guide](../config.md#loading-and-composition) for composition,
replacement, and inheritance behavior.
## Standalone preflight
```sh
audita preflight --config config.yml --output corrected.json transcript.json
```
`preflight` accepts the processing arguments and checks configuration, glossary
and profile selections, normalization, chunk feasibility, and intended output
destinations. It uses temporary sibling files to probe regular-file write
readiness while leaving final transcript/report files untouched and retaining
no processing debug artifacts.
By default, it also runs native PromptKit structured-output smoke checks for
each distinct selected profile. These checks can contact providers and consume
usage. Use `--smoke=false` for local checks only. Configured secrets bootstrap
still applies. Diagnostics identify profile progress and actionable failures,
and present native smoke usage separately from execution-observer totals.
`audita run` is now an alias of `audita process`. Both consume the shared
prepared plan and execute the existing correction pipeline without automatic
smoke checks. See the [CLI reference](../cli.md#preflight),
[operations guide](../operations.md#preflight), and
[subprocess contract](../integrations/subprocess.md#readiness-before-processing).
## Compatibility and upgrade
No configuration migration is required from v4.1.0. The application configuration
remains version 3, existing processing invocations remain supported, and ordinary
transcript and report schemas are unchanged. Normalization and chunk planning
now finish before output/report initialization, so failures during those early
steps need not leave reports.
Standalone preflight uses the existing exit categories: `0` for success, `2`
for invalid usage/input, and `1` for operational failures, including unsuccessful
or inconclusive provider verification. Its diagnostics are human-readable;
a successful check does not reserve resources or guarantee a later run succeeds.
Source builds still require Go 1.27.0 or newer. The Go module path remains
`gitea.maximumdirect.net/eric/audita/v4`, and dependency versions are unchanged
from v4.1.0.
[COPYRIGHT](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.2.0/COPYRIGHT) | [LICENSE](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.2.0/LICENSE) | [ATTRIBUTION](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.2.0/docs/oss/attribution.md)

View File

@@ -1,6 +1,6 @@
# Deferred Feature Work # Deferred Feature Work
**Last updated:** 2026-11-15 **Last updated:** 2026-11-26
**Status:** Deferred or exploratory work; not implemented or scheduled. These **Status:** Deferred or exploratory work; not implemented or scheduled. These
entries preserve work beyond completed feature and library upgrades. entries preserve work beyond completed feature and library upgrades.
@@ -96,3 +96,20 @@ Broader validator context and combined semantic validation remain exploratory.
A proposal to expand context should identify a captured case and the evidence A proposal to expand context should identify a captured case and the evidence
missing from the validator request. missing from the validator request.
See the [current validator context](../internal/validators.md#supplemental-validation-context). See the [current validator context](../internal/validators.md#supplemental-validation-context).
## Narratio Runtime Glossary Adoption
Audita's runtime glossary feature and the production/testing overlays in the
separate `audita-pipelines-dnd` repository are implemented. Recipe roles, stage
selections, profile aliases, installation and examples now belong to that
repository's [README](https://forge.maximumdirect.net/eric/audita-pipelines-dnd/src/branch/main/README.md).
Audita's interface belongs in the [CLI](../cli.md), [configuration](../config.md),
and [input contracts](../integrations/transcript-glossary-files.md).
Narratio's adapter migration remains separate work: supply native runtime
glossary files, select the operator's configuration/overlay, and review remaining
CLI/output assumptions, including legacy `--modules`. Narratio owns projecting
campaign/session content such as party rosters into native collections. It can
pin a recipe revision without encoding the processing sequence. This work does
not restore legacy Audita flags or formats. Publishing recipes and selecting
an Audita release remain separate from their implementation.

View File

@@ -12,9 +12,13 @@ local service and its model. Then run:
```sh ```sh
audita config validate --config config.yml audita config validate --config config.yml
audita preflight --smoke=false --config config.yml --output corrected.json transcript.json
audita process --config config.yml --output corrected.json transcript.json audita process --config config.yml --output corrected.json transcript.json
``` ```
The local-only preflight checks the intended destination without contacting the
model. Omit `--smoke=false` to run the default live structured-output checks;
see [PromptKit diagnostics](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/consumers/pkg-promptkit.md).
Processing makes model requests. Reports are written beside the selected output Processing makes model requests. Reports are written beside the selected output
unless disabled. For an offline validator preview, from the same directory: unless disabled. For an offline validator preview, from the same directory:
@@ -49,6 +53,27 @@ audita promptkit show profile service-test --config config.yml
The example does not promise a provider's model availability, price, or quality. The example does not promise a provider's model availability, price, or quality.
## Runtime glossary input
From `examples/service`, the `runtime-glossary` overlay selects a configured
reference collection and an incoming collection. The runtime file replaces the
incoming entries and supplies its instruction. Inspect the combined settings:
```sh
audita config show --scope app --config config.yml --overlay runtime-glossary \
--glossary-file runtime-glossary.yml
```
After configuring the example service and credential, run:
```sh
audita process --config config.yml --overlay runtime-glossary \
--glossary-file runtime-glossary.yml --output corrected.json transcript.json
```
The [runtime file](service/runtime-glossary.yml) and
[overlay](service/overlays/runtime-glossary.yml) contain synthetic data.
## Edit a prompt and run again ## Edit a prompt and run again
From `examples/prompt-edit`, inspect the operator replacement: From `examples/prompt-edit`, inspect the operator replacement:
@@ -59,7 +84,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

View File

@@ -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

View File

@@ -0,0 +1,12 @@
glossaries: [reference, incoming]
glossary_collections:
reference:
instruction: Preserve established place names.
entries:
- {id: observatory, name: North Observatory, category: place}
incoming:
entries:
- {id: speaker, name: Placeholder Speaker, category: person}
llm:
proposal_profile: service-test
validation_profile: service-test

View File

@@ -0,0 +1,8 @@
incoming:
instruction: Use the speaker's preferred spelling when supported by context.
entries:
- id: speaker
name: Mira Chen
category: person
aliases: [Mira]
source_note: Prepared for this recording

10
go.mod
View File

@@ -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
View File

@@ -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=

View File

@@ -0,0 +1,170 @@
// Package appconfig composes Audita and PromptKit configuration sources.
package appconfig
import (
"context"
"errors"
"fmt"
"path/filepath"
"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"`
}
type Options struct {
Overlay string
Overrides []ck.Override
GlossaryFiles []string
}
type Acquisition struct {
*ck.Result[Config]
GlossarySources []string
}
// GlossaryInputError identifies failures in the separate runtime input load.
type GlossaryInputError struct{ Err error }
func (e *GlossaryInputError) Error() string { return e.Err.Error() }
func (e *GlossaryInputError) Unwrap() error { return e.Err }
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, options Options) (*Acquisition, *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
var glossarySources []string
overrides := append([]ck.Override(nil), options.Overrides...)
if len(options.GlossaryFiles) > 0 {
inputs := make([]ck.Input, len(options.GlossaryFiles))
for i, path := range options.GlossaryFiles {
absolute, err := filepath.Abs(path)
if err != nil {
return nil, report, &GlossaryInputError{Err: err}
}
inputs[i] = ck.Input{Source: ck.File(absolute), Imports: true}
}
underlays := make([]ck.Underlay, 0, len(inputs)-1)
for _, item := range inputs[:len(inputs)-1] {
underlays = append(underlays, ck.Underlay{Inputs: []ck.Input{item}})
}
glossaries, err := ck.LoadLayered(inputs[len(inputs)-1], ck.LayeredOptions[map[string]any]{
Definition: ck.Definition[map[string]any]{SequenceIdentities: []ck.SequenceIdentity{config.GlossaryEntryIdentity(nil)}},
Underlays: underlays,
})
if canceled := ctx.Err(); canceled != nil {
return nil, report, errors.Join(err, canceled)
}
if err != nil {
return nil, report, &GlossaryInputError{Err: err}
}
for _, source := range glossaries.Sources() {
if source.Kind == ck.SourceKindFile {
glossarySources = append(glossarySources, source.Path)
}
}
overrides = append(overrides, ck.Override{Path: ck.Keys("glossary_collections"), Value: glossaries.Config, Flag: "--glossary-file"})
}
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: options.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)
}
if err != nil {
return nil, report, err
}
return &Acquisition{Result: result, GlossarySources: glossarySources}, report, nil
}

View 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"))}, Options{Overlay: "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()}, Options{})
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)
}
}
}

View File

@@ -1,6 +1,7 @@
package config package appconfig
import ( import (
"context"
"os" "os"
"path/filepath" "path/filepath"
"slices" "slices"
@@ -37,6 +38,7 @@ glossary_collections:
- path: shared/extra.yml - path: shared/extra.yml
required: true required: true
party: party:
instruction: Use established names.
entries: entries:
- id: hero - id: hero
name: Original name: Original
@@ -48,25 +50,28 @@ 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"))}, Options{})
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 got := result.Config.Application.GlossaryCollections["party"].Instruction; got != "Use established names." {
t.Fatalf("instruction not inherited: %q", got)
}
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))}, Options{})
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 +102,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)}, Options{}); err != nil {
t.Fatalf("valid %q: %v", data, err) t.Fatalf("valid %q: %v", data, err)
} }
} }
@@ -108,7 +113,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)}, Options{}); err == nil {
t.Fatalf("accepted %q", data) t.Fatalf("accepted %q", data)
} }
} }
@@ -118,7 +123,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)}, Options{}); err == nil {
t.Fatal("peer conflict accepted") t.Fatal("peer conflict accepted")
} }
} }
@@ -129,11 +134,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()}, Options{})
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)
} }
} }

View File

@@ -0,0 +1,136 @@
package appconfig
import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"testing"
ck "go.maximumdirect.net/configkit"
)
func TestRuntimeGlossaryComposition(t *testing.T) {
dir := t.TempDir()
files := map[string]string{
"main.yml": `version: 3
glossary_collections:
party:
instruction: Keep the configured guidance
entries: [{id: configured, name: Configured, category: person}]
reference:
entries: [{id: reference, name: Reference, category: lore}]
`,
"overlays/selected.yml": `glossary_collections:
party:
entries: [{id: overlay, name: Overlay, category: person}]
`,
"first.yml": `config:
imports: [{path: imported.yml, required: true}]
party:
entries:
- {id: shared, name: Old, category: person, aliases: [Former]}
- {id: retained, name: Retained, category: person}
`,
"imported.yml": `other:
entries: [{id: imported, name: Imported, category: lore}]
`,
"last.yml": `party:
entries:
- {id: shared, name: New, category: person, note: kept}
`,
}
for name, contents := range files {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(contents), 0644); err != nil {
t.Fatal(err)
}
}
paths := []string{filepath.Join(dir, "first.yml"), filepath.Join(dir, "last.yml")}
acquired, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, Options{Overlay: "selected", GlossaryFiles: paths})
if err != nil {
t.Fatal(err)
}
collections := acquired.Config.Application.GlossaryCollections
party := collections["party"]
if party.Instruction != "Keep the configured guidance" || len(party.Entries) != 2 {
t.Fatalf("party = %+v", party)
}
if party.Entries[0].ID != "shared" || party.Entries[0].Name != "New" || len(party.Entries[0].Aliases) != 0 || party.Entries[0].Extra["note"] != "kept" || party.Entries[1].ID != "retained" {
t.Fatalf("entries = %+v", party.Entries)
}
if len(collections["reference"].Entries) != 1 || len(collections["other"].Entries) != 1 {
t.Fatalf("collections = %+v", collections)
}
for _, name := range []string{"first.yml", "last.yml", "imported.yml"} {
path := filepath.Join(dir, name)
if !slices.Contains(acquired.GlossarySources, path) {
t.Errorf("missing source %s: %v", path, acquired.GlossarySources)
}
for _, source := range acquired.Sources() {
if source.Path == path {
t.Errorf("preliminary source leaked into final result: %s", path)
}
}
}
info, ok := acquired.Metadata().Lookup(ck.Keys("glossary_collections", "party", "entries"))
if !ok || info.Origin.Layer != ck.LayerCLI {
t.Fatalf("origin = %+v", info)
}
}
func TestRuntimeGlossaryLoadErrors(t *testing.T) {
dir := t.TempDir()
main := filepath.Join(dir, "main.yml")
if err := os.WriteFile(main, []byte("version: 3\n"), 0644); err != nil {
t.Fatal(err)
}
malformed := filepath.Join(dir, "bad.yml")
if err := os.WriteFile(malformed, []byte("party: [\n"), 0644); err != nil {
t.Fatal(err)
}
for _, path := range []string{malformed, filepath.Join(dir, "missing.yml")} {
_, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{GlossaryFiles: []string{path}})
var inputErr *GlossaryInputError
var loadErr *ck.LoadError
if !errors.As(err, &inputErr) || !errors.As(err, &loadErr) || report == nil {
t.Fatalf("path %s: report=%v error=%v", path, report, err)
}
}
}
func TestRuntimeGlossaryPresence(t *testing.T) {
for _, tc := range []struct {
name, body string
wantInstruction string
wantEntries int
}{
{"omitted", "party: {}\n", "original", 1},
{"empty", "party: {instruction: '', entries: []}\n", "", 0},
{"null entries", "party: {entries: null}\n", "original", 0},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
main := filepath.Join(dir, "main.yml")
incoming := filepath.Join(dir, "input.yml")
if err := os.WriteFile(main, []byte("glossary_collections:\n party:\n instruction: original\n entries: [{id: a, name: A, category: C}]\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(incoming, []byte(tc.body), 0644); err != nil {
t.Fatal(err)
}
got, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{GlossaryFiles: []string{incoming}})
if err != nil {
t.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics())
}
party := got.Config.Application.GlossaryCollections["party"]
if party.Instruction != tc.wantInstruction || len(party.Entries) != tc.wantEntries {
t.Fatalf("party = %+v", party)
}
})
}
}

View 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)}, Options{})
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)}, Options{})
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)}, Options{})
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}}, Options{})
if err != nil {
t.Fatal(err)
}
if result.Config.Application.Context.Description != "captured" {
t.Fatalf("loaded description = %q", result.Config.Application.Context.Description)
}
}

View File

@@ -0,0 +1,118 @@
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"))}, Options{Overlay: "selected", Overrides: []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"))}, Options{Overlay: "missing"}); err == nil {
t.Fatal("missing overlay accepted")
}
if _, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, Options{Overlay: "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)}, Options{})
if err != nil {
return nil, err
}
return result.Result, nil
}
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}}, Options{Overlay: "local"})
if err != nil {
t.Fatal(err)
}
if result.Config.Application.Context.Description != "project" {
t.Fatalf("description = %q", result.Config.Application.Context.Description)
}
}

View File

@@ -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"
@@ -24,10 +24,15 @@ type invocationState struct {
} }
type engineEntry struct { type engineEntry struct {
selection ckconfig.Selection selection ckconfig.Selection
input acquisitionInput
engine *pk.Engine engine *pk.Engine
} }
func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct{}, _ *invocationState) (*ck.Result[config.Config], error) { type acquisitionInput struct {
GlossaryFiles []string
}
func acquireApplication(ctx context.Context, selection ckconfig.Selection, input acquisitionInput) (*appconfig.Acquisition, error) {
if err := ctx.Err(); err != nil { if err := ctx.Err(); err != nil {
return nil, err return nil, err
} }
@@ -40,10 +45,19 @@ 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}, appconfig.Options{Overlay: selection.Overlay.Value, Overrides: selection.Overrides, GlossaryFiles: input.GlossaryFiles})
return loaded, reportBootstrap(ctx, report, err)
} }
func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) { func loadApplication(ctx context.Context, selection ckconfig.Selection, input acquisitionInput, _ *invocationState) (*ck.Result[appconfig.Config], error) {
loaded, err := acquireApplication(ctx, selection, input)
if err != nil {
return nil, err
}
return loaded.Result, nil
}
func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input acquisitionInput, state *invocationState) (*pk.Engine, error) {
loaded, err := loadApplication(ctx, selection, input, state) loaded, err := loadApplication(ctx, selection, input, state)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -55,10 +69,10 @@ func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input s
return llm.NewEngine(ctx, loaded, client) return llm.NewEngine(ctx, loaded, client)
} }
func capturePromptEngine(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) { func capturePromptEngine(ctx context.Context, selection ckconfig.Selection, input acquisitionInput, state *invocationState) (*pk.Engine, error) {
if state != nil { if state != nil {
for _, entry := range state.engines { for _, entry := range state.engines {
if reflect.DeepEqual(entry.selection, selection) { if reflect.DeepEqual(entry.selection, selection) && reflect.DeepEqual(entry.input, input) {
return entry.engine, nil return entry.engine, nil
} }
} }
@@ -68,30 +82,49 @@ func capturePromptEngine(ctx context.Context, selection ckconfig.Selection, inpu
return nil, err return nil, err
} }
if state != nil { if state != nil {
state.engines = append(state.engines, engineEntry{selection: selection, engine: engine}) state.engines = append(state.engines, engineEntry{selection: selection, input: acquisitionInput{GlossaryFiles: append([]string(nil), input.GlossaryFiles...)}, engine: engine})
} }
return engine, nil return engine, nil
} }
func shareComparisonGlossaries(scope ckconfig.Scope[acquisitionInput, *invocationState]) ckconfig.Scope[acquisitionInput, *invocationState] {
compare := scope.Compare
scope.Compare = func(ctx context.Context, request ckconfig.ComparisonRequest[acquisitionInput], state *invocationState) (commandkit.Acquired[[]ck.Difference], error) {
request.Right.Input.GlossaryFiles = append([]string(nil), request.Left.Input.GlossaryFiles...)
return compare(ctx, request, state)
}
return scope
}
func buildApplication(extra ...commandkit.Declaration) (*commandkit.App, error) { func buildApplication(extra ...commandkit.Declaration) (*commandkit.App, error) {
return buildApplicationWithClient(nil, extra...) return buildApplicationWithClient(nil, extra...)
} }
func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) { func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) {
selector := commandkit.RepeatFlag(commandkit.FlagMeta{Name: "glossary-file", Usage: "Runtime glossary file (repeatable)."}, nil, func(s string) (string, error) { return s, nil }, func(in *acquisitionInput, value commandkit.Supplied[[]string]) { in.GlossaryFiles = value.Value })
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 = shareComparisonGlossaries(withBootstrapContext(appScope))
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}}) promptScope := shareComparisonGlossaries(withBootstrapContext(ckprompt.ConfigScope(loadPromptEngine)))
configCommand := ckconfig.Command(ckconfig.Suite[acquisitionInput, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Selectors: []ckconfig.Selector[acquisitionInput]{{Binding: selector, Scopes: []string{"app", "promptkit"}}}, Scopes: []ckconfig.Scope[acquisitionInput, *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} }
definitions = ckprompt.WithRequestValidation(definitions, capturePromptEngine, func(_ context.Context, seed ckprompt.ValidationRequest, _ struct{}, _ *invocationState) (pk.RunRequest, error) { definitions.Selectors = []commandkit.Flag[acquisitionInput]{selector}
definitions = ckprompt.WithRequestValidation(definitions, capturePromptEngine, func(_ context.Context, seed ckprompt.ValidationRequest, _ acquisitionInput, _ *invocationState) (pk.RunRequest, error) {
return applicationPromptRequest(seed.Request, seed.Namespaces), nil return applicationPromptRequest(seed.Request, seed.Namespaces), nil
}) })
definitions = ckprompt.WithRequestPreparation(definitions, capturePromptEngine, func(_ context.Context, seed ckprompt.PreparationRequest, _ struct{}, _ *invocationState) (pk.RunRequest, error) { definitions = ckprompt.WithRequestPreparation(definitions, capturePromptEngine, func(_ context.Context, seed ckprompt.PreparationRequest, _ acquisitionInput, _ *invocationState) (pk.RunRequest, error) {
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()),
commandkit.WithInvocationFeature(commandkit.WithInvocationFeature(preflightCommand(), bootstrapFeature()), preflightUsageFeature()),
commandkit.Alias("run", "process"),
}
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...)

View File

@@ -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"
) )
@@ -96,15 +98,15 @@ func TestPromptConfigurationComparisonAcquiresEqualSelectionsIndependently(t *te
} }
} }
writeProfile("before") writeProfile("before")
scope := ckprompt.ConfigScope(func(ctx context.Context, selection ckconfig.Selection, input struct{}, state *invocationState) (*pk.Engine, error) { scope := ckprompt.ConfigScope(func(ctx context.Context, selection ckconfig.Selection, input acquisitionInput, state *invocationState) (*pk.Engine, error) {
engine, err := loadPromptEngine(ctx, selection, input, state) engine, err := loadPromptEngine(ctx, selection, input, state)
writeProfile("after") writeProfile("after")
return engine, err return engine, err
}) })
side := ckconfig.ComparisonSide[struct{}]{Selection: ckconfig.Selection{ side := ckconfig.ComparisonSide[acquisitionInput]{Selection: ckconfig.Selection{
Config: commandkit.Supplied[string]{Value: main, Set: true}, Config: commandkit.Supplied[string]{Value: main, Set: true},
}} }}
result, err := scope.Compare(context.Background(), ckconfig.ComparisonRequest[struct{}]{Left: side, Right: side}, &invocationState{}) result, err := scope.Compare(context.Background(), ckconfig.ComparisonRequest[acquisitionInput]{Left: side, Right: side}, &invocationState{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -116,6 +118,32 @@ func TestPromptConfigurationComparisonAcquiresEqualSelectionsIndependently(t *te
t.Fatal("comparison did not capture the model before and after the resource changed") t.Fatal("comparison did not capture the model before and after the resource changed")
} }
func TestPromptEngineCacheIncludesRuntimeGlossaryInput(t *testing.T) {
dir := t.TempDir()
main := filepath.Join(dir, "main.yml")
first := filepath.Join(dir, "first.yml")
second := filepath.Join(dir, "second.yml")
for path, contents := range map[string]string{main: "version: 3\n", first: "one: {entries: []}\n", second: "two: {entries: []}\n"} {
if err := os.WriteFile(path, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
selection := ckconfig.Selection{Config: commandkit.Supplied[string]{Value: main, Set: true}}
state := &invocationState{}
left, err := capturePromptEngine(context.Background(), selection, acquisitionInput{GlossaryFiles: []string{first}}, state)
if err != nil {
t.Fatal(err)
}
right, err := capturePromptEngine(context.Background(), selection, acquisitionInput{GlossaryFiles: []string{second}}, state)
if err != nil || left == right {
t.Fatalf("different inputs reused engine: %v", err)
}
matched, err := capturePromptEngine(context.Background(), selection, acquisitionInput{GlossaryFiles: []string{first}}, state)
if err != nil || matched != left {
t.Fatalf("matching input did not reuse engine: %v", err)
}
}
func TestRequestInspectionAndExplicitSmokeUseSameSources(t *testing.T) { func TestRequestInspectionAndExplicitSmokeUseSameSources(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
file := filepath.Join(dir, "config.yml") file := filepath.Join(dir, "config.yml")
@@ -192,11 +220,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 +262,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
View 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
}

View File

@@ -0,0 +1,136 @@
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)}, appconfig.Options{})
if err != nil {
return nil, reportBootstrap(ctx, report, err)
}
return result.Result, reportBootstrap(ctx, report, nil)
}
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)}, appconfig.Options{})
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)}, appconfig.Options{})
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 }

View File

@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"io" "io"
"net/http" "net/http"
"net/http/httptest"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@@ -14,10 +15,13 @@ 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"
commandkit "go.maximumdirect.net/commandkit"
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 +37,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)}, appconfig.Options{Overlay: 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"`
@@ -62,7 +95,7 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
mu.Unlock() mu.Unlock()
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"corrections\":[]}"}}]}`)), Request: r}, nil return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"corrections\":[]}"}}]}`)), Request: r}, nil
}) })
engine, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) engine, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -74,21 +107,27 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
inputs := &processInputs{Configuration: loaded, Runtime: engine, Source: source} inputs := &processInputs{Configuration: loaded.Result, Runtime: engine, Source: source}
prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(root, tc.dir, "transcript.json")}, inputs, &bytes.Buffer{}) prepared, err := prepareProcess(context.Background(), processInput{Transcript: filepath.Join(root, tc.dir, "transcript.json")}, inputs, &bytes.Buffer{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer prepared.Prepared.Output.Close() defer prepared.Prepared.Output.Close()
if _, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil); err != nil { if _, err := executePipeline(context.Background(), prepared, 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,11 +159,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
engine, err := llm.NewRuntime(context.Background(), loaded, nil) engine, err := llm.NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -148,3 +187,74 @@ func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
t.Fatalf("before=%q after=%q", before, after) t.Fatalf("before=%q after=%q", before, after)
} }
} }
func TestRuntimeGlossaryExampleWorkflow(t *testing.T) {
_, file, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate examples")
}
source := filepath.Join(filepath.Dir(file), "..", "..", "examples", "service")
dir := t.TempDir()
for _, name := range []string{"config.yml", "prompts.yml", "transcript.json", "runtime-glossary.yml", "overlays/runtime-glossary.yml"} {
data, err := os.ReadFile(filepath.Join(source, name))
if err != nil {
t.Fatal(err)
}
dest := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(dest), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(dest, data, 0600); err != nil {
t.Fatal(err)
}
}
t.Setenv("AUDITA_EXAMPLE_KEY", "synthetic")
var seen string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var request struct {
Messages []struct {
Content string `json:"content"`
} `json:"messages"`
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
t.Error(err)
return
}
for _, message := range request.Messages {
seen += message.Content
}
io.WriteString(w, `{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"corrections\":[]}"}}]}`)
}))
defer server.Close()
promptsPath := filepath.Join(dir, "prompts.yml")
promptsData, err := os.ReadFile(promptsPath)
if err != nil {
t.Fatal(err)
}
promptsData = bytes.ReplaceAll(promptsData, []byte("https://example.invalid/v1"), []byte(server.URL+"/v1"))
if err := os.WriteFile(promptsPath, promptsData, 0600); err != nil {
t.Fatal(err)
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
common := []string{"--config", filepath.Join(dir, "config.yml"), "--overlay", "runtime-glossary", "--glossary-file", filepath.Join(dir, "runtime-glossary.yml")}
var out, stderr bytes.Buffer
args := append([]string{"config", "show", "--scope=app"}, common...)
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
if result.Status != 0 || !strings.Contains(out.String(), "Mira Chen") || !strings.Contains(out.String(), "North Observatory") || strings.Contains(out.String(), "Placeholder Speaker") {
t.Fatalf("inspection %d %s %s", result.Status, out.String(), stderr.String())
}
out.Reset()
stderr.Reset()
args = append([]string{"process"}, common...)
args = append(args, "--output", filepath.Join(dir, "output.json"), filepath.Join(dir, "transcript.json"))
result = app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
if result.Status != 0 || !strings.Contains(seen, "Mira Chen") || !strings.Contains(seen, "North Observatory") || !strings.Contains(seen, "speaker's preferred spelling") || !strings.Contains(seen, "Preserve established place names") {
t.Fatalf("processing %d seen=%s stderr=%s", result.Status, seen, stderr.String())
}
if _, err := os.Stat(filepath.Join(dir, "output.json")); err != nil {
t.Fatal(err)
}
}

136
internal/cli/preflight.go Normal file
View File

@@ -0,0 +1,136 @@
package cli
import (
"context"
"fmt"
"io"
"strings"
"text/template"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
commandkit "go.maximumdirect.net/commandkit"
pk "go.maximumdirect.net/promptkit"
)
// preflightUsage carries native observations to CommandKit's diagnostic report.
// Smoke calls are deliberately absent from PromptKit's execution observer.
type preflightUsageKey struct{}
type preflightUsage struct {
Lines []string
Failed bool
}
var preflightUsageTemplate = template.Must(commandkit.ParseTextTemplate("preflight smoke usage", `{{if .Lines}}Preflight smoke usage; execution-observer totals exclude these calls.
{{if .Failed}}See per-profile failure details below.
{{else}}{{range .Lines}}{{.}}
{{end}}{{end}}{{end}}`, nil))
func preflightUsageFeature() commandkit.InvocationFeature {
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{
Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
if inv.CanonicalPath() != "preflight" {
return inv.Context, nil
}
usage := new(preflightUsage)
return context.WithValue(inv.Context, preflightUsageKey{}, usage), func() commandkit.Report {
return commandkit.Report{Value: usage, TextTemplate: preflightUsageTemplate}
}
},
})
}
func runPreflight(inv commandkit.Invocation, input processInput) commandkit.Outcome {
reporter := inv.Reporter()
_ = reporter.Progress("Checking local processing readiness.")
loaded, err := loadProcessInputs(inv.Context, input, inv.ReportingMode())
if err != nil {
return acquisitionOutcome(inv, err)
}
prepared, err := prepareLocal(inv.Context, input, loaded, reporter.Output())
if err != nil {
return preparationOutcome(inv, err)
}
if err := diagnostics.ProbeOutput(inv.Context, prepared.Destinations); err != nil {
return commandkit.Failure(err.Error()).WithCause(err)
}
if !input.Smoke.Value {
_ = reporter.AtEnd().Info("Local preflight checks passed; provider verification was skipped.")
return commandkit.Success()
}
if len(prepared.Plan.Profiles) == 0 {
_ = reporter.AtEnd().Info("Local preflight checks passed; no profiles were selected for provider verification.")
return commandkit.Success()
}
_ = reporter.Progress("Checking structured output for selected profiles.")
results, err := llm.VerifyStructuredOutput(inv.Context, loaded.Runtime.Engine, prepared.Plan.Profiles, func(id string) {
_ = reporter.Progress(fmt.Sprintf("Checking structured output for profile %q.", id))
})
if usage, ok := inv.Context.Value(preflightUsageKey{}).(*preflightUsage); ok {
usage.Failed = err != nil
for _, result := range results {
usage.Lines = append(usage.Lines, verificationLine(result))
}
}
if err != nil {
details := make([]commandkit.Detail, 0, len(results))
for _, result := range results {
line := verificationLine(result)
details = append(details, func(w io.Writer) error { _, err := io.WriteString(w, line+"\n"); return err })
}
return commandkit.Failure("Structured-output verification failed.", details...).WithCause(err)
}
_ = reporter.AtEnd().Info("Local and structured-output preflight checks passed.")
return commandkit.Success()
}
func verificationLine(result llm.ProfileVerification) string {
line := fmt.Sprintf("Profile %q: %s", result.ProfileID, result.Status)
if result.Err != nil {
line += ": " + result.Err.Error()
}
if result.Report == nil {
return line + "; smoke usage: unknown"
}
report := result.Report
if result.Status != llm.VerificationSuccess {
line += fmt.Sprintf(" (completed=%t, generation=%s, JSON=%s, schema=%s", report.Completed, boolObservation(report.Facts.GenerationCompleted), boolObservation(report.Facts.ValidJSON), boolObservation(report.Facts.SchemaMatched))
if report.Failure != pk.ExecutionFailureNone {
line += ", failure=" + string(report.Failure)
}
if report.Reason != pk.SmokeTestReasonNone {
line += ", reason=" + string(report.Reason)
}
line += ")"
}
usage := report.Usage
counts := []struct {
name string
count pk.ObservedTokenCount
}{
{"prompt", usage.PromptTokens}, {"completion", usage.CompletionTokens}, {"reasoning", usage.ReasoningTokens}, {"total", usage.TotalTokens}, {"cached", usage.CachedTokens}, {"cache-write", usage.CacheWriteTokens},
}
parts := make([]string, 0, len(counts))
for _, count := range counts {
value := "unknown"
if count.count.Known {
value = fmt.Sprintf("%d", count.count.Value)
}
if count.count.Complete {
value += " (complete)"
} else {
value += " (incomplete)"
}
parts = append(parts, count.name+"="+value)
}
return line + "; smoke usage: " + strings.Join(parts, ", ")
}
func boolObservation(value *bool) string {
if value == nil {
return "unknown"
}
if *value {
return "true"
}
return "false"
}

View File

@@ -0,0 +1,303 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
commandkit "go.maximumdirect.net/commandkit"
pk "go.maximumdirect.net/promptkit"
)
func TestPreflightBindingsAndRunAlias(t *testing.T) {
dir := t.TempDir()
for name, contents := range map[string]string{
"config.yml": "version: 3\npipeline: {stages: []}\nreporting: {enabled: false}\n",
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"hello"}]`,
"glossary.yml": "party: {entries: [{id: alice, name: Alice, category: person}]}\n",
"overlays/local.yml": "context: {description: Local example}\n",
} {
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
cfg, transcript, output := filepath.Join(dir, "config.yml"), filepath.Join(dir, "transcript.json"), filepath.Join(dir, "out.json")
if err := os.WriteFile(output, []byte("existing"), 0600); err != nil {
t.Fatal(err)
}
common := []string{"--config", cfg, "--overlay", "local", "--glossary-file", filepath.Join(dir, "glossary.yml"), "--glossaries", `["party"]`, "--output", output, transcript}
var out, stderr bytes.Buffer
invoke := func(args ...string) int {
out.Reset()
stderr.Reset()
return app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}).Status
}
args := append([]string{"preflight", "--smoke=false"}, common...)
if status := invoke(args...); status != 0 {
t.Fatalf("preflight %d: %s", status, stderr.String())
}
if data, err := os.ReadFile(output); err != nil || string(data) != "existing" {
t.Fatalf("destination changed: %q %v", data, err)
}
if status := invoke("preflight", "--help"); status != 0 || !strings.Contains(out.String(), "--smoke") {
t.Fatalf("help %d: %s %s", status, out.String(), stderr.String())
}
if status := invoke("preflight", "--quiet", "--config", filepath.Join(dir, "missing"), transcript); status != 2 || !strings.Contains(stderr.String(), "quiet") {
t.Fatalf("quiet %d: %s", status, stderr.String())
}
if status := invoke("preflight", "--quiet", "--smoke=false", "--config", cfg, "--output", os.DevNull, transcript); status != 0 {
t.Fatalf("null %d: %s", status, stderr.String())
}
args = append([]string{"run"}, common...)
if status := invoke(args...); status != 0 {
t.Fatalf("alias %d: %s", status, stderr.String())
}
if data, err := os.ReadFile(output); err != nil || string(data) == "existing" || !strings.Contains(string(data), "hello") {
t.Fatalf("alias output: %q %v", data, err)
}
if status := invoke("process", "--smoke=false", transcript); status != 2 {
t.Fatalf("process accepted smoke flag: %d", status)
}
}
func TestPreflightVerifiesDistinctProfilesAfterLocalChecks(t *testing.T) {
dir := t.TempDir()
var models []string
var negative bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Model string `json:"model"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
return
}
models = append(models, body.Model)
content := `{"status":"ok"}`
if negative && body.Model == "review-model" {
content = `{"bad":true}`
}
_ = json.NewEncoder(w).Encode(map[string]any{"model": body.Model, "choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}}}, "usage": map[string]int{"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}})
}))
defer server.Close()
for name, contents := range map[string]string{
"config.yml": "version: 3\nllm: {proposal_profile: proposal, validation_profile: review, correction_repair_profile: unused, correction_repair_attempts: 0}\npipeline: {stages: [{module: grammar}]}\n",
"prompts.yml": fmt.Sprintf("backends:\n - id: shared\n endpoint: %s/v1\nprofiles:\n - {id: proposal, backend: shared, model: proposal-model}\n - {id: review, backend: shared, model: review-model}\n - {id: unused, backend: shared, model: unused-model}\n", server.URL),
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"private transcript"}]`,
"output.json": "existing output",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
var out, stderr bytes.Buffer
args := []string{"preflight", "--config", filepath.Join(dir, "config.yml"), "--output", filepath.Join(dir, "output.json"), "--work-dir", filepath.Join(dir, "debug"), "--debug", filepath.Join(dir, "transcript.json")}
invoke := func(args []string) int {
out.Reset()
stderr.Reset()
models = nil
return app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr}).Status
}
if status := invoke(args); status != 0 || !slices.Equal(models, []string{"proposal-model", "review-model"}) || !strings.Contains(stderr.String(), "smoke usage") || !strings.Contains(stderr.String(), "total=10") {
t.Fatalf("success %d models=%v stdout=%s stderr=%s", status, models, out.String(), stderr.String())
}
local := append([]string{}, args...)
local = append(local[:1], append([]string{"--smoke=false"}, local[1:]...)...)
if status := invoke(local); status != 0 || len(models) != 0 {
t.Fatalf("local %d models=%v err=%s", status, models, stderr.String())
}
invalid := append([]string{}, args...)
invalid = append(invalid[:1], append([]string{"--target-sections=2"}, invalid[1:]...)...)
if status := invoke(invalid); status != 2 || len(models) != 0 {
t.Fatalf("invalid %d models=%v err=%s", status, models, stderr.String())
}
negative = true
requested := append([]string{"preflight", "--show-tokens"}, args[1:]...)
if status := invoke(requested); status != 1 || !strings.Contains(stderr.String(), "total=10 (complete)") || !strings.Contains(stderr.String(), "execution-observer totals exclude these calls") {
t.Fatalf("failed verification usage: status=%d diagnostic=%s", status, stderr.String())
}
quiet := append([]string{}, args...)
quiet = append(quiet[:1], append([]string{"--quiet"}, quiet[1:]...)...)
if status := invoke(quiet); status != 1 || len(models) != 2 || !strings.Contains(stderr.String(), `Profile "review": negative`) || strings.Contains(stderr.String(), "private transcript") || strings.Contains(stderr.String(), `"bad"`) {
t.Fatalf("negative %d models=%v err=%s", status, models, stderr.String())
}
if data, err := os.ReadFile(filepath.Join(dir, "output.json")); err != nil || string(data) != "existing output" {
t.Fatalf("output changed: %q %v", data, err)
}
for _, name := range []string{"errors.yml", "recoveries.yml", "report.md", "debug"} {
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
t.Fatalf("artifact %s exists: %v", name, err)
}
}
}
func TestPreflightCancellationRetainsPartialProfileDiagnostics(t *testing.T) {
dir := t.TempDir()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if calls == 2 {
cancel()
return
}
_, _ = io.WriteString(w, `{"model":"fixture","choices":[{"message":{"role":"assistant","content":"{\"status\":\"ok\"}"}}],"usage":{"prompt_tokens":7,"completion_tokens":3,"total_tokens":10}}`)
}))
defer server.Close()
for name, contents := range map[string]string{
"config.yml": "version: 3\nllm: {proposal_profile: one, validation_profile: two}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n",
"prompts.yml": fmt.Sprintf("profiles:\n - {id: one, endpoint: %s/v1, model: one}\n - {id: two, endpoint: %s/v1, model: two}\n", server.URL, server.URL),
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"hello"}]`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(contents), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
var out, stderr bytes.Buffer
result := app.Execute(ctx, []string{"preflight", "--quiet", "--config", filepath.Join(dir, "config.yml"), "--output", filepath.Join(dir, "out"), filepath.Join(dir, "transcript.json")}, commandkit.Streams{Out: &out, Err: &stderr})
if result.Status != 1 || calls != 2 || !errors.Is(result.Cause, context.Canceled) || !strings.Contains(stderr.String(), `Profile "one": success`) || !strings.Contains(stderr.String(), `Profile "two": inconclusive`) {
t.Fatalf("status=%d calls=%d cause=%v stderr=%q", result.Status, calls, result.Cause, stderr.String())
}
}
func TestPreflightUsagePreservesUnknownAndCompleteness(t *testing.T) {
report := &pk.SmokeTestReport{Usage: pk.ObservedTokenUsage{
PromptTokens: pk.ObservedTokenCount{Known: true, Complete: false, Value: 4},
CompletionTokens: pk.ObservedTokenCount{Known: true, Complete: true, Value: 0},
TotalTokens: pk.ObservedTokenCount{Known: false, Complete: true},
}}
line := verificationLine(llm.ProfileVerification{ProfileID: "fixture", Status: llm.VerificationSuccess, Report: report})
for _, want := range []string{"prompt=4 (incomplete)", "completion=0 (complete)", "total=unknown (complete)", "reasoning=unknown (incomplete)"} {
if !strings.Contains(line, want) {
t.Fatalf("missing %q in %q", want, line)
}
}
}
func TestPreflightExplainsNativePreparationError(t *testing.T) {
dir := t.TempDir()
for name, body := range map[string]string{
"config.yml": "version: 3\nllm: {proposal_profile: selected}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n",
"prompts.yml": "profiles: [{id: selected, endpoint: 'http://example.invalid/v1'}]\n",
"transcript.json": `[{"speaker":"A","start":0,"end":1,"text":"hello"}]`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
for _, flags := range [][]string{nil, {"--quiet"}, {"--debug"}, {"--progress"}, {"--progress=false"}, {"--quiet", "--progress"}} {
var out, diagnostic bytes.Buffer
args := append([]string{"preflight"}, flags...)
args = append(args, "--config", filepath.Join(dir, "config.yml"), "--output", filepath.Join(dir, "out.json"), filepath.Join(dir, "transcript.json"))
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
wantProgress := slices.Contains(flags, "--debug") || (slices.Contains(flags, "--progress") && !slices.Contains(flags, "--quiet"))
if strings.Contains(diagnostic.String(), `Checking structured output for profile "selected"`) != wantProgress {
t.Fatalf("flags=%v diagnostic=%s", flags, diagnostic.String())
}
if result.Status != 1 || result.Cause == nil || !strings.Contains(diagnostic.String(), `Profile "selected"`) || !strings.Contains(diagnostic.String(), "model is required") {
t.Fatalf("status=%d cause=%v diagnostic=%s", result.Status, result.Cause, diagnostic.String())
}
}
}
func TestPreflightUsageReportScopesNativeObservations(t *testing.T) {
for _, tc := range []struct {
name, command string
flags []string
smoke bool
visible bool
}{
{"ordinary", "preflight", nil, true, true},
{"requested", "preflight", []string{"--show-tokens"}, true, true},
{"verbose", "preflight", []string{"--show-tokens", "--verbose"}, true, true},
{"quiet", "preflight", []string{"--show-tokens", "--quiet"}, true, false},
{"local only", "preflight", []string{"--show-tokens", "--smoke=false"}, false, false},
{"processing", "process", []string{"--show-tokens"}, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
content := `{"status":"ok"}`
if tc.command == "process" {
content = `{"corrections":[]}`
}
_ = json.NewEncoder(w).Encode(map[string]any{"choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": content}}}, "usage": map[string]int{"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}})
}))
defer server.Close()
dir := t.TempDir()
for name, body := range map[string]string{
"config.yml": "version: 3\nllm: {proposal_profile: fixture}\npipeline: {stages: [{module: grammar}]}\nreporting: {enabled: false}\n",
"prompts.yml": fmt.Sprintf("profiles: [{id: fixture, endpoint: '%s/v1', model: fixture}]\n", server.URL),
"transcript.json": `[{"speaker":"A","start":0,"end":1,"text":"hello"}]`,
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
args := append([]string{tc.command}, tc.flags...)
args = append(args, "--config", filepath.Join(dir, "config.yml"), "--output", filepath.Join(dir, "out.json"), filepath.Join(dir, "transcript.json"))
var out, diagnostic bytes.Buffer
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostic})
if result.Status != 0 {
t.Fatalf("status=%d diagnostic=%s", result.Status, diagnostic.String())
}
if strings.Contains(diagnostic.String(), "total=10 (complete)") != tc.visible || strings.Contains(diagnostic.String(), "execution-observer totals exclude these calls") != tc.visible {
t.Fatalf("diagnostic=%s", diagnostic.String())
}
wantCalls := 0
if tc.smoke || tc.command == "process" {
wantCalls = 1
}
if calls != wantCalls {
t.Fatalf("calls=%d want=%d", calls, wantCalls)
}
if tc.command == "process" && (!strings.Contains(diagnostic.String(), "Total tokens: 10") || strings.Contains(diagnostic.String(), "Preflight smoke usage")) {
t.Fatalf("processing diagnostic=%s", diagnostic.String())
}
if slices.Contains(tc.flags, "--quiet") && diagnostic.Len() != 0 {
t.Fatalf("quiet diagnostic=%s", diagnostic.String())
}
if out.Len() != 0 {
t.Fatalf("unexpected stdout: %s", out.String())
}
})
}
}

View File

@@ -5,11 +5,10 @@ import (
"fmt" "fmt"
"sync" "sync"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization" "gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"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"
@@ -26,29 +25,11 @@ type processResult struct {
func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcome { func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcome {
loaded, err := loadProcessInputs(inv.Context, input, inv.ReportingMode()) loaded, err := loadProcessInputs(inv.Context, input, inv.ReportingMode())
if err != nil { if err != nil {
if canceled := inv.Context.Err(); canceled != nil && !errors.Is(err, canceled) { return acquisitionOutcome(inv, err)
err = errors.Join(err, canceled)
}
var loadErr *ck.LoadError
if errors.As(err, &loadErr) {
_, explanation := ckconfig.AdaptDiagnostics("Application configuration:\n", loadErr.Sources(), loadErr.Diagnostics())
if ckconfig.ClassifyConfigurationError(err) == commandkit.OutcomeUsage {
return commandkit.Usage(loadErr.Error(), explanation.Details...).WithCause(err)
}
return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(err)
}
if inv.Context.Err() != nil || llm.IsAssetError(err) {
return commandkit.Failure("Could not prepare processing.").WithCause(err)
}
return commandkit.Usage(err.Error()).WithCause(err)
} }
prepared, err := prepareProcess(inv.Context, input, loaded, inv.Reporter().Output()) prepared, err := prepareProcess(inv.Context, input, loaded, inv.Reporter().Output())
if err != nil { if err != nil {
var selection *preflight.SelectionError return preparationOutcome(inv, err)
if inv.Context.Err() == nil && errors.As(err, &selection) {
return commandkit.Usage(err.Error()).WithCause(err)
}
return commandkit.Failure(err.Error()).WithCause(err)
} }
defer prepared.Prepared.Output.Close() defer prepared.Prepared.Output.Close()
var warningsMu sync.Mutex var warningsMu sync.Mutex
@@ -65,14 +46,9 @@ 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{ normalized, summary := prepared.Invocation.Plan.Transcript, prepared.Invocation.Plan.Summary
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,
})
transcript := loaded.Source.Canonical()
loaded.Source = nil loaded.Source = nil
normalized, summary := normalizer.Normalize(transcript)
if debug != nil { if debug != nil {
warn(debug.WriteNormalizedTranscript(normalized)) warn(debug.WriteNormalizedTranscript(normalized))
warn(debug.WriteNormalizationSummary(summary)) warn(debug.WriteNormalizationSummary(summary))
@@ -81,7 +57,7 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
return finishProcess(inv, input, prepared, reporting.Snapshot{}, nil, &runner.ExecutionFailure{Phase: "normalization", Cause: err}) return finishProcess(inv, input, prepared, reporting.Snapshot{}, nil, &runner.ExecutionFailure{Phase: "normalization", Cause: err})
} }
reporter := inv.Reporter() reporter := inv.Reporter()
result, runErr := executePipeline(inv.Context, loaded, prepared, normalized, warn, func(message string) { result, runErr := executePipeline(inv.Context, prepared, warn, func(message string) {
_ = reporter.Progress(message) _ = reporter.Progress(message)
}) })
if runErr != nil { if runErr != nil {
@@ -108,3 +84,37 @@ func (p *preparedProcess) DebugPath() string {
} }
return p.Prepared.Debug.Path() return p.Prepared.Debug.Path()
} }
func acquisitionOutcome(inv commandkit.Invocation, err error) commandkit.Outcome {
if canceled := inv.Context.Err(); canceled != nil && !errors.Is(err, canceled) {
err = errors.Join(err, canceled)
}
var loadErr *ck.LoadError
if errors.As(err, &loadErr) {
_, explanation := ckconfig.AdaptDiagnostics("Application configuration:\n", loadErr.Sources(), loadErr.Diagnostics())
if inv.Context.Err() == nil && ckconfig.ClassifyConfigurationError(err) == commandkit.OutcomeUsage {
return commandkit.Usage(loadErr.Error(), explanation.Details...).WithCause(err)
}
return commandkit.Failure(loadErr.Error(), explanation.Details...).WithCause(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.Usage(err.Error()).WithCause(err)
}
func preparationOutcome(inv commandkit.Invocation, err error) commandkit.Outcome {
var selection *preflight.SelectionError
if inv.Context.Err() == nil && errors.As(err, &selection) {
return commandkit.Usage(err.Error()).WithCause(err)
}
return commandkit.Failure(err.Error()).WithCause(err)
}

View File

@@ -14,12 +14,15 @@ type processInput struct {
Transcript string Transcript string
Output commandkit.Supplied[string] Output commandkit.Supplied[string]
Debug commandkit.Supplied[bool] Debug commandkit.Supplied[bool]
Smoke commandkit.Supplied[bool]
Overrides []ck.Override Overrides []ck.Override
GlossaryFiles []string
} }
func processCommand() commandkit.Command { func processingFlags() []commandkit.Flag[processInput] {
stringValue := func(s string) (string, error) { return s, nil } stringValue := func(s string) (string, error) { return s, nil }
flags := []commandkit.Flag[processInput]{ flags := []commandkit.Flag[processInput]{
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "glossary-file", Usage: "Runtime glossary file (repeatable)."}, nil, stringValue, func(in *processInput, v commandkit.Supplied[[]string]) { in.GlossaryFiles = v.Value }),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Application configuration file."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Config = v }), commandkit.ValueFlag(commandkit.FlagMeta{Name: "config", Usage: "Application configuration file."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Config = v }),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Configuration overlay."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Overlay = v }), commandkit.ValueFlag(commandkit.FlagMeta{Name: "overlay", Usage: "Configuration overlay."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Overlay = v }),
commandkit.ValueFlag(commandkit.FlagMeta{Name: "output", Usage: "Transcript output file."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Output = v }), commandkit.ValueFlag(commandkit.FlagMeta{Name: "output", Usage: "Transcript output file."}, (*string)(nil), stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Output = v }),
@@ -92,9 +95,20 @@ func processCommand() commandkit.Command {
in.Overrides = append(in.Overrides, ck.Override{Path: ck.Keys("reporting", "enabled"), Value: v.Value, Flag: "--reporting"}) in.Overrides = append(in.Overrides, ck.Override{Path: ck.Keys("reporting", "enabled"), Value: v.Value, Flag: "--reporting"})
} }
})) }))
return commandkit.NewCommand(commandkit.CommandSpec[processInput]{Name: "process", Summary: "Polish a transcript.", Flags: flags, Run: runProcess, return flags
Arguments: []commandkit.Argument[processInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "transcript", Usage: "Transcript JSON file."}, true, stringValue, func(in *processInput, v commandkit.Supplied[string]) { in.Transcript = v.Value })}, }
})
func transcriptArguments() []commandkit.Argument[processInput] {
return []commandkit.Argument[processInput]{commandkit.ValueArgument(commandkit.ArgumentMeta{Name: "transcript", Usage: "Transcript JSON file."}, true, func(s string) (string, error) { return s, nil }, func(in *processInput, v commandkit.Supplied[string]) { in.Transcript = v.Value })}
}
func processCommand() commandkit.Command {
return commandkit.NewCommand(commandkit.CommandSpec[processInput]{Name: "process", Summary: "Polish a transcript.", Flags: processingFlags(), Run: runProcess, Arguments: transcriptArguments()})
}
func preflightCommand() commandkit.Command {
flags := append(processingFlags(), commandkit.BoolFlag(commandkit.FlagMeta{Name: "smoke", Usage: "Verify structured output with selected profiles."}, true, func(in *processInput, v commandkit.Supplied[bool]) { in.Smoke = v }))
return commandkit.NewCommand(commandkit.CommandSpec[processInput]{Name: "preflight", Summary: "Check processing readiness.", Flags: flags, Run: runPreflight, Arguments: transcriptArguments()})
} }
func parseCollectionNames(raw string) (any, error) { func parseCollectionNames(raw string) (any, error) {

View File

@@ -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,25 +26,38 @@ 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
} }
func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) { type runtimePreparationError struct{ cause error }
func (e *runtimePreparationError) Error() string { return e.cause.Error() }
func (e *runtimePreparationError) Unwrap() error { return e.cause }
func checkQuietDestination(input processInput, mode commandkit.ReportingMode) 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 fmt.Errorf("quiet processing requires an output file or /dev/null")
}
return nil
}
func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) {
if err := checkQuietDestination(input, mode); err != nil {
return nil, err
} }
selection := ckconfig.Selection{Config: input.Config, Overlay: input.Overlay, Overrides: input.Overrides} selection := ckconfig.Selection{Config: input.Config, Overlay: input.Overlay, Overrides: input.Overrides}
loaded, err := loadApplication(ctx, selection, struct{}{}, nil) acquired, err := acquireApplication(ctx, selection, acquisitionInput{GlossaryFiles: input.GlossaryFiles})
if err != nil { if err != nil {
return nil, err return nil, err
} }
loaded := acquired.Result
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
@@ -64,6 +77,7 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.
raw = nil raw = nil
} }
protected := append([]string(nil), runtime.SourcePaths...) protected := append([]string(nil), runtime.SourcePaths...)
protected = append(protected, acquired.GlossarySources...)
for _, entry := range loaded.Sources() { for _, entry := range loaded.Sources() {
if entry.Kind == ck.SourceKindFile && entry.Path != "" { if entry.Kind == ck.SourceKindFile && entry.Path != "" {
protected = append(protected, entry.Path) protected = append(protected, entry.Path)
@@ -74,13 +88,46 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.
// preparedProcess groups the output resources and the facts needed for reports. // preparedProcess groups the output resources and the facts needed for reports.
type preparedProcess struct { type preparedProcess struct {
Prepared *preflight.Prepared Prepared *preparedOutput
Invocation *preparedInvocation
RunID string RunID string
Started time.Time Started time.Time
} }
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) { type preparedInvocation struct {
cfg := &loaded.Configuration.Config Loaded *processInputs
Plan *preflight.Plan
Destinations *diagnostics.CheckedDestinations
}
func prepareLocal(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedInvocation, error) {
cfg := &loaded.Configuration.Config.Application
checkedBackends := make(map[string]struct{})
inspectProfile := func(ctx context.Context, id string) error {
profile, err := loaded.Runtime.Engine.InspectProfile(ctx, id)
if errors.Is(err, pk.ErrProfileNotFound) {
return &preflight.SelectionError{Cause: err}
}
if err != nil || profile.Backend == nil {
return err
}
backend := *profile.Backend
if _, ok := checkedBackends[backend]; ok {
return nil
}
_, err = loaded.Runtime.Engine.InspectBackend(ctx, backend)
if errors.Is(err, pk.ErrBackendNotFound) {
return &preflight.SelectionError{Cause: err}
}
if err == nil {
checkedBackends[backend] = struct{}{}
}
return err
}
plan, err := preflight.BuildPlan(ctx, cfg, loaded.Source, inspectProfile)
if err != nil {
return nil, err
}
reportDir := "" reportDir := ""
reportDirSet := false reportDirSet := false
for _, override := range input.Overrides { for _, override := range input.Overrides {
@@ -97,6 +144,22 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu
} }
} }
} }
checked, err := diagnostics.CheckOutput(diagnostics.OutputSelection{InputTranscriptPath: input.Transcript, TranscriptPath: input.Output.Value, ReportDir: reportDir, ReportingEnabled: cfg.Reporting.Enabled, ProtectedPaths: loaded.ProtectedPaths, Stdout: stdout})
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
return &preparedInvocation{Loaded: loaded, Plan: plan, Destinations: checked}, nil
}
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) {
local, err := prepareLocal(ctx, input, loaded, stdout)
if err != nil {
return nil, err
}
cfg := local.Plan.Config
runID, err := generateRunID() runID, err := generateRunID()
if err != nil { if err != nil {
return nil, err return nil, err
@@ -120,42 +183,21 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu
return renderReportBundle(processreport.Failed(failedSnapshot, primary, "initialization", failures)) return renderReportBundle(processreport.Failed(failedSnapshot, primary, "initialization", failures))
} }
} }
var debug *preflight.DebugInput var debug *debugInput
var warnings []error var warnings []error
if input.Debug.Value { if input.Debug.Value {
var effective bytes.Buffer var effective bytes.Buffer
if err := loaded.Configuration.WriteEffective(&effective); err != nil { if err := loaded.Configuration.WriteEffective(&effective); err != nil {
warnings = append(warnings, err) warnings = append(warnings, err)
} }
debug = &preflight.DebugInput{WorkDir: cfg.Diagnostics.WorkDir, RunID: runID, EffectiveConfig: effective.Bytes(), Metadata: diagnostics.InvocationMetadata{Operation: "process", TranscriptPath: input.Transcript, OutputPath: input.Output.Value, Overlay: input.Overlay.Value, ConfigVersion: &cfg.Version, RunID: runID, StartedAt: started}} debug = &debugInput{WorkDir: cfg.Diagnostics.WorkDir, RunID: runID, EffectiveConfig: effective.Bytes(), Metadata: diagnostics.InvocationMetadata{Operation: "process", TranscriptPath: input.Transcript, OutputPath: input.Output.Value, Overlay: input.Overlay.Value, ConfigVersion: &cfg.Version, RunID: runID, StartedAt: started}}
} }
checkedBackends := make(map[string]struct{}) prepared, err := prepareOutput(ctx, local.Destinations, initial, failed, debug)
prepared, err := preflight.Prepare(ctx, preflight.Input{InspectProfile: func(ctx context.Context, id string) error {
profile, err := loaded.Runtime.Engine.InspectProfile(ctx, id)
if errors.Is(err, pk.ErrProfileNotFound) {
return &preflight.SelectionError{Cause: err}
}
if err != nil || profile.Backend == nil {
return err
}
backend := *profile.Backend
if _, ok := checkedBackends[backend]; ok {
return nil
}
_, err = loaded.Runtime.Engine.InspectBackend(ctx, backend)
if errors.Is(err, pk.ErrBackendNotFound) {
return &preflight.SelectionError{Cause: err}
}
if err == nil {
checkedBackends[backend] = struct{}{}
}
return err
}, Config: cfg, Transcript: loaded.Source, Output: diagnostics.OutputSelection{InputTranscriptPath: input.Transcript, TranscriptPath: input.Output.Value, ReportDir: reportDir, ReportingEnabled: cfg.Reporting.Enabled, ProtectedPaths: loaded.ProtectedPaths, Stdout: stdout}, InitialReports: initial, FailedReports: failed, Debug: debug})
if err != nil { if err != nil {
return nil, err return nil, err
} }
prepared.Warnings = append(warnings, prepared.Warnings...) prepared.Warnings = append(warnings, prepared.Warnings...)
return &preparedProcess{Prepared: prepared, RunID: runID, Started: started}, nil return &preparedProcess{Prepared: prepared, Invocation: local, RunID: runID, Started: started}, nil
} }
func generateRunID() (string, error) { func generateRunID() (string, error) {

View File

@@ -2,6 +2,7 @@ package cli
import ( import (
"context" "context"
"errors"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
@@ -9,6 +10,8 @@ import (
"strings" "strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight"
commandkit "go.maximumdirect.net/commandkit" commandkit "go.maximumdirect.net/commandkit"
ck "go.maximumdirect.net/configkit" ck "go.maximumdirect.net/configkit"
) )
@@ -106,3 +109,40 @@ func TestCollectionFlagJSON(t *testing.T) {
} }
} }
} }
func TestInfeasibleChunkingPrecedesOutputInitialization(t *testing.T) {
dir := t.TempDir()
configPath := filepath.Join(dir, "config.yml")
transcriptPath := filepath.Join(dir, "transcript.json")
outputPath := filepath.Join(dir, "output.json")
if err := os.WriteFile(configPath, []byte("version: 3\npipeline:\n stages: []\n"), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(transcriptPath, []byte(`[{"speaker":"Alice","start":0,"end":1,"text":"hello"}]`), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outputPath, []byte("existing"), 0644); err != nil {
t.Fatal(err)
}
input := processInput{Config: commandkit.Supplied[string]{Value: configPath, Set: true}, Transcript: transcriptPath, Output: commandkit.Supplied[string]{Value: outputPath, Set: true}, Debug: commandkit.Supplied[bool]{Value: true, Set: true}}
loaded, err := loadProcessInputs(context.Background(), input, commandkit.ReportingModeOrdinary)
if err != nil {
t.Fatal(err)
}
count := 2
loaded.Configuration.Config.Application.Chunking.TargetSections = &count
_, err = prepareProcess(context.Background(), input, loaded, io.Discard)
var selection *preflight.SelectionError
if !errors.As(err, &selection) {
t.Fatalf("expected selection error, got %v", err)
}
data, err := os.ReadFile(outputPath)
if err != nil || string(data) != "existing" {
t.Fatalf("output changed: %q %v", data, err)
}
for _, name := range []string{"errors.yml", "recoveries.yml", "report.md"} {
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
t.Fatalf("unexpected report %s: %v", name, err)
}
}
}

View File

@@ -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,11 +101,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -113,15 +113,15 @@ pipeline:
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source} inputs := &processInputs{Configuration: loaded.Result, 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)
} }
defer prepared.Prepared.Output.Close() defer prepared.Prepared.Output.Close()
result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) result, err := executePipeline(context.Background(), prepared, func(error) {}, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -213,14 +213,14 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
transport := controlledTransport(func(r *http.Request) (*http.Response, error) { transport := controlledTransport(func(r *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporarily unavailable"}}`)), Request: r}, nil return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"error":{"message":"temporarily unavailable"}}`)), Request: r}, nil
}) })
runtime, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -228,14 +228,14 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source} inputs := &processInputs{Configuration: loaded.Result, 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)
} }
defer prepared.Prepared.Output.Close() defer prepared.Prepared.Output.Close()
result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil) result, err := executePipeline(context.Background(), prepared, func(error) {}, nil)
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"))}, appconfig.Options{})
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.Result, &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.Result, 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(), prepared, func(error) {}, nil)
if err != nil {
t.Fatal(err)
}
if result.Transcript.Segments[0].Text != "hello" || len(result.Snapshot.Errors) != 1 || (result.Snapshot.Errors[0].StageIndex == nil || *result.Snapshot.Errors[0].StageIndex != 0) || len(result.Snapshot.Errors[0].Failures) != 1 || result.Snapshot.Errors[0].Failures[0].Reason != "invalid_output" {
t.Fatalf("transcript=%+v errors=%+v", result.Transcript, result.Snapshot.Errors)
}
}

View File

@@ -1,11 +1,9 @@
package cli package cli
import ( import (
"errors"
"fmt" "fmt"
"time" "time"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
"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/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/processreport" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/processreport"
@@ -39,11 +37,6 @@ func finishProcess(inv commandkit.Invocation, input processInput, prepared *prep
} }
result := prepared.Prepared.Output.Finish(inv.Context, primary, transcript, render) result := prepared.Prepared.Output.Finish(inv.Context, primary, transcript, render)
if result != nil { if result != nil {
var infeasible *chunking.InfeasibleTargetError
var outputFailure diagnostics.FileFailure
if inv.Context.Err() == nil && errors.As(result, &infeasible) && !errors.As(result, &outputFailure) {
return commandkit.Usage(infeasible.Error()).WithCause(result)
}
return commandkit.Failure(result.Error()).WithCause(result) return commandkit.Failure(result.Error()).WithCause(result)
} }
_ = reporter.AtEnd().Info(reporting.CompletionLine(snapshot)) _ = reporter.AtEnd().Info(reporting.CompletionLine(snapshot))

View File

@@ -156,7 +156,7 @@ func TestCanceledEmptyPipelineLeavesTranscriptAndFinalizesReports(t *testing.T)
t.Fatal(err) t.Fatal(err)
} }
defer prepared.Prepared.Output.Close() defer prepared.Prepared.Output.Close()
result, err := executePipeline(inv.Context, loaded, prepared, loaded.Source.Canonical(), func(error) {}, nil) result, err := executePipeline(inv.Context, prepared, func(error) {}, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -6,7 +6,6 @@ import (
"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/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/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/processreport" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/processreport"
@@ -15,9 +14,10 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/modules" "gitea.maximumdirect.net/eric/audita/v4/internal/modules"
) )
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, prepared *preparedProcess, warn func(error), progress func(string)) (processResult, error) {
cfg := &loaded.Configuration.Config loaded := prepared.Invocation.Loaded
specs := prepared.Prepared.Specs cfg := prepared.Invocation.Plan.Config
specs := prepared.Invocation.Plan.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}
var observer *llm.ObservationCollector var observer *llm.ObservationCollector
@@ -62,7 +62,7 @@ func executePipeline(ctx context.Context, loaded *processInputs, prepared *prepa
interactions = writer interactions = writer
} }
output, runErr := runner.New(modules.NewFactory()).Run(ctx, runner.RunInput{ output, runErr := runner.New(modules.NewFactory()).Run(ctx, runner.RunInput{
Config: cfg, Transcript: normalized, ModuleSpecs: specs, Plan: prepared.Invocation.Plan,
Interactions: interactions, Evidence: &evidence, Progress: runnerProgress(progress), Interactions: interactions, Evidence: &evidence, Progress: runnerProgress(progress),
}) })
if debug != nil { if debug != nil {

View File

@@ -0,0 +1,49 @@
package cli
import (
"context"
"errors"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
)
type debugInput struct {
WorkDir string
RunID string
Metadata diagnostics.InvocationMetadata
EffectiveConfig []byte
}
type preparedOutput struct {
Output *diagnostics.OutputSession
Debug *diagnostics.RunDirectory
Warnings []error
}
func prepareOutput(ctx context.Context, checked *diagnostics.CheckedDestinations, initial diagnostics.ReportBundle, failed diagnostics.ReportRenderer, debug *debugInput) (*preparedOutput, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
session := diagnostics.NewOutputSession(checked)
if err := session.Prepare(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, session.Close())
}
if err := session.Initialize(ctx, initial, failed); err != nil {
return nil, errors.Join(err, session.Close())
}
cancelOutput := func(err error) error { return session.Finish(ctx, err, nil, failed) }
if err := ctx.Err(); err != nil {
return nil, cancelOutput(err)
}
result := &preparedOutput{Output: session}
if debug != nil {
result.Debug, result.Warnings = diagnostics.PrepareDebug(debug.WorkDir, debug.RunID, debug.Metadata, debug.EffectiveConfig)
}
if err := ctx.Err(); err != nil {
return nil, cancelOutput(err)
}
return result, nil
}

View File

@@ -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")

View File

@@ -0,0 +1,187 @@
package cli
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
commandkit "go.maximumdirect.net/commandkit"
)
func TestProcessProtectsRuntimeGlossarySources(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()
imported := "imported.yml"
if mode == "report" {
imported = "errors.yml"
}
files := map[string]string{
"config.yml": "version: 3\nllm: {proposal_profile: fixture}\npipeline: {stages: [{module: grammar}]}\n",
"input.json": `[{"speaker":"Alice","start":0,"end":1,"text":"Hello."}]`,
"runtime.yml": fmt.Sprintf("config:\n imports: [{path: %s, required: true}]\nparty: {entries: []}\n", imported),
imported: "reference: {entries: []}\n",
"prompts.yml": fmt.Sprintf("profiles:\n - id: fixture\n endpoint: %s/v1\n model: test\n api_key_required: false\n", server.URL),
}
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 = filepath.Join(dir, "runtime.yml")
}
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"), "--glossary-file", filepath.Join(dir, "runtime.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 error=%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 error=%s", result.Status, calls.Load(), stderr.String())
}
for _, name := range []string{"runtime.yml", imported} {
raw, err := os.ReadFile(filepath.Join(dir, name))
if err != nil || string(raw) != files[name] {
t.Fatalf("source %s changed: %s %v", name, raw, err)
}
}
})
}
}
func TestProcessRuntimeGlossaryFailures(t *testing.T) {
dir := t.TempDir()
files := map[string]string{"config.yml": "version: 3\nglossaries: [party]\npipeline: {stages: [{module: glossary}]}\n", "input.json": `[{"speaker":"Alice","start":0,"end":1,"text":"Hello."}]`, "empty.yml": "party: {entries: []}\n", "bad.yml": "party: [\n"}
for name, data := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
for _, tc := range []struct {
name string
status int
diagnostic string
}{
{"missing.yml", 1, "source.missing"},
{"bad.yml", 2, "yaml.invalid"},
{"empty.yml", 2, "no glossary entries"},
} {
var stdout, stderr bytes.Buffer
output := filepath.Join(dir, "output.json")
status := Run(context.Background(), []string{"process", "--config", filepath.Join(dir, "config.yml"), "--glossary-file", filepath.Join(dir, tc.name), "--output", output, filepath.Join(dir, "input.json")}, &stdout, &stderr)
if status != tc.status || !strings.Contains(stderr.String(), tc.diagnostic) {
t.Fatalf("%s: status=%d stderr=%s", tc.name, status, stderr.String())
}
for _, name := range []string{"output.json", "errors.yml", "recoveries.yml", "report.md"} {
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
t.Fatalf("%s: output %s prepared: %v", tc.name, name, err)
}
}
}
}
func TestNativeCommandsUseRuntimeGlossary(t *testing.T) {
dir := t.TempDir()
for name, data := range map[string]string{
"left.yml": "version: 3\ncontext: {description: left}\nglossary_collections: {party: {entries: [{id: a, name: Left, category: C}]}}\n",
"right.yml": "version: 3\ncontext: {description: right}\nglossary_collections: {party: {entries: [{id: b, name: Right, category: C}]}}\n",
"input.yml": "party: {entries: [{id: c, name: Runtime, category: C}]}\n",
"bad.yml": "party: [\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
app, err := buildApplication()
if err != nil {
t.Fatal(err)
}
run := func(args ...string) (int, string, string) {
t.Helper()
var out, stderr bytes.Buffer
result := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &stderr})
return result.Status, out.String(), stderr.String()
}
main := filepath.Join(dir, "left.yml")
file := filepath.Join(dir, "input.yml")
code, out, stderr := run("config", "show", "--scope=app", "--config", main, "--glossary-file", file)
if code != 0 || !strings.Contains(out, "Runtime") || strings.Contains(out, "name: Left") {
t.Fatalf("show %d %s %s", code, out, stderr)
}
code, out, stderr = run("config", "explain", "--scope=app", "--config", main, "--glossary-file", file, "--path=/glossary_collections/party/entries")
if code != 0 || !strings.Contains(out, "--glossary-file") {
t.Fatalf("explain %d %s %s", code, out, stderr)
}
code, out, stderr = run("config", "diff", "--details", "--scope=app", "--config", main, "--against-config", filepath.Join(dir, "right.yml"), "--glossary-file", file)
if code != 0 || !strings.Contains(out, "left") || !strings.Contains(out, "right") || strings.Contains(out, "glossary_collections") {
t.Fatalf("diff %d %s %s", code, out, stderr)
}
for _, args := range [][]string{{"config", "show", "--scope=promptkit"}, {"promptkit", "list", "prompts"}} {
valid := append(append([]string(nil), args...), "--config", main, "--glossary-file", file)
code, _, stderr = run(valid...)
if code != 0 {
t.Fatalf("%v: %d %s", valid, code, stderr)
}
args = append(args, "--config", main, "--glossary-file", filepath.Join(dir, "bad.yml"))
code, _, stderr = run(args...)
if code == 0 || !strings.Contains(stderr, "bad.yml") {
t.Fatalf("%v: %d %s", args, code, stderr)
}
}
for _, args := range [][]string{{"--help"}, {"version"}, {"config", "scopes"}, {"promptkit", "--help"}} {
code, _, stderr = run(args...)
if code != 0 {
t.Fatalf("%v: %d %s", args, code, stderr)
}
}
}
func TestRuntimeGlossaryUsesInvocationDirectory(t *testing.T) {
root := t.TempDir()
project := filepath.Join(root, "project")
invocation := filepath.Join(root, "invocation")
for _, dir := range []string{project, invocation, filepath.Join(project, "overlays"), filepath.Join(project, "secrets")} {
if err := os.MkdirAll(dir, 0700); err != nil {
t.Fatal(err)
}
}
t.Setenv("AUDITA_GLOSSARY_CONTEXT_TEST", "")
files := map[string]string{
filepath.Join(project, "config.yml"): "version: 3\nconfig: {secrets_dir: secrets, secrets_overwrite: true}\ncontext: {description: main}\n",
filepath.Join(project, "secrets", "AUDITA_GLOSSARY_CONTEXT_TEST"): "loaded",
filepath.Join(project, "glossary.yml"): "reference: {entries: [{id: r, name: Companion, category: C}]}\n",
filepath.Join(project, "overlays", "chosen.yml"): "context: {description: overlay}\n",
filepath.Join(invocation, "input.yml"): "config: {imports: [{path: imported.yml}]}\nparty: {entries: [{id: a, name: Incoming, category: C}]}\n",
filepath.Join(invocation, "imported.yml"): "lore: {entries: [{id: b, name: Imported, category: C}]}\n",
}
for path, data := range files {
if err := os.WriteFile(path, []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
t.Chdir(invocation)
var out, stderr bytes.Buffer
code := Run(context.Background(), []string{"config", "show", "--scope=app", "--config", filepath.Join(project, "config.yml"), "--overlay", "chosen", "--glossary-file", "input.yml"}, &out, &stderr)
if code != 0 || !strings.Contains(out.String(), "Incoming") || !strings.Contains(out.String(), "Imported") || !strings.Contains(out.String(), "Companion") || !strings.Contains(out.String(), "overlay") || os.Getenv("AUDITA_GLOSSARY_CONTEXT_TEST") != "loaded" {
t.Fatalf("status=%d out=%s err=%s", code, out.String(), stderr.String())
}
}

View 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)
}
})
}
}

View File

@@ -33,6 +33,7 @@ type Config struct {
} }
type GlossaryCollection struct { type GlossaryCollection struct {
Instruction string `yaml:"instruction"`
Entries []GlossaryEntry `yaml:"entries"` Entries []GlossaryEntry `yaml:"entries"`
} }
type GlossaryEntry struct { type GlossaryEntry struct {
@@ -50,7 +51,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 +96,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,27 +107,18 @@ func defaults() Config {
} }
} }
const glossaryImports = `config: // GlossaryEntryIdentity identifies entries beneath a collections mapping.
imports: func GlossaryEntryIdentity(prefix ck.SequenceSelector) ck.SequenceIdentity {
- path: glossary.yml selector := append(ck.SequenceSelector(nil), prefix...)
required: false selector = append(selector, ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries"))
destination: [glossary_collections] return ck.SequenceIdentityMatching(selector, "id")
- dir: glossary }
required: false
recursive: true
pattern: ["*.yml", "*.yaml"]
destination: [glossary_collections]
`
// Load resolves the selected main source and preserves native source evidence. // Definition describes the application settings independently of their sources.
func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) { func Definition() ck.Definition[Config] {
input.Imports = true return ck.Definition[Config]{
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{GlossaryEntryIdentity(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections")})},
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 {
if version.Present && (version.Null || version.Text != "3") { if version.Present && (version.Null || version.Text != "3") {
v.Error(ck.Keys("version"), "use application configuration version 3; see docs/migrations/v3.md") v.Error(ck.Keys("version"), "use application configuration version 3; see docs/migrations/v3.md")
@@ -136,8 +127,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 +183,6 @@ func validate(c *Config, v *ck.Validation) {
func validateRuntimeSettings(check func(bool, ck.Path, string), base ck.Path, settings LLM, validation Validation, context Context) { func validateRuntimeSettings(check func(bool, ck.Path, string), base ck.Path, settings LLM, validation Validation, context Context) {
llm := base.Key("llm") llm := base.Key("llm")
check(settings.TransientRetries >= 0, llm.Key("transient_retries"), "retry budget must be non-negative") check(settings.TransientRetries >= 0, llm.Key("transient_retries"), "retry budget must be non-negative")
check(settings.RepairAttempts >= 0 && settings.RepairAttempts <= 3, llm.Key("repair_attempts"), "repair attempts must be between zero and three")
check(settings.CorrectionRepairAttempts >= 0, llm.Key("correction_repair_attempts"), "correction repair attempts must be non-negative") check(settings.CorrectionRepairAttempts >= 0, llm.Key("correction_repair_attempts"), "correction repair attempts must be non-negative")
check(settings.CorrectionRepairProfile == nil || *settings.CorrectionRepairProfile != "", llm.Key("correction_repair_profile"), "correction repair profile must not be empty; use null to clear it") check(settings.CorrectionRepairProfile == nil || *settings.CorrectionRepairProfile != "", llm.Key("correction_repair_profile"), "correction repair profile must not be empty; use null to clear it")
check(settings.OperationTimeout > 0, llm.Key("operation_timeout"), "operation timeout must be positive") check(settings.OperationTimeout > 0, llm.Key("operation_timeout"), "operation timeout must be positive")

View File

@@ -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 {

View 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,
})
}

View File

@@ -63,7 +63,6 @@ func resolveSettings(c *Config, r *ck.Resolution) error {
proposal := llm.Key("proposal_profile") proposal := llm.Key("proposal_profile")
ck.Default(r, proposal, &item.LLM.ProposalProfile, cloneSelection(c.LLM.ProposalProfile), "inherit proposal profile", rootLLM.Key("proposal_profile")) ck.Default(r, proposal, &item.LLM.ProposalProfile, cloneSelection(c.LLM.ProposalProfile), "inherit proposal profile", rootLLM.Key("proposal_profile"))
ck.Default(r, llm.Key("transient_retries"), &item.LLM.TransientRetries, c.LLM.TransientRetries, "inherit retry budget", rootLLM.Key("transient_retries")) ck.Default(r, llm.Key("transient_retries"), &item.LLM.TransientRetries, c.LLM.TransientRetries, "inherit retry budget", rootLLM.Key("transient_retries"))
ck.Default(r, llm.Key("repair_attempts"), &item.LLM.RepairAttempts, c.LLM.RepairAttempts, "inherit repair budget", rootLLM.Key("repair_attempts"))
ck.Default(r, llm.Key("correction_repair_attempts"), &item.LLM.CorrectionRepairAttempts, c.LLM.CorrectionRepairAttempts, "inherit correction repair budget", rootLLM.Key("correction_repair_attempts")) ck.Default(r, llm.Key("correction_repair_attempts"), &item.LLM.CorrectionRepairAttempts, c.LLM.CorrectionRepairAttempts, "inherit correction repair budget", rootLLM.Key("correction_repair_attempts"))
ck.Default(r, llm.Key("operation_timeout"), &item.LLM.OperationTimeout, c.LLM.OperationTimeout, "inherit operation timeout", rootLLM.Key("operation_timeout")) ck.Default(r, llm.Key("operation_timeout"), &item.LLM.OperationTimeout, c.LLM.OperationTimeout, "inherit operation timeout", rootLLM.Key("operation_timeout"))
ck.Default(r, base.Key("validation").Key("max_prompt_tokens"), &item.Validation.MaxPromptTokens, c.Validation.MaxPromptTokens, "inherit validation budget", ck.Keys("validation", "max_prompt_tokens")) ck.Default(r, base.Key("validation").Key("max_prompt_tokens"), &item.Validation.MaxPromptTokens, c.Validation.MaxPromptTokens, "inherit validation budget", ck.Keys("validation", "max_prompt_tokens"))

View File

@@ -27,7 +27,6 @@ func TestResolutionCopiesRootOverridesAndHonorsClears(t *testing.T) {
glossaries: [party] glossaries: [party]
llm: llm:
proposal_profile: A proposal_profile: A
repair_attempts: 2
context: context:
description: root description: root
pipeline: pipeline:
@@ -36,7 +35,6 @@ pipeline:
glossaries: [party] glossaries: [party]
llm: llm:
proposal_profile: B proposal_profile: B
repair_attempts: 0
context: context:
description: "" description: ""
- module: grammar - module: grammar
@@ -52,7 +50,7 @@ pipeline:
if !reflect.DeepEqual(cfg.ProtectedTerms, []string{"spells"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[0].Glossaries, []string{"party"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[1].Glossaries, []string{"spells"}) || len(cfg.Pipeline.Stages[2].Glossaries) != 0 { if !reflect.DeepEqual(cfg.ProtectedTerms, []string{"spells"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[0].Glossaries, []string{"party"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[1].Glossaries, []string{"spells"}) || len(cfg.Pipeline.Stages[2].Glossaries) != 0 {
t.Fatalf("resolved: %+v", cfg) t.Fatalf("resolved: %+v", cfg)
} }
if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].LLM.RepairAttempts != 0 || cfg.Pipeline.Stages[0].Context.Description != "" { if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].Context.Description != "" {
t.Fatalf("clears lost: %+v", cfg.Pipeline.Stages) t.Fatalf("clears lost: %+v", cfg.Pipeline.Stages)
} }
if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" { if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" {

View File

@@ -0,0 +1,71 @@
package diagnostics
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
type probeFile interface {
Name() string
Close() error
}
type probeOperations struct {
create func(string, string) (probeFile, error)
remove func(string) error
}
// ProbeOutput checks whether temporary files can be created beside active regular outputs.
func ProbeOutput(ctx context.Context, checked *CheckedDestinations) error {
return probeOutput(ctx, checked, probeOperations{
create: func(dir, pattern string) (probeFile, error) { return os.CreateTemp(dir, pattern) },
remove: os.Remove,
})
}
func probeOutput(ctx context.Context, checked *CheckedDestinations, ops probeOperations) error {
type target struct{ display, path string }
var targets []target
if checked.transcript != "" && !checked.direct {
targets = append(targets, target{checked.transcript, checked.publishPath})
}
if checked.enabled {
for i, path := range checked.reportDestinations {
targets = append(targets, target{checked.reports[i], path})
}
}
for _, target := range targets {
if err := ctx.Err(); err != nil {
return fmt.Errorf("probe output %q: %w", target.display, err)
}
pattern := ".audita-probe-*"
if strings.HasPrefix(filepath.Base(target.path), ".audita-probe-") {
pattern = ".audita-check-*"
}
file, err := ops.create(filepath.Dir(target.path), pattern)
if err != nil {
return errors.Join(fmt.Errorf("probe output %q: create temporary file: %w", target.display, err), ctx.Err())
}
name := file.Name()
closeErr := file.Close()
removeErr := ops.remove(name)
var failures []error
if closeErr != nil {
failures = append(failures, fmt.Errorf("probe output %q: close temporary file %q: %w", target.display, name, closeErr))
}
if removeErr != nil {
failures = append(failures, fmt.Errorf("probe output %q: remove temporary file %q: %w", target.display, name, removeErr))
}
if err := ctx.Err(); err != nil {
failures = append(failures, fmt.Errorf("probe output %q: %w", target.display, err))
}
if err := errors.Join(failures...); err != nil {
return err
}
}
return ctx.Err()
}

View File

@@ -0,0 +1,157 @@
package diagnostics
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
)
func TestProbeOutputPreservesDestinations(t *testing.T) {
dir := t.TempDir()
output := filepath.Join(dir, "output.json")
for _, name := range []string{output, filepath.Join(dir, ErrorsFile)} {
if err := os.WriteFile(name, []byte("existing"), 0600); err != nil {
t.Fatal(err)
}
}
checked, err := CheckOutput(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true})
if err != nil {
t.Fatal(err)
}
if err := ProbeOutput(context.Background(), checked); err != nil {
t.Fatal(err)
}
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 2 {
t.Fatalf("unexpected files: %v, %v", entries, err)
}
for _, name := range []string{output, filepath.Join(dir, ErrorsFile)} {
data, err := os.ReadFile(name)
if err != nil || string(data) != "existing" {
t.Fatalf("destination changed: %q, %v", data, err)
}
}
}
type testProbeFile struct {
name string
closeErr error
closed bool
cancel context.CancelFunc
}
func (f *testProbeFile) Name() string { return f.name }
func (f *testProbeFile) Close() error {
f.closed = true
if f.cancel != nil {
f.cancel()
}
return f.closeErr
}
func TestProbeFailuresAndCancellation(t *testing.T) {
failure := errors.New("probe failure")
for _, mode := range []string{"create", "close", "remove", "cancel"} {
t.Run(mode, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
checked, err := CheckOutput(OutputSelection{TranscriptPath: filepath.Join(t.TempDir(), "out")})
if err != nil {
t.Fatal(err)
}
file := &testProbeFile{name: "temporary"}
removed := false
ops := probeOperations{
create: func(_, _ string) (probeFile, error) {
if mode == "create" {
return nil, failure
}
return file, nil
},
remove: func(string) error {
removed = true
if mode == "remove" {
return failure
}
return nil
},
}
if mode == "close" {
file.closeErr = failure
}
if mode == "cancel" {
file.cancel = cancel
}
err = probeOutput(ctx, checked, ops)
want := failure
if mode == "cancel" {
want = context.Canceled
}
if !errors.Is(err, want) {
t.Fatalf("error %v does not contain %v", err, want)
}
if mode != "create" && (!file.closed || !removed) {
t.Fatal("probe was not closed and removed")
}
})
}
}
func TestProbeSkipsInactiveAndStreamTargets(t *testing.T) {
checked, err := CheckOutput(OutputSelection{TranscriptPath: os.DevNull, ReportDir: filepath.Join(t.TempDir(), "missing")})
if err != nil {
t.Fatal(err)
}
calls := 0
err = probeOutput(context.Background(), checked, probeOperations{create: func(_, _ string) (probeFile, error) { calls++; return nil, errors.New("unexpected") }, remove: os.Remove})
if err != nil || calls != 0 {
t.Fatalf("stream or inactive reports probed: %d, %v", calls, err)
}
if _, err := CheckOutput(OutputSelection{TranscriptPath: filepath.Join(t.TempDir(), "missing", "out")}); err == nil {
t.Fatal("missing parent accepted")
}
path := filepath.Join(t.TempDir(), "input")
if _, err := CheckOutput(OutputSelection{TranscriptPath: path, ProtectedPaths: []string{path}}); err == nil {
t.Fatal("collision accepted")
}
}
func TestProbeVisitsActiveTargetsAndStopsOnCancellation(t *testing.T) {
dir := t.TempDir()
output := filepath.Join(dir, "out")
checked, err := CheckOutput(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var visited int
ops := probeOperations{
create: func(_, _ string) (probeFile, error) {
visited++
return &testProbeFile{name: "temporary", cancel: cancel}, nil
},
remove: func(string) error { return nil },
}
if err := probeOutput(ctx, checked, ops); !errors.Is(err, context.Canceled) || visited != 1 {
t.Fatalf("cancellation: %v, visits %d", err, visited)
}
var paths []string
ops.create = func(dir, pattern string) (probeFile, error) {
file, err := os.CreateTemp(dir, pattern)
if err == nil {
paths = append(paths, file.Name())
}
return file, err
}
ops.remove = os.Remove
if err := probeOutput(context.Background(), checked, ops); err != nil {
t.Fatal(err)
}
if len(paths) != 4 {
t.Fatalf("expected four probes, got %d", len(paths))
}
}

View File

@@ -68,10 +68,20 @@ type OutputSession struct {
stdout io.Writer stdout io.Writer
} }
// SelectOutput checks active destinations before any output resources are opened. // CheckedDestinations records destination paths and kinds without opening them.
func SelectOutput(selection OutputSelection) (*OutputSession, error) { type CheckedDestinations struct {
session := &OutputSession{enabled: selection.ReportingEnabled, stdout: selection.Stdout} transcript string
session.replace = session.replaceReport publishPath string
reports [3]string
reportDestinations [3]string
enabled bool
direct bool
stdout io.Writer
}
// CheckOutput checks active destinations before any output resources are opened.
func CheckOutput(selection OutputSelection) (*CheckedDestinations, error) {
checked := &CheckedDestinations{enabled: selection.ReportingEnabled, stdout: selection.Stdout}
type destination struct { type destination struct {
display string display string
path string path string
@@ -89,7 +99,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
return destination{display: path, path: resolved, info: info}, nil return destination{display: path, path: resolved, info: info}, nil
} }
var resolvedDir string var resolvedDir string
if session.enabled { if checked.enabled {
if strings.TrimSpace(selection.ReportDir) == "" { if strings.TrimSpace(selection.ReportDir) == "" {
return nil, fmt.Errorf("report directory is required") return nil, fmt.Errorf("report directory is required")
} }
@@ -115,11 +125,11 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
if target.info != nil && target.info.IsDir() { if target.info != nil && target.info.IsDir() {
return nil, fmt.Errorf("transcript output %q is a directory", target.display) return nil, fmt.Errorf("transcript output %q is a directory", target.display)
} }
session.transcript, session.publishPath = target.display, target.path checked.transcript, checked.publishPath = target.display, target.path
session.direct = target.info != nil && !target.info.Mode().IsRegular() checked.direct = target.info != nil && !target.info.Mode().IsRegular()
active = append(active, target) active = append(active, target)
} }
if session.enabled { if checked.enabled {
label := selection.ReportDir label := selection.ReportDir
if !os.IsPathSeparator(label[len(label)-1]) { if !os.IsPathSeparator(label[len(label)-1]) {
label += string(filepath.Separator) label += string(filepath.Separator)
@@ -133,7 +143,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
if target.info != nil && !target.info.Mode().IsRegular() { if target.info != nil && !target.info.Mode().IsRegular() {
return nil, fmt.Errorf("report output %q is not a regular file", target.display) return nil, fmt.Errorf("report output %q is not a regular file", target.display)
} }
session.reports[i], session.reportDestinations[i] = target.display, target.path checked.reports[i], checked.reportDestinations[i] = target.display, target.path
active = append(active, target) active = append(active, target)
} }
} }
@@ -141,7 +151,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
return a.path == b.path || (a.info != nil && b.info != nil && os.SameFile(a.info, b.info)) return a.path == b.path || (a.info != nil && b.info != nil && os.SameFile(a.info, b.info))
} }
if len(active) == 0 { if len(active) == 0 {
return session, nil return checked, nil
} }
var protected []destination var protected []destination
for _, path := range selection.ProtectedPaths { for _, path := range selection.ProtectedPaths {
@@ -154,7 +164,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
} }
} }
var input destination var input destination
if session.enabled && selection.InputTranscriptPath != "" { if checked.enabled && selection.InputTranscriptPath != "" {
var err error var err error
input, err = check(selection.InputTranscriptPath) input, err = check(selection.InputTranscriptPath)
if err != nil { if err != nil {
@@ -167,7 +177,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
return nil, fmt.Errorf("output destination %q conflicts with input %q", target.display, source.display) return nil, fmt.Errorf("output destination %q conflicts with input %q", target.display, source.display)
} }
} }
if (session.transcript == "" || i > 0) && input.path != "" && same(target, input) { if (checked.transcript == "" || i > 0) && input.path != "" && same(target, input) {
return nil, fmt.Errorf("output destination %q conflicts with input %q", target.display, input.display) return nil, fmt.Errorf("output destination %q conflicts with input %q", target.display, input.display)
} }
for _, prior := range active[:i] { for _, prior := range active[:i] {
@@ -176,19 +186,18 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
} }
} }
} }
return session, nil return checked, nil
} }
// PrepareOutput validates destinations and acquires the transcript resource. // NewOutputSession constructs a session without acquiring output resources.
func PrepareOutput(selection OutputSelection) (*OutputSession, error) { func NewOutputSession(checked *CheckedDestinations) *OutputSession {
session, err := SelectOutput(selection) session := &OutputSession{
if err != nil { transcript: checked.transcript, publishPath: checked.publishPath,
return nil, err reports: checked.reports, reportDestinations: checked.reportDestinations,
enabled: checked.enabled, direct: checked.direct, stdout: checked.stdout,
} }
if err := session.Prepare(); err != nil { session.replace = session.replaceReport
return nil, err return session
}
return session, nil
} }
// Prepare opens a sibling temporary file for regular transcript output. // Prepare opens a sibling temporary file for regular transcript output.

View File

@@ -33,20 +33,20 @@ func TestPrepareOutputAllowsInPlaceTranscriptButRejectsReportCollisions(t *testi
t.Fatal(err) t.Fatal(err)
} }
for _, output := range []string{input, alias, hardlink} { for _, output := range []string{input, alias, hardlink} {
if _, err := PrepareOutput(OutputSelection{TranscriptPath: output, InputTranscriptPath: input}); err != nil { if _, err := prepareOutputForTest(OutputSelection{TranscriptPath: output, InputTranscriptPath: input}); err != nil {
t.Fatalf("in-place output rejected: %s: %v", output, err) t.Fatalf("in-place output rejected: %s: %v", output, err)
} }
} }
if _, err := PrepareOutput(OutputSelection{TranscriptPath: filepath.Join(dir, ErrorsFile), ReportDir: dir, ReportingEnabled: true}); err == nil { if _, err := prepareOutputForTest(OutputSelection{TranscriptPath: filepath.Join(dir, ErrorsFile), ReportDir: dir, ReportingEnabled: true}); err == nil {
t.Fatal("report/transcript collision accepted") t.Fatal("report/transcript collision accepted")
} }
if _, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true, ProtectedPaths: []string{filepath.Join(dir, ErrorsFile)}}); err == nil { if _, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true, ProtectedPaths: []string{filepath.Join(dir, ErrorsFile)}}); err == nil {
t.Fatal("report/source collision accepted") t.Fatal("report/source collision accepted")
} }
if err := os.Symlink(input, filepath.Join(dir, ErrorsFile)); err != nil { if err := os.Symlink(input, filepath.Join(dir, ErrorsFile)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true, InputTranscriptPath: input}); err == nil { if _, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true, InputTranscriptPath: input}); err == nil {
t.Fatal("report/input alias accepted") t.Fatal("report/input alias accepted")
} }
if err := os.Remove(filepath.Join(dir, ErrorsFile)); err != nil { if err := os.Remove(filepath.Join(dir, ErrorsFile)); err != nil {
@@ -55,7 +55,7 @@ func TestPrepareOutputAllowsInPlaceTranscriptButRejectsReportCollisions(t *testi
if err := os.Mkdir(filepath.Join(dir, MarkdownFile), 0700); err != nil { if err := os.Mkdir(filepath.Join(dir, MarkdownFile), 0700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if _, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true}); err == nil { if _, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true}); err == nil {
t.Fatal("directory report target accepted") t.Fatal("directory report target accepted")
} }
if got, err := os.ReadFile(input); err != nil || string(got) != "source" { if got, err := os.ReadFile(input); err != nil || string(got) != "source" {
@@ -69,7 +69,7 @@ func TestPrepareOutputPreservesExistingTranscriptAndChecksParent(t *testing.T) {
if err := os.WriteFile(output, []byte("old content"), 0600); err != nil { if err := os.WriteFile(output, []byte("old content"), 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := PrepareOutput(OutputSelection{TranscriptPath: output}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -85,10 +85,10 @@ func TestPrepareOutputPreservesExistingTranscriptAndChecksParent(t *testing.T) {
if info, _ := os.Stat(output); info.Mode().Perm() != 0600 { if info, _ := os.Stat(output); info.Mode().Perm() != 0600 {
t.Fatalf("permission changed: %v", info.Mode()) t.Fatalf("permission changed: %v", info.Mode())
} }
if _, err := PrepareOutput(OutputSelection{TranscriptPath: filepath.Join(dir, "missing", "out.json")}); err == nil { if _, err := prepareOutputForTest(OutputSelection{TranscriptPath: filepath.Join(dir, "missing", "out.json")}); err == nil {
t.Fatal("absent parent accepted") t.Fatal("absent parent accepted")
} }
if _, err := PrepareOutput(OutputSelection{TranscriptPath: dir}); err == nil { if _, err := prepareOutputForTest(OutputSelection{TranscriptPath: dir}); err == nil {
t.Fatal("directory target accepted") t.Fatal("directory target accepted")
} }
entries, err := os.ReadDir(dir) entries, err := os.ReadDir(dir)
@@ -115,7 +115,7 @@ func TestOutputPathsUseFilesystemParent(t *testing.T) {
} }
parent := alias + string(filepath.Separator) + ".." parent := alias + string(filepath.Separator) + ".."
output := parent + string(filepath.Separator) + "out.json" output := parent + string(filepath.Separator) + "out.json"
session, err := PrepareOutput(OutputSelection{TranscriptPath: output, ReportDir: parent, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output, ReportDir: parent, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -146,7 +146,7 @@ func TestOutputPublishesThroughTranscriptAndReportSymlinks(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
} }
session, err := PrepareOutput(OutputSelection{TranscriptPath: transcript, ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: transcript, ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -196,7 +196,7 @@ func TestStagingCleansTemporaryResourcesAfterPublicationFailure(t *testing.T) {
func TestDisabledReportingIgnoresUnusableDirectory(t *testing.T) { func TestDisabledReportingIgnoresUnusableDirectory(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
session, err := PrepareOutput(OutputSelection{TranscriptPath: filepath.Join(dir, "out.json"), ReportDir: filepath.Join(dir, "missing"), ReportingEnabled: false}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: filepath.Join(dir, "out.json"), ReportDir: filepath.Join(dir, "missing"), ReportingEnabled: false})
if err != nil || len(session.ReportPaths()) != 0 { if err != nil || len(session.ReportPaths()) != 0 {
t.Fatalf("disabled reports probed: %+v %v", session, err) t.Fatalf("disabled reports probed: %+v %v", session, err)
} }
@@ -210,7 +210,7 @@ func TestDisabledReportingIgnoresUnusableDirectory(t *testing.T) {
func TestEnabledReportingRequiresExistingDirectory(t *testing.T) { func TestEnabledReportingRequiresExistingDirectory(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
if _, err := PrepareOutput(OutputSelection{ReportDir: filepath.Join(dir, "missing"), ReportingEnabled: true}); err == nil { if _, err := prepareOutputForTest(OutputSelection{ReportDir: filepath.Join(dir, "missing"), ReportingEnabled: true}); err == nil {
t.Fatal("missing report directory accepted") t.Fatal("missing report directory accepted")
} }
if _, err := os.Stat(filepath.Join(dir, "missing")); !errors.Is(err, os.ErrNotExist) { if _, err := os.Stat(filepath.Join(dir, "missing")); !errors.Is(err, os.ErrNotExist) {
@@ -220,7 +220,7 @@ func TestEnabledReportingRequiresExistingDirectory(t *testing.T) {
func TestStdoutModeInitializesAndFinalizesReports(t *testing.T) { func TestStdoutModeInitializesAndFinalizesReports(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -251,7 +251,7 @@ func TestStdoutModeInitializesAndFinalizesReports(t *testing.T) {
func TestInitializeFailureMarksPriorReportFailedBeforeModelWork(t *testing.T) { func TestInitializeFailureMarksPriorReportFailedBeforeModelWork(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -286,7 +286,7 @@ func TestInitializeFailureMarksPriorReportFailedBeforeModelWork(t *testing.T) {
func TestFinalizationCollectsFailuresAndRetainsPublishedTranscript(t *testing.T) { func TestFinalizationCollectsFailuresAndRetainsPublishedTranscript(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
output := filepath.Join(dir, "output.json") output := filepath.Join(dir, "output.json")
session, err := PrepareOutput(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -330,7 +330,7 @@ func TestFailedRenderingKeepsInitializedEvidenceAfterStreamError(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
delivery := errors.New("stream delivery failed") delivery := errors.New("stream delivery failed")
rendering := errors.New("failed report rendering failed") rendering := errors.New("failed report rendering failed")
session, err := PrepareOutput(OutputSelection{ session, err := prepareOutputForTest(OutputSelection{
Stdout: writerFunc(func([]byte) (int, error) { return 0, delivery }), Stdout: writerFunc(func([]byte) (int, error) { return 0, delivery }),
ReportDir: dir, ReportingEnabled: true, ReportDir: dir, ReportingEnabled: true,
}) })
@@ -390,7 +390,7 @@ func TestFailedReportsIncludeLaterDeliveryFailures(t *testing.T) {
} { } {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -430,7 +430,7 @@ func TestFailedReportsIncludeLaterDeliveryFailures(t *testing.T) {
func TestRepeatedFailureOfOneReportCountsOnce(t *testing.T) { func TestRepeatedFailureOfOneReportCountsOnce(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -471,7 +471,7 @@ func TestCancellationAfterStreamDeliveryUsesOnlyFailedReports(t *testing.T) {
defer cancel() defer cancel()
delivery := errors.New("late stream error") delivery := errors.New("late stream error")
var escaped []byte var escaped []byte
session, err := PrepareOutput(OutputSelection{ session, err := prepareOutputForTest(OutputSelection{
Stdout: writerFunc(func(payload []byte) (int, error) { Stdout: writerFunc(func(payload []byte) (int, error) {
escaped = append(escaped, payload...) escaped = append(escaped, payload...)
cancel() cancel()
@@ -502,7 +502,7 @@ func TestCancellationAfterStreamDeliveryUsesOnlyFailedReports(t *testing.T) {
} }
func TestCleanupFailureKeepsTemporaryDirectoryForRetry(t *testing.T) { func TestCleanupFailureKeepsTemporaryDirectoryForRetry(t *testing.T) {
session, err := PrepareOutput(OutputSelection{TranscriptPath: filepath.Join(t.TempDir(), "output.json")}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: filepath.Join(t.TempDir(), "output.json")})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -600,13 +600,14 @@ func TestSelectionAndAbortPreserveTranscript(t *testing.T) {
if err := os.WriteFile(output, []byte("original"), 0600); err != nil { if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := SelectOutput(OutputSelection{TranscriptPath: output}) checked, err := CheckOutput(OutputSelection{TranscriptPath: output})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if entries, err := os.ReadDir(dir); err != nil || len(entries) != 1 { if entries, err := os.ReadDir(dir); err != nil || len(entries) != 1 {
t.Fatalf("selection changed directory: %v %v", entries, err) t.Fatalf("selection changed directory: %v %v", entries, err)
} }
session := NewOutputSession(checked)
if err := session.Prepare(); err != nil { if err := session.Prepare(); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -627,7 +628,7 @@ func TestSelectionAndAbortPreserveTranscript(t *testing.T) {
func TestStdoutAndDeviceDelivery(t *testing.T) { func TestStdoutAndDeviceDelivery(t *testing.T) {
var stdout bytes.Buffer var stdout bytes.Buffer
session, err := PrepareOutput(OutputSelection{Stdout: &stdout}) session, err := prepareOutputForTest(OutputSelection{Stdout: &stdout})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -637,7 +638,7 @@ func TestStdoutAndDeviceDelivery(t *testing.T) {
if stdout.String() != "transcript" { if stdout.String() != "transcript" {
t.Fatalf("stdout=%q", stdout.String()) t.Fatalf("stdout=%q", stdout.String())
} }
session, err = PrepareOutput(OutputSelection{TranscriptPath: os.DevNull}) session, err = prepareOutputForTest(OutputSelection{TranscriptPath: os.DevNull})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -655,7 +656,7 @@ func TestFinishRetainsPrimaryFailureAndAttemptsReports(t *testing.T) {
if err := os.WriteFile(output, []byte("original"), 0600); err != nil { if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := PrepareOutput(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output, ReportDir: dir, ReportingEnabled: true})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -707,7 +708,7 @@ type shortOutput struct{}
func (shortOutput) Write(b []byte) (int, error) { return len(b) / 2, nil } func (shortOutput) Write(b []byte) (int, error) { return len(b) / 2, nil }
func TestShortStdoutWriteIsFailure(t *testing.T) { func TestShortStdoutWriteIsFailure(t *testing.T) {
session, err := PrepareOutput(OutputSelection{Stdout: shortOutput{}}) session, err := prepareOutputForTest(OutputSelection{Stdout: shortOutput{}})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -723,7 +724,7 @@ func TestTranscriptWriteFailureCleansTemporaryResource(t *testing.T) {
if err := os.WriteFile(output, []byte("original"), 0600); err != nil { if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
session, err := PrepareOutput(OutputSelection{TranscriptPath: output}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -746,7 +747,7 @@ func TestTranscriptWriteFailureCleansTemporaryResource(t *testing.T) {
func TestNamedPipeIsNotOpenedDuringPreparation(t *testing.T) { func TestNamedPipeIsNotOpenedDuringPreparation(t *testing.T) {
pipe := filepath.Join(t.TempDir(), "output-pipe") pipe := filepath.Join(t.TempDir(), "output-pipe")
makeNamedPipe(t, pipe) makeNamedPipe(t, pipe)
session, err := PrepareOutput(OutputSelection{TranscriptPath: pipe}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: pipe})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -761,7 +762,7 @@ func TestNamedPipeIsNotOpenedDuringPreparation(t *testing.T) {
func TestLateNamedPipeIsPreserved(t *testing.T) { func TestLateNamedPipeIsPreserved(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
path := filepath.Join(dir, "output") path := filepath.Join(dir, "output")
session, err := PrepareOutput(OutputSelection{TranscriptPath: path}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: path})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -784,7 +785,7 @@ func TestLateNamedPipeIsPreserved(t *testing.T) {
func TestStreamChangedToRegularFileIsPreserved(t *testing.T) { func TestStreamChangedToRegularFileIsPreserved(t *testing.T) {
path := filepath.Join(t.TempDir(), "output") path := filepath.Join(t.TempDir(), "output")
makeNamedPipe(t, path) makeNamedPipe(t, path)
session, err := PrepareOutput(OutputSelection{TranscriptPath: path}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: path})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -814,3 +815,15 @@ func makeNamedPipe(t *testing.T, path string) {
t.Fatalf("mkfifo: %v %s", err, output) t.Fatalf("mkfifo: %v %s", err, output)
} }
} }
func prepareOutputForTest(selection OutputSelection) (*OutputSession, error) {
checked, err := CheckOutput(selection)
if err != nil {
return nil, err
}
session := NewOutputSession(checked)
if err := session.Prepare(); err != nil {
return nil, err
}
return session, nil
}

View File

@@ -23,7 +23,7 @@ func TestTranscriptStreamDestinations(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
// Preparation must finish even though the pipe has no reader yet. // Preparation must finish even though the pipe has no reader yet.
session, err := PrepareOutput(OutputSelection{TranscriptPath: path}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: path})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -59,7 +59,7 @@ func TestTranscriptStreamWriteFailure(t *testing.T) {
if _, err := os.Stat("/dev/full"); os.IsNotExist(err) { if _, err := os.Stat("/dev/full"); os.IsNotExist(err) {
t.Skip("/dev/full unavailable") t.Skip("/dev/full unavailable")
} }
session, err := PrepareOutput(OutputSelection{TranscriptPath: "/dev/full"}) session, err := prepareOutputForTest(OutputSelection{TranscriptPath: "/dev/full"})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -68,3 +68,17 @@ func TestTranscriptStreamWriteFailure(t *testing.T) {
t.Fatalf("write failure lost: %+v", failures) t.Fatalf("write failure lost: %+v", failures)
} }
} }
func TestProbeSkipsNamedPipeWithoutOpeningIt(t *testing.T) {
fifo := filepath.Join(t.TempDir(), "output.pipe")
if err := syscall.Mkfifo(fifo, 0600); err != nil {
t.Fatal(err)
}
checked, err := CheckOutput(OutputSelection{TranscriptPath: fifo})
if err != nil {
t.Fatal(err)
}
if err := ProbeOutput(context.Background(), checked); err != nil {
t.Fatal(err)
}
}

View File

@@ -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"`
}

View File

@@ -31,6 +31,8 @@ type TranscriptModule interface {
type StructuredCompletionRequest = structuredoutput.Request type StructuredCompletionRequest = structuredoutput.Request
type StructuredCompletionResponse = structuredoutput.Response type StructuredCompletionResponse = structuredoutput.Response
type GlossaryInstruction = promptcontext.GlossaryInstruction
// ModuleRunSpec identifies one resolved module instance in a pipeline. // ModuleRunSpec identifies one resolved module instance in a pipeline.
type ModuleRunSpec struct { type ModuleRunSpec struct {
ModuleKey string `json:"module_key"` ModuleKey string `json:"module_key"`
@@ -40,6 +42,7 @@ type ModuleRunSpec struct {
ID *string `json:"-"` ID *string `json:"-"`
Settings config.Stage `json:"-"` Settings config.Stage `json:"-"`
Glossary []glossary.Entry `json:"-"` Glossary []glossary.Entry `json:"-"`
GlossaryInstructions []GlossaryInstruction `json:"-"`
ProtectedTerms []glossary.Term `json:"-"` ProtectedTerms []glossary.Term `json:"-"`
GlossaryView *validators.GlossaryView `json:"-"` GlossaryView *validators.GlossaryView `json:"-"`
GlossaryVariables *promptcontext.GlossaryVariables `json:"-"` GlossaryVariables *promptcontext.GlossaryVariables `json:"-"`
@@ -56,6 +59,7 @@ func (s *ModuleRunSpec) PrepareGlossary() error {
if err != nil { if err != nil {
return err return err
} }
variables.InstructionsBlock = promptcontext.GlossaryInstructionsBlock(s.GlossaryInstructions)
s.GlossaryVariables = &variables s.GlossaryVariables = &variables
} }
if s.GlossaryView == nil { if s.GlossaryView == nil {
@@ -140,10 +144,16 @@ func ResolveModuleRunSpecs(cfg *config.Config) []ModuleRunSpec {
key := GlossarySelection(item) key := GlossarySelection(item)
if prior, ok := selections[key]; ok { if prior, ok := selections[key]; ok {
spec.Glossary = specs[prior].Glossary spec.Glossary = specs[prior].Glossary
spec.GlossaryInstructions = specs[prior].GlossaryInstructions
spec.ProtectedTerms = specs[prior].ProtectedTerms spec.ProtectedTerms = specs[prior].ProtectedTerms
continue continue
} }
selected := glossary.Select(cfg.GlossaryCollections, item.Glossaries) selected := glossary.Select(cfg.GlossaryCollections, item.Glossaries)
for _, name := range item.Glossaries {
if collection, ok := cfg.GlossaryCollections[name]; ok {
spec.GlossaryInstructions = append(spec.GlossaryInstructions, GlossaryInstruction{Collection: name, Text: collection.Instruction})
}
}
protected := glossary.Select(cfg.GlossaryCollections, item.ProtectedTerms) protected := glossary.Select(cfg.GlossaryCollections, item.ProtectedTerms)
var excluded []glossary.Entry var excluded []glossary.Entry
if key.exempt { if key.exempt {

View File

@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"reflect" "reflect"
"strings"
"testing" "testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking" "gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
@@ -92,6 +93,36 @@ func TestResolveModuleRunSpecs(t *testing.T) {
} }
} }
func TestResolveGlossaryInstructions(t *testing.T) {
cfg := &config.Config{
GlossaryCollections: map[string]config.GlossaryCollection{
"one": {Instruction: "First {{literal}}"}, "two": {Instruction: "Second"}, "protected": {Instruction: "Protection only"}, "empty": {},
},
Pipeline: config.Pipeline{Stages: []config.Stage{
{Module: "grammar", Glossaries: []string{"two", "empty", "one"}, ProtectedTerms: []string{"protected"}},
{Module: "grammar", Glossaries: []string{"two", "empty", "one"}, ProtectedTerms: []string{"protected"}},
{Module: "grammar", Glossaries: []string{"one"}, ProtectedTerms: []string{"protected"}},
}},
}
specs := ResolveModuleRunSpecs(cfg)
want := []GlossaryInstruction{{Collection: "two", Text: "Second"}, {Collection: "empty"}, {Collection: "one", Text: "First {{literal}}"}}
for _, spec := range specs[:2] {
if !reflect.DeepEqual(spec.GlossaryInstructions, want) {
t.Fatalf("instructions = %+v, want %+v", spec.GlossaryInstructions, want)
}
}
if !reflect.DeepEqual(specs[2].GlossaryInstructions, want[2:]) {
t.Fatalf("specific selection = %+v", specs[2].GlossaryInstructions)
}
if err := specs[0].PrepareGlossary(); err != nil {
t.Fatal(err)
}
block := specs[0].GlossaryVariables.InstructionsBlock
if !strings.Contains(block, "two") || !strings.Contains(block, "one") || !strings.Contains(block, "First {{literal}}") || strings.Index(block, "Second") > strings.Index(block, "First") || strings.Contains(block, "empty") || strings.Contains(block, "Protection only") {
t.Fatalf("instruction block = %q", block)
}
}
func TestSectionMetadataFromSection(t *testing.T) { func TestSectionMetadataFromSection(t *testing.T) {
section := chunking.Section{ section := chunking.Section{
Index: 3, Index: 3,

View File

@@ -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 {

View File

@@ -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,11 +24,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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{})

View File

@@ -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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -105,32 +131,32 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
} }
return &http.Response{StatusCode: step.status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil return &http.Response{StatusCode: step.status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}) })
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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())
}
})
}
}

View File

@@ -14,8 +14,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/responseschema" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
"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 +32,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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -56,7 +57,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
body := fmt.Sprintf(`{"model":%q,"choices":[{"message":{"content":%s}}]}`, req.Model, content) body := fmt.Sprintf(`{"model":%q,"choices":[{"message":{"content":%s}}]}`, req.Model, content)
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, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -69,8 +70,15 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"} selected := contracts.ResolveModuleRunSpecs(&config.Config{
initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: vars, CaptureExchange: true}, &map[string]any{}) GlossaryCollections: map[string]config.GlossaryCollection{"party": {Instruction: "Keep {{literal}} names"}},
Pipeline: config.Pipeline{Stages: []config.Stage{{Module: "grammar", Glossaries: []string{"party"}}}},
})
if err := selected[0].PrepareGlossary(); err != nil {
t.Fatal(err)
}
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]", "GlossaryInstructionsBlock": selected[0].GlossaryVariables.InstructionsBlock}
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 +94,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)
@@ -95,6 +103,11 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
t.Fatalf("models = %v", models) t.Fatalf("models = %v", models)
} }
prefix := messages[0] prefix := messages[0]
initialMessages, _ := json.Marshal(prefix)
repairMessages, _ := json.Marshal(messages[1])
if !strings.Contains(string(initialMessages), "Keep {{literal}} names") || !strings.Contains(string(repairMessages), "Keep {{literal}} names") {
t.Fatalf("guidance missing from proposal or repair: %s %s", initialMessages, repairMessages)
}
if len(messages) != 3 || !reflect.DeepEqual(messages[1][:len(prefix)], prefix) || !reflect.DeepEqual(messages[2][:len(prefix)], prefix) { if len(messages) != 3 || !reflect.DeepEqual(messages[1][:len(prefix)], prefix) || !reflect.DeepEqual(messages[2][:len(prefix)], prefix) {
t.Fatalf("prefixes: %+v", messages) t.Fatalf("prefixes: %+v", messages)
} }
@@ -111,7 +124,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 +149,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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -154,15 +167,15 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
body := fmt.Sprintf(`{"model":"fixture","choices":[{"message":{"content":%s}}]}`, content) body := fmt.Sprintf(`{"model":"fixture","choices":[{"message":{"content":%s}}]}`, content)
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, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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 +185,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
result = turn.Response result = turn.Response
return nil, turn.Err return nil, turn.Err
} }
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil
}) })
if err != nil || exhausted || result == nil { if err != nil || exhausted || result == nil {
t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err) t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err)

View File

@@ -6,7 +6,6 @@ import (
"testing" "testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts" "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit" pk "go.maximumdirect.net/promptkit"
@@ -31,7 +30,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := adapterRequest(responseschema.CorrectionSetKey) req := adapterRequest("proposal")
req.CaptureExchange = true req.CaptureExchange = true
base, err := client.CompleteStructured(context.Background(), req, &map[string]any{}) base, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
if err != nil { if err != nil {
@@ -55,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())
}
}

View File

@@ -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,11 +29,11 @@ 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)}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
first, err := NewRuntime(context.Background(), loaded, nil) first, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -60,7 +60,7 @@ func TestEngineCapturesAutomaticPromptSources(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
write("message.txt", "second") write("message.txt", "second")
second, err := NewRuntime(context.Background(), loaded, nil) second, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -70,11 +70,11 @@ 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()}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -103,11 +103,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
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"))}, appconfig.Options{}); err == nil || appconfig.IsAssetError(err) {
t.Fatalf("peer conflict classification: %v", err) t.Fatalf("peer conflict classification: %v", err)
} }
} }
@@ -144,12 +144,12 @@ 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}}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
t.Chdir(t.TempDir()) t.Chdir(t.TempDir())
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -181,11 +181,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -211,11 +211,11 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View File

@@ -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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -48,7 +50,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
} }
return nil, providerErr return nil, providerErr
})} })}
runtime, err := NewRuntime(context.Background(), loaded, httpClient) runtime, err := NewRuntime(context.Background(), loaded.Result, httpClient)
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"))}, appconfig.Options{})
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"))}, appconfig.Options{})
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.Result, 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)
} }
@@ -127,7 +145,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
cancel() cancel()
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -162,7 +180,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
body := `{"model":"one","choices":[{"message":{"content":"{\"corrections\":[]}"}}]}` body := `{"model":"one","choices":[{"message":{"content":"{\"corrections\":[]}"}}]}`
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, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -213,7 +231,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
} }
return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}) })
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -251,11 +269,11 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
body := `{"model":"fixture","choices":[{"message":{"content":"{\"corrections\":[]}"}}]}` body := `{"model":"fixture","choices":[{"message":{"content":"{\"corrections\":[]}"}}]}`
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, &http.Client{Transport: transport}) runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}} req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
for _, tc := range []struct{ profile, auth string }{{"inherited", "Bearer backend-secret-value"}, {"explicit", "Bearer profile-secret-value"}, {"cleared", ""}} { for _, tc := range []struct{ profile, auth string }{{"inherited", "Bearer backend-secret-value"}, {"explicit", "Bearer profile-secret-value"}, {"cleared", ""}} {
t.Run(tc.profile, func(t *testing.T) { t.Run(tc.profile, func(t *testing.T) {
client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{}) client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{})

View File

@@ -9,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)}}
} }

View File

@@ -9,7 +9,6 @@ import (
"testing" "testing"
"time" "time"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
pk "go.maximumdirect.net/promptkit" pk "go.maximumdirect.net/promptkit"
) )
@@ -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)
}
}

View File

@@ -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) }

View File

@@ -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()}, appconfig.Options{})
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")
} }
} }

View File

@@ -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()}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View 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}}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
runtime, err := NewRuntime(context.Background(), loaded.Result, 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)
}
}
}

View File

@@ -0,0 +1,96 @@
package llm
import (
"context"
"errors"
"fmt"
pk "go.maximumdirect.net/promptkit"
)
type VerificationStatus string
const (
VerificationSuccess VerificationStatus = "success"
VerificationNegative VerificationStatus = "negative"
VerificationUnsupported VerificationStatus = "unsupported"
VerificationInconclusive VerificationStatus = "inconclusive"
)
type ProfileVerification struct {
ProfileID string
Status VerificationStatus
Report *pk.SmokeTestReport
Err error
}
type smokeTester interface {
SmokeTest(context.Context, pk.SmokeTestRequest) (*pk.SmokeTestReport, error)
}
func classifyStructuredOutput(report *pk.SmokeTestReport, err error) VerificationStatus {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return VerificationInconclusive
}
if err != nil {
return VerificationNegative
}
if report == nil || report.Kind != pk.SmokeTestStructuredOutput {
return VerificationInconclusive
}
if !report.Supported || (report.Applicable != nil && !*report.Applicable) {
return VerificationUnsupported
}
if report.Failure != pk.ExecutionFailureNone {
return VerificationNegative
}
if !report.Completed || report.Applicable == nil {
return VerificationInconclusive
}
for _, fact := range []*bool{report.Facts.GenerationCompleted, report.Facts.ValidJSON, report.Facts.SchemaMatched} {
if fact != nil && !*fact {
return VerificationNegative
}
}
for _, fact := range []*bool{report.Facts.GenerationCompleted, report.Facts.ValidJSON, report.Facts.SchemaMatched} {
if fact == nil {
return VerificationInconclusive
}
}
return VerificationSuccess
}
// VerifyStructuredOutput checks selected profiles sequentially and retains native evidence.
func VerifyStructuredOutput(ctx context.Context, engine smokeTester, profiles []string, progress func(string)) ([]ProfileVerification, error) {
var results []ProfileVerification
var failures []error
for _, id := range profiles {
if err := ctx.Err(); err != nil {
failures = append(failures, err)
break
}
if progress != nil {
progress(id)
}
report, err := engine.SmokeTest(ctx, pk.SmokeTestRequest{Kind: pk.SmokeTestStructuredOutput, ProfileID: id})
status := classifyStructuredOutput(report, err)
results = append(results, ProfileVerification{ProfileID: id, Status: status, Report: report, Err: err})
if status != VerificationSuccess {
if err != nil {
failures = append(failures, fmt.Errorf("profile %q: %w", id, err))
} else {
failures = append(failures, fmt.Errorf("profile %q: structured-output verification %s", id, status))
}
}
if canceled := ctx.Err(); canceled != nil {
if !errors.Is(err, canceled) {
failures = append(failures, canceled)
}
break
}
}
if err := ctx.Err(); err != nil && !errors.Is(errors.Join(failures...), err) {
failures = append(failures, err)
}
return results, errors.Join(failures...)
}

View File

@@ -0,0 +1,132 @@
package llm
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
ck "go.maximumdirect.net/configkit"
pk "go.maximumdirect.net/promptkit"
)
func boolValue(v bool) *bool { return &v }
func positiveSmokeReport() *pk.SmokeTestReport {
return &pk.SmokeTestReport{Kind: pk.SmokeTestStructuredOutput, Supported: true, Applicable: boolValue(true), Completed: true, Facts: pk.SmokeTestFacts{GenerationCompleted: boolValue(true), ValidJSON: boolValue(true), SchemaMatched: boolValue(true)}}
}
func TestStructuredOutputClassification(t *testing.T) {
cases := []struct {
name string
change func(*pk.SmokeTestReport)
err error
want VerificationStatus
}{
{"success without HTTP facts", func(*pk.SmokeTestReport) {}, nil, VerificationSuccess},
{"negative", func(r *pk.SmokeTestReport) { r.Facts.SchemaMatched = boolValue(false) }, nil, VerificationNegative},
{"unsupported", func(r *pk.SmokeTestReport) { r.Supported = false }, nil, VerificationUnsupported},
{"inapplicable", func(r *pk.SmokeTestReport) { r.Applicable = boolValue(false) }, nil, VerificationUnsupported},
{"unknown applicability", func(r *pk.SmokeTestReport) { r.Applicable = nil }, nil, VerificationInconclusive},
{"unknown fact", func(r *pk.SmokeTestReport) { r.Facts.ValidJSON = nil }, nil, VerificationInconclusive},
{"incomplete", func(r *pk.SmokeTestReport) { r.Completed = false }, nil, VerificationInconclusive},
{"wrong kind", func(r *pk.SmokeTestReport) { r.Kind = pk.SmokeTestTextInference }, nil, VerificationInconclusive},
{"native failure", func(r *pk.SmokeTestReport) { r.Failure = pk.ExecutionFailureKind("transport") }, nil, VerificationNegative},
{"error", func(*pk.SmokeTestReport) {}, errors.New("failed"), VerificationNegative},
{"cancellation", func(*pk.SmokeTestReport) {}, context.Canceled, VerificationInconclusive},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := positiveSmokeReport()
tc.change(r)
if got := classifyStructuredOutput(r, tc.err); got != tc.want {
t.Fatalf("got %s want %s", got, tc.want)
}
})
}
if got := classifyStructuredOutput(nil, nil); got != VerificationInconclusive {
t.Fatalf("nil report: %s", got)
}
}
type smokeFunc func(context.Context, pk.SmokeTestRequest) (*pk.SmokeTestReport, error)
func (f smokeFunc) SmokeTest(ctx context.Context, request pk.SmokeTestRequest) (*pk.SmokeTestReport, error) {
return f(ctx, request)
}
func TestVerifyStructuredOutputContinuesAndStopsOnCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
failure := errors.New("failure")
var calls []string
engine := smokeFunc(func(_ context.Context, request pk.SmokeTestRequest) (*pk.SmokeTestReport, error) {
if request.Kind != pk.SmokeTestStructuredOutput || request.Execution != nil || request.TransientRetries != nil || request.PromptID != "" || request.APIKey != "" || request.BackendID != "" {
t.Fatalf("unexpected request: %+v", request)
}
calls = append(calls, request.ProfileID)
switch request.ProfileID {
case "first":
return nil, failure
case "second":
cancel()
return positiveSmokeReport(), context.Canceled
default:
return positiveSmokeReport(), nil
}
})
results, err := VerifyStructuredOutput(ctx, engine, []string{"first", "second", "third"}, nil)
if !slices.Equal(calls, []string{"first", "second"}) || len(results) != 2 || results[1].Report == nil || !errors.Is(err, failure) || !errors.Is(err, context.Canceled) {
t.Fatalf("calls=%v results=%+v error=%v", calls, results, err)
}
}
func TestVerifyStructuredOutputUsesNativeEngine(t *testing.T) {
dir := t.TempDir()
for name, body := range map[string]string{"config.yml": "version: 3\n", "prompts.yml": "profiles:\n - id: fixture\n endpoint: https://example.invalid/v1\n model: fixture-model\n"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
calls := 0
transport := transportFunc(func(r *http.Request) (*http.Response, error) {
calls++
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Fatal(err)
}
if body["model"] != "fixture-model" || body["response_format"] == nil {
t.Errorf("unexpected request: %v", body)
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"model":"fixture-model","choices":[{"message":{"role":"assistant","content":"{\"status\":\"ok\"}"}}]}`)), Request: r}, nil
})
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil {
t.Fatal(err)
}
results, err := VerifyStructuredOutput(context.Background(), runtime.Engine, []string{"fixture"}, nil)
if err != nil || calls != 1 || len(results) != 1 || results[0].Status != VerificationSuccess {
t.Fatalf("calls=%d results=%+v err=%v", calls, results, err)
}
}
func TestVerificationIdentifiesProfileBeforeDispatch(t *testing.T) {
var current string
engine := smokeFunc(func(_ context.Context, req pk.SmokeTestRequest) (*pk.SmokeTestReport, error) {
if current != req.ProfileID {
t.Fatalf("progress %q before dispatch %q", current, req.ProfileID)
}
return positiveSmokeReport(), nil
})
_, err := VerifyStructuredOutput(context.Background(), engine, []string{"one", "two"}, func(id string) { current = id })
if err != nil {
t.Fatal(err)
}
}

View File

@@ -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)

View File

@@ -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,18 +33,21 @@ 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"))}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := NewRuntime(context.Background(), loaded, nil) runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil { if err != nil {
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"),

View File

@@ -0,0 +1,75 @@
package preflight
import (
"context"
"errors"
"fmt"
"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/normalization"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
)
// Plan holds the local processing decisions for one invocation.
type Plan struct {
Config *config.Config
Specs []contracts.ModuleRunSpec
Transcript *schema.Transcript
Summary *normalization.NormalizationSummary
Sections []chunking.Section
Profiles []string
}
// BuildPlan resolves processing selections, normalizes the input, and fixes its chunks.
func BuildPlan(ctx context.Context, cfg *config.Config, source *schema.SourceTranscript, inspect func(context.Context, string) error) (*Plan, error) {
if cfg == nil {
return nil, fmt.Errorf("application configuration is required")
}
if source == nil {
return nil, fmt.Errorf("transcript is required")
}
var profiles []string
var inspectAndCollect func(context.Context, string) error
if inspect != nil {
inspectAndCollect = func(ctx context.Context, id string) error {
if err := inspect(ctx, id); err != nil {
return err
}
profiles = append(profiles, id)
return nil
}
}
specs, err := ProcessingPlan(ctx, cfg, inspectAndCollect)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,
})
transcript, summary := normalizer.Normalize(source.Canonical())
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("normalize transcript: %w", err)
}
chunker := chunking.NewChunker(chunking.ChunkingConfig{
MaxSectionTokens: cfg.Chunking.MaxSectionTokens, MinSectionTokens: cfg.Chunking.MinSectionTokens,
TargetSections: cfg.Chunking.TargetSections,
})
sections, err := chunker.ChunkTranscript(transcript)
if err != nil {
var infeasible *chunking.InfeasibleTargetError
if errors.As(err, &infeasible) {
return nil, &SelectionError{Cause: fmt.Errorf("chunk normalized transcript: %w", err)}
}
return nil, fmt.Errorf("chunk normalized transcript: %w", err)
}
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("chunk normalized transcript: %w", err)
}
return &Plan{Config: cfg, Specs: specs, Transcript: transcript, Summary: summary, Sections: sections, Profiles: profiles}, nil
}

View File

@@ -0,0 +1,73 @@
package preflight
import (
"context"
"errors"
"slices"
"strings"
"testing"
"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/schema"
)
func TestBuildPlanResolvesProfilesAndChunks(t *testing.T) {
proposal, validation, repair, unused := "proposal", "validation", "repair", "unused"
cfg := &config.Config{
Chunking: config.Chunking{MaxSectionTokens: 100},
Pipeline: config.Pipeline{Stages: []config.Stage{
{Module: "grammar", LLM: config.LLM{ProposalProfile: &proposal, ValidationProfile: &validation, CorrectionRepairProfile: &unused}},
{Module: "grammar", LLM: config.LLM{ProposalProfile: &validation, ValidationProfile: &proposal, CorrectionRepairProfile: &repair, CorrectionRepairAttempts: 1}},
}},
}
source := &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Start: 0, End: 1, Text: "hello"}, {Speaker: "B", Start: 2, End: 3, Text: "world"}}}
var inspected []string
plan, err := BuildPlan(context.Background(), cfg, source, func(_ context.Context, id string) error { inspected = append(inspected, id); return nil })
if err != nil {
t.Fatal(err)
}
if !slices.Equal(plan.Profiles, []string{proposal, validation, repair}) || !slices.Equal(plan.Profiles, inspected) {
t.Fatalf("profiles %v, inspected %v", plan.Profiles, inspected)
}
if len(plan.Specs) != 2 || len(plan.Transcript.Segments) != 2 || plan.Summary.InputSegmentCount != 2 || len(plan.Sections) != 1 || plan.Sections[0].StartSegmentID != 1 || plan.Sections[0].EndSegmentID != 2 {
t.Fatalf("unexpected plan: %+v", plan)
}
count := 3
cfg.Chunking.TargetSections = &count
_, err = BuildPlan(context.Background(), cfg, source, func(context.Context, string) error { return nil })
var selection *SelectionError
var infeasible *chunking.InfeasibleTargetError
if !errors.As(err, &selection) || !errors.As(err, &infeasible) {
t.Fatalf("expected input selection failure, got %v", err)
}
}
func TestBuildPlanEmptyPipeline(t *testing.T) {
cfg := &config.Config{Chunking: config.Chunking{MaxSectionTokens: 100}}
plan, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Text: "hello"}}}, nil)
if err != nil || len(plan.Profiles) != 0 || len(plan.Specs) != 0 || len(plan.Sections) != 1 {
t.Fatalf("plan %+v, error %v", plan, err)
}
}
func TestBuildPlanRetainsNormalizedContentAndGuidance(t *testing.T) {
profile := "selected"
cfg := &config.Config{
Chunking: config.Chunking{MaxSectionTokens: 100},
Normalization: config.Normalization{MaxSegmentGap: 2, EllipsisGap: 2, MaxSegmentDuration: 10, MaxSegmentTokens: 100},
GlossaryCollections: map[string]config.GlossaryCollection{"terms": {Instruction: "Use the shared vocabulary", Entries: []config.GlossaryEntry{{ID: "one", Name: "Example"}}}},
Pipeline: config.Pipeline{Stages: []config.Stage{{Module: "glossary", Glossaries: []string{"terms"}, LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}}},
}
source := &schema.SourceTranscript{Segments: []schema.SourceSegment{{Speaker: "A", Start: 0, End: 1, Text: "hello"}, {Speaker: "A", Start: 1.1, End: 2, Text: "world"}}}
plan, err := BuildPlan(context.Background(), cfg, source, func(context.Context, string) error { return nil })
if err != nil {
t.Fatal(err)
}
if len(plan.Transcript.Segments) != 1 || plan.Transcript.Segments[0].Text != "hello world" || plan.Summary.MergesPerformed != 1 || len(plan.Sections) != 1 || plan.Sections[0].Segments[0].Text != "hello world" {
t.Fatalf("normalization or chunks: %+v", plan)
}
if !strings.Contains(plan.Specs[0].GlossaryVariables.InstructionsBlock, "Use the shared vocabulary") {
t.Fatalf("guidance missing: %+v", plan.Specs[0])
}
}

View File

@@ -1,91 +1,16 @@
// Package preflight checks resolved processing inputs and prepares output resources. // Package preflight prepares provider-independent processing inputs.
package preflight package preflight
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"slices" "slices"
"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/diagnostics"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/modulecatalog" "gitea.maximumdirect.net/eric/audita/v4/internal/core/modulecatalog"
"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"
) )
// Input contains already acquired application and transcript inputs.
type Input struct {
InspectProfile func(context.Context, string) error
Config *config.Config
Transcript *schema.SourceTranscript
Output diagnostics.OutputSelection
InitialReports diagnostics.ReportBundle
FailedReports diagnostics.ReportRenderer
Debug *DebugInput
}
type DebugInput struct {
WorkDir string
RunID string
Metadata diagnostics.InvocationMetadata
EffectiveConfig []byte
}
type Prepared struct {
Specs []contracts.ModuleRunSpec
Output *diagnostics.OutputSession
Debug *diagnostics.RunDirectory
Warnings []error
}
// Prepare validates invocation inputs and collisions before acquiring outputs.
func Prepare(ctx context.Context, input Input) (*Prepared, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if input.Config == nil {
return nil, fmt.Errorf("application configuration is required")
}
if input.Transcript == nil {
return nil, fmt.Errorf("transcript is required")
}
specs, err := ProcessingPlan(ctx, input.Config, input.InspectProfile)
if err != nil {
return nil, err
}
session, err := diagnostics.SelectOutput(input.Output)
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if err := session.Prepare(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, errors.Join(err, session.Close())
}
if err := session.Initialize(ctx, input.InitialReports, input.FailedReports); err != nil {
return nil, errors.Join(err, session.Close())
}
cancelOutput := func(err error) error {
return session.Finish(ctx, err, nil, input.FailedReports)
}
if err := ctx.Err(); err != nil {
return nil, cancelOutput(err)
}
result := &Prepared{Specs: specs, Output: session}
if input.Debug != nil {
result.Debug, result.Warnings = diagnostics.PrepareDebug(input.Debug.WorkDir, input.Debug.RunID, input.Debug.Metadata, input.Debug.EffectiveConfig)
}
if err := ctx.Err(); err != nil {
return nil, cancelOutput(err)
}
return result, nil
}
// SelectionError indicates that resolved operator settings cannot be used for processing. // SelectionError indicates that resolved operator settings cannot be used for processing.
type SelectionError struct{ Cause error } type SelectionError struct{ Cause error }

View File

@@ -1,48 +0,0 @@
package preflight
import (
"context"
"os"
"path/filepath"
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/diagnostics"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
)
func TestReadinessAndCollisionPrecedeOutputPreparation(t *testing.T) {
dir := t.TempDir()
output := filepath.Join(dir, "output.json")
if _, err := Prepare(context.Background(), Input{Config: &config.Config{}, Output: diagnostics.OutputSelection{TranscriptPath: output}}); err == nil {
t.Fatal("missing transcript accepted")
}
if _, err := os.Stat(output); !os.IsNotExist(err) {
t.Fatalf("output created: %v", err)
}
if _, err := Prepare(context.Background(), Input{Config: &config.Config{}, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output, ProtectedPaths: []string{output}}}); err == nil {
t.Fatal("collision accepted")
}
entries, err := os.ReadDir(dir)
if err != nil || len(entries) != 0 {
t.Fatalf("prepared before check: %v %v", entries, err)
}
}
func TestOptionalDebugFailureDoesNotPreventPreparation(t *testing.T) {
dir := t.TempDir()
blocked := filepath.Join(dir, "file")
if err := os.WriteFile(blocked, []byte("x"), 0600); err != nil {
t.Fatal(err)
}
result, err := Prepare(context.Background(), Input{Config: &config.Config{}, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: filepath.Join(dir, "output")}, Debug: &DebugInput{WorkDir: blocked, RunID: "run"}})
if err != nil {
t.Fatal(err)
}
if len(result.Warnings) == 0 || result.Debug != nil {
t.Fatalf("debug=%v warnings=%v", result.Debug, result.Warnings)
}
if err := result.Output.Close(); err != nil {
t.Fatal(err)
}
}

View File

@@ -4,35 +4,28 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"os"
"path/filepath"
"slices" "slices"
"strings" "strings"
"testing" "testing"
"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/diagnostics"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
) )
func TestLaterEmptyGlossaryFailsBeforeOutputPreparation(t *testing.T) { func TestLaterEmptyGlossaryFailsBeforeProfileInspection(t *testing.T) {
profile, id := "selected", "spells" profile, id := "selected", "spells"
cfg := &config.Config{Pipeline: config.Pipeline{Stages: []config.Stage{ cfg := &config.Config{Pipeline: config.Pipeline{Stages: []config.Stage{
{Module: "grammar", LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}, {Module: "grammar", LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}},
{Module: "glossary", ID: &id, Glossaries: []string{"empty"}, LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}}, {Module: "glossary", ID: &id, Glossaries: []string{"empty"}, LLM: config.LLM{ProposalProfile: &profile, ValidationProfile: &profile}},
}}} }}}
output := filepath.Join(t.TempDir(), "transcript.json")
calls := 0 calls := 0
_, err := Prepare(context.Background(), Input{Config: cfg, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output}, InspectProfile: func(context.Context, string) error { calls++; return nil }}) _, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{}, func(context.Context, string) error { calls++; return nil })
if err == nil || !strings.Contains(err.Error(), "stage 2") || !strings.Contains(err.Error(), "spells") || !strings.Contains(err.Error(), "empty") { if err == nil || !strings.Contains(err.Error(), "stage 2") || !strings.Contains(err.Error(), "spells") || !strings.Contains(err.Error(), "empty") {
t.Fatalf("unexpected error: %v", err) t.Fatalf("unexpected error: %v", err)
} }
if calls != 0 { if calls != 0 {
t.Fatal("inspected profiles before checking all glossary selections") t.Fatal("inspected profiles before checking all glossary selections")
} }
if _, err := os.Stat(output); !os.IsNotExist(err) {
t.Fatalf("output exists: %v", err)
}
} }
func TestEmptyPipelineNeedsNoProfile(t *testing.T) { func TestEmptyPipelineNeedsNoProfile(t *testing.T) {
@@ -54,14 +47,10 @@ func TestCorrectionRepairReadinessDependsOnBudget(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
cfg.Pipeline.Stages[0].LLM.CorrectionRepairAttempts = 1 cfg.Pipeline.Stages[0].LLM.CorrectionRepairAttempts = 1
output := filepath.Join(t.TempDir(), "transcript.json") _, err := BuildPlan(context.Background(), cfg, &schema.SourceTranscript{}, inspect)
_, err := Prepare(context.Background(), Input{Config: cfg, Transcript: &schema.SourceTranscript{}, Output: diagnostics.OutputSelection{TranscriptPath: output}, InspectProfile: inspect})
if err == nil || !strings.Contains(err.Error(), "correction repair") { if err == nil || !strings.Contains(err.Error(), "correction repair") {
t.Fatalf("readiness error: %v", err) t.Fatalf("readiness error: %v", err)
} }
if _, err := os.Stat(output); !os.IsNotExist(err) {
t.Fatalf("output exists: %v", err)
}
} }
func TestProcessingPlanReusesOnlyMatchingGlossaryViews(t *testing.T) { func TestProcessingPlanReusesOnlyMatchingGlossaryViews(t *testing.T) {
@@ -74,8 +63,8 @@ func TestProcessingPlanReusesOnlyMatchingGlossaryViews(t *testing.T) {
exempt.Module = "glossary" exempt.Module = "glossary"
cfg := &config.Config{ cfg := &config.Config{
GlossaryCollections: map[string]config.GlossaryCollection{ GlossaryCollections: map[string]config.GlossaryCollection{
"a": {Entries: []config.GlossaryEntry{{ID: "a", Name: "A"}}}, "a": {Instruction: "First instruction", Entries: []config.GlossaryEntry{{ID: "a", Name: "A"}}},
"b": {Entries: []config.GlossaryEntry{{ID: "b", Name: "B"}}}, "b": {Instruction: "Second instruction", Entries: []config.GlossaryEntry{{ID: "b", Name: "B"}}},
}, },
Pipeline: config.Pipeline{Stages: []config.Stage{item, item, reversed, exempt}}, Pipeline: config.Pipeline{Stages: []config.Stage{item, item, reversed, exempt}},
} }
@@ -93,6 +82,9 @@ func TestProcessingPlanReusesOnlyMatchingGlossaryViews(t *testing.T) {
plan[2].Glossary[0].ID != "b" || plan[3].GlossaryVariables.ProtectionJSON != "[]" { plan[2].Glossary[0].ID != "b" || plan[3].GlossaryVariables.ProtectionJSON != "[]" {
t.Fatalf("incorrect glossary reuse or exemptions: %+v", plan) t.Fatalf("incorrect glossary reuse or exemptions: %+v", plan)
} }
if !strings.Contains(plan[1].GlossaryVariables.InstructionsBlock, "First instruction") || strings.Index(plan[2].GlossaryVariables.InstructionsBlock, "Second instruction") > strings.Index(plan[2].GlossaryVariables.InstructionsBlock, "First instruction") {
t.Fatalf("instruction reuse/order: %+v", plan)
}
} }
func TestProcessingPlanPreservesFirstInspectionFailureAndCause(t *testing.T) { func TestProcessingPlanPreservesFirstInspectionFailureAndCause(t *testing.T) {

View File

@@ -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.

View File

@@ -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: &section, 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")
}
}

View File

@@ -8,10 +8,12 @@ import (
"strings" "strings"
"testing" "testing"
"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"
"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/preflight"
"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/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"
@@ -73,8 +75,8 @@ func TestFatalBatchRetainsEarlierDecisionsInLedger(t *testing.T) {
client := &interruptedValidationClient{cause: origin} client := &interruptedValidationClient{cause: origin}
cfg := config.Config{Chunking: config.Chunking{MaxSectionTokens: 8192, MinSectionTokens: 1}, Validation: config.Validation{MaxPromptTokens: 150}} cfg := config.Config{Chunking: config.Chunking{MaxSectionTokens: 8192, MinSectionTokens: 1}, Validation: config.Validation{MaxPromptTokens: 150}}
result, err := runner.New(partialModule{validator}).Run(context.Background(), runner.RunInput{ result, err := runner.New(partialModule{validator}).Run(context.Background(), runner.RunInput{
Config: &cfg, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "hello"}}}, Plan: &preflight.Plan{Sections: []chunking.Section{{Index: 0, StartSegmentID: 1, EndSegmentID: 1, Segments: []schema.Segment{{ID: 1, Text: "hello"}}}}, Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "hello"}}},
ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}, Evidence: &runner.EvidenceSelection{Reports: true, Debug: true}, Specs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", ValidationClient: client, Settings: config.Stage{Validation: cfg.Validation}}}}, Evidence: &runner.EvidenceSelection{Reports: true, Debug: true},
}) })
if !errors.Is(err, origin) || client.calls != 3 { if !errors.Is(err, origin) || client.calls != 3 {
t.Fatalf("fatal cause/calls: %v %d", err, client.calls) t.Fatalf("fatal cause/calls: %v %d", err, client.calls)

View File

@@ -3,6 +3,7 @@ package promptcontext
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/glossary" "gitea.maximumdirect.net/eric/audita/v4/internal/core/glossary"
) )
@@ -11,6 +12,22 @@ import (
type GlossaryVariables struct { type GlossaryVariables struct {
ContextJSON string ContextJSON string
ProtectionJSON string ProtectionJSON string
InstructionsBlock string
}
type GlossaryInstruction struct {
Collection string
Text string
}
func GlossaryInstructionsBlock(instructions []GlossaryInstruction) string {
var blocks []string
for _, instruction := range instructions {
if instruction.Text != "" {
blocks = append(blocks, instruction.Collection+":\n"+instruction.Text)
}
}
return strings.Join(blocks, "\n\n")
} }
func PrepareGlossaryVariables(entries []glossary.Entry, terms []glossary.Term) (GlossaryVariables, error) { func PrepareGlossaryVariables(entries []glossary.Entry, terms []glossary.Term) (GlossaryVariables, error) {

View File

@@ -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,16 +47,16 @@ 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)}, appconfig.Options{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
runtime, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport}) runtime, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
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)

View File

@@ -13,7 +13,6 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/stagename" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/stagename"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput" "gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
) )
@@ -86,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},

View File

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

View File

@@ -35,6 +35,7 @@ func ExecuteModuleProposal(ctx context.Context, req ModuleProposalRequest) (cont
if err != nil { if err != nil {
return contracts.ProposalResult{}, err return contracts.ProposalResult{}, err
} }
prepared.InstructionsBlock = promptcontext.GlossaryInstructionsBlock(req.ProposalRequest.RunSpec.GlossaryInstructions)
glossary = &prepared glossary = &prepared
} }
variables, err := buildProposalVariables( variables, err := buildProposalVariables(

Some files were not shown because too many files have changed in this diff Show More