Compare commits
90 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f97f31ccb | |||
| 0e565b3abf | |||
| fb612b361d | |||
| e72f69c68b | |||
| c15204bdc7 | |||
| 8699ec442a | |||
| 00a3628451 | |||
| 9af2c146f1 | |||
| 3b7baed65e | |||
| 04546acee0 | |||
| 994cba3ba2 | |||
| ff4f98d2f7 | |||
| 009373130c | |||
| 3e287503eb | |||
| c0d2280305 | |||
| 38c5f3c290 | |||
| 1ded570158 | |||
| 7ee50d1a3f | |||
| 4543d66e21 | |||
| 5a842f6a7f | |||
| 0b9c7912c2 | |||
| 4c2b11aa45 | |||
| 973b24e466 | |||
| cbb2f768be | |||
| b96eeb57ba | |||
| f5cef61bb5 | |||
| 7ba1846e63 | |||
| 2eae2a4af2 | |||
| bed9424329 | |||
| 330044b207 | |||
| 7874ea648b | |||
| a9ab8e59b3 | |||
| a0292a3ba0 | |||
| a980fbbb09 | |||
| b4bc5e5640 | |||
| 2dc057b97e | |||
| e761512c1c | |||
| bd3a22754a | |||
| 645931c5e3 | |||
| 604ae631b3 | |||
| 9dadd97ee6 | |||
| be2846847b | |||
| 8411a69187 | |||
| 33d9e0428d | |||
| 1ebf39bd6f | |||
| 51cb6b2059 | |||
| 4b1812995f | |||
| bf3184cf0a | |||
| 889ac766a5 | |||
| e0445abe48 | |||
| 20db09bd2a | |||
| 39087675e1 | |||
| a4b8fd0976 | |||
| b1cde637a2 | |||
| d2c4c63580 | |||
| f85a07c14d | |||
| 3a5ea78b80 | |||
| 178b0cfa9c | |||
| 892cff8088 | |||
| bdeac85e8e | |||
| c554eecaec | |||
| 59f353348b | |||
| ac47c239c2 | |||
| fed190cc97 | |||
| d25d7fa7d4 | |||
| deec32cd4c | |||
| a020d155f4 | |||
| ca06f7c4e3 | |||
| 338e93a7eb | |||
| 58ff21e4df | |||
| 752ec676a6 | |||
| fa5d834f13 | |||
| c477bcc388 | |||
| c167a5e5ab | |||
| 6ca5f89356 | |||
| 9977cd9130 | |||
| 1ca5011049 | |||
| f87c45331c | |||
| 82c52c8e7f | |||
| 12fd2fba6b | |||
| f13db066f2 | |||
| e144c502f6 | |||
| 4dc461f9c9 | |||
| 60a80381a9 | |||
| 231b4c8a14 | |||
| e0471af25a | |||
| 187600eed2 | |||
| 11f45c8812 | |||
| a301ad1f27 | |||
| 92162ba9a6 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -47,6 +47,7 @@ pipeline.yml
|
||||
bin/
|
||||
|
||||
# Local run artifacts
|
||||
.releasekit/
|
||||
.audita-runs/
|
||||
report.json
|
||||
corrected.json
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
type repairWireMessage struct {
|
||||
@@ -115,7 +116,7 @@ func (p *correctionProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
raw, _ := json.Marshal(content)
|
||||
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) {
|
||||
@@ -190,7 +191,7 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
||||
provider.mu.Lock()
|
||||
provider.decimalReferences = tc.decimalReferences
|
||||
provider.mu.Unlock()
|
||||
args := []string{"--verbose"}
|
||||
args := []string{"--verbose", "--show-tokens"}
|
||||
if tc.debug {
|
||||
args = append(args, "--debug")
|
||||
}
|
||||
@@ -222,6 +223,9 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
||||
provider.mu.Lock()
|
||||
requests := append([]repairWireRequest(nil), provider.requests...)
|
||||
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 branches [][]repairWireMessage
|
||||
for _, req := range requests {
|
||||
@@ -271,13 +275,13 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
|
||||
}
|
||||
var execution struct {
|
||||
Summary struct {
|
||||
ProviderAttempts int `json:"provider_attempts"`
|
||||
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||
} `json:"summary"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &execution); err != nil {
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -336,7 +340,7 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
|
||||
f, provider := setupCorrectionFixture(t, 2, false, true)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
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.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1")
|
||||
var stderr bytes.Buffer
|
||||
@@ -356,6 +360,12 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
|
||||
if ctx.Err() != nil || err == nil {
|
||||
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) {
|
||||
t.Fatalf("transcript published: %v", err)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -24,6 +26,8 @@ import (
|
||||
"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/schema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
@@ -195,7 +199,7 @@ func (p *fixtureProvider) serve(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
encoded, _ := json.Marshal(content)
|
||||
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.
|
||||
@@ -261,6 +265,25 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
|
||||
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
|
||||
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
|
||||
for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") {
|
||||
if name = strings.TrimSpace(name); name != "" {
|
||||
@@ -271,7 +294,7 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
|
||||
if len(stageList) != 0 {
|
||||
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-") {
|
||||
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()
|
||||
}
|
||||
|
||||
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 {
|
||||
t.Helper()
|
||||
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 {
|
||||
Calls []struct {
|
||||
Summary struct {
|
||||
ProviderAttempts int `json:"provider_attempts"`
|
||||
StructuralRepairs int `json:"structural_repairs"`
|
||||
} `json:"summary"`
|
||||
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||
} `json:"calls"`
|
||||
}
|
||||
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())
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -492,10 +560,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in
|
||||
}
|
||||
var execution struct {
|
||||
Calls []struct {
|
||||
Summary struct {
|
||||
ProviderAttempts int `json:"provider_attempts"`
|
||||
StructuralRepairs int `json:"structural_repairs"`
|
||||
} `json:"summary"`
|
||||
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||
} `json:"calls"`
|
||||
}
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1213,8 +1278,10 @@ func TestSubprocessInfeasibleSectionTargetIsAnInputFailure(t *testing.T) {
|
||||
if _, err := os.Stat(f.output); !os.IsNotExist(err) {
|
||||
t.Fatalf("unexpected transcript output: %v", err)
|
||||
}
|
||||
if document := f.errors(t); document.Status != reporting.StatusFailed {
|
||||
t.Fatalf("report status: %+v", document)
|
||||
for _, name := range []string{"errors.yml", "recoveries.yml", "report.md"} {
|
||||
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", "[]")
|
||||
// PromptKit uses profile IDs, not filename stems. A report-named profile is
|
||||
// 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)
|
||||
}
|
||||
loaded := filepath.Join(f.dir, "prompts", "errors.yml")
|
||||
|
||||
62
docs/cli.md
62
docs/cli.md
@@ -3,7 +3,7 @@
|
||||
Audita uses CommandKit for routing and the ConfigKit and PromptKit integrations
|
||||
for their standard inspection and request commands. Run `audita --help` or
|
||||
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,
|
||||
validation, smoke tests, and their provider-specific caveats. Help and version
|
||||
do not load application or model configuration.
|
||||
@@ -14,12 +14,21 @@ do not load application or model configuration.
|
||||
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.
|
||||
`--output` writes the transcript to a file; omission selects stdout. The shared
|
||||
`--debug` flag enables retained debug artifacts, and `--quiet` suppresses optional
|
||||
messages. Quiet processing requires an output file or `/dev/null`. See
|
||||
[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
|
||||
chunk activity, model proposal, validation and repair operations, and observed
|
||||
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
|
||||
and inheritance.
|
||||
|
||||
`--glossary-file PATH` supplies a shared glossary YAML or JSON 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
|
||||
|
||||
The application configuration scope uses ConfigKit's native effective values,
|
||||
source evidence, explanation, comparison, and redaction. PromptKit supplies its
|
||||
own configuration and resource scopes and request preparation, validation, and
|
||||
explicit smoke diagnostics. Inspection does not require a processing-ready
|
||||
pipeline or contact a provider. Processing preflight separately checks the selected
|
||||
profiles and glossary entries. Smoke tests can contact providers and are run
|
||||
only on explicit request.
|
||||
pipeline or contact a provider. Processing and standalone preflight separately
|
||||
check selected profiles and glossary entries. Native PromptKit smoke commands
|
||||
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
|
||||
reports may record recoverable model failures even when processing completes.
|
||||
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
|
||||
processing profile or required glossary selection is an input failure. See the
|
||||
or input, and native comparison may return `3` for differences. ConfigKit
|
||||
classifies native configuration diagnostics; unclassified runtime preparation
|
||||
and bootstrap failures, and cancellation, are operational. A missing
|
||||
processing profile, 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).
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# Audita Configuration
|
||||
|
||||
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).
|
||||
|
||||
## Loading and composition
|
||||
@@ -14,26 +15,73 @@ not continue after a selected file fails. An omitted version uses the v3 schema;
|
||||
a supplied version must be `3`.
|
||||
|
||||
Operator sources may use ConfigKit imports. The selected main file provides the
|
||||
base for an optional `overlays/<name>.yml`, optional `glossary.yml`, and recursive
|
||||
`glossary/` YAML files. Without a main source, automatic companion files are not
|
||||
loaded from the working directory. ConfigKit composes sources, resolves native
|
||||
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)
|
||||
base for an optional `overlays/<name>.yml` and automatic prompt companions.
|
||||
Without a main source, automatic companions are not loaded from the working
|
||||
directory. ConfigKit composes sources, resolves native inheritance, applies
|
||||
explicit overrides, records derived defaults, and validates 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.
|
||||
|
||||
Explicit `--glossary-file` inputs use the shared `glossary@0.2.0` contract from
|
||||
schemas distribution `2026.11.1` and the `maximumdirect.glossary.v1` marker.
|
||||
The files are ordered native layers; imports within a file are native peers and
|
||||
resolve beside their declaring file. Audita validates the completed envelope,
|
||||
then projects collection entries through native CLI assignments to
|
||||
`glossary_collections`. When other CLI overrides target that namespace, file
|
||||
assignments are scoped to their supplied entry lists so disjoint overrides can
|
||||
coexist. An empty collection map adds no assignment. Native override budgets and
|
||||
genuine overlap checks still apply. Supplied entry lists replace configured lists
|
||||
at that boundary; unrelated configured collections remain. ConfigKit governs native
|
||||
composition and assignment. Final explanation records the CLI assignment;
|
||||
runtime files and imports remain recorded for collision protection. See the
|
||||
[shared file contract](integrations/transcript-glossary-files.md#glossary-collections).
|
||||
|
||||
Audita does not automatically discover `glossary.yml` or files under `glossary/`.
|
||||
Pass desired files explicitly. An extension named `instruction` in a shared
|
||||
collection is data and is not application instruction guidance. Inline application
|
||||
`glossary_collections` may still define `instruction`.
|
||||
|
||||
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 loads its default catalog and Audita's embedded prompts, followed by
|
||||
optional `prompts.yml` and recursive `prompts/` YAML files beside the application
|
||||
main. Native imports, resource collections, inheritance, and replacement apply.
|
||||
The combined result contains native PromptKit settings under `/promptkit`.
|
||||
Audita combines the bundled OpenRouter catalog and its embedded prompts and
|
||||
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
|
||||
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
|
||||
invocation to pick up changes. Inspection does not require model credentials.
|
||||
|
||||
## 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
|
||||
`plural` provide optional context. Entries are identified within their collection
|
||||
by `id`. Root `glossaries` and `protected_terms` select collection names. If root
|
||||
@@ -74,7 +122,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_attempts` | `1` | Nonnegative repair attempts per correction; zero disables correction repair. |
|
||||
| `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. |
|
||||
| `validation.max_prompt_tokens` | `2048` | Positive validation batching budget. |
|
||||
| `context.description` | empty | Prompt context; at most 500 bytes after trimming. |
|
||||
|
||||
@@ -1,34 +1,22 @@
|
||||
# OpenAI-Compatible LLM Integration
|
||||
|
||||
Audita uses the pinned [PromptKit](https://forge.maximumdirect.net/base-layer/promptkit/src/commit/171fb11f4e967a1da3af57843c6467954b14ba09)
|
||||
built-in OpenAI-compatible transport. PromptKit owns chat-completions wire framing,
|
||||
provider envelope parsing, transient retries, per-generation timeouts, and JSON
|
||||
Schema repair. A backend's configured base endpoint must support the selected
|
||||
profile's model and structured JSON-schema responses; local configuration
|
||||
inspection does not contact the provider.
|
||||
Audita uses [PromptKit v0.25.0](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/integrations/openai-compatible-chat.md)
|
||||
for its OpenAI-compatible transport, provider conventions, credentials, retries,
|
||||
admission, and observed token and cost information. Inspection prepares requests
|
||||
without contacting a provider or requiring model credentials.
|
||||
|
||||
Audita selects role profiles independently for each pipeline entry and supplies
|
||||
its domain response schema and per-operation budget. PromptKit owns backend and
|
||||
credential selection, request preparation, transport, retries, repairs, and
|
||||
admission. Audita executes the same prepared handle and retains its own domain
|
||||
validation. Profiles may use native endpoint and credential settings; local
|
||||
inspection does not resolve a credential value or call the provider.
|
||||
Audita selects a profile for each proposal, validation, and correction-repair
|
||||
role. The selected prompt supplies the output contract and structural-repair
|
||||
budget, while Audita retains its operation timeout, transient retry selection,
|
||||
semantic correction-repair budget, and domain checks. Operator prompt contracts
|
||||
must produce the response shapes expected by Audita. See [configuration](../config.md)
|
||||
and the [migration guide](../migrations/v4.1.md).
|
||||
|
||||
`llm.transient_retries` counts additional attempts for eligible transient
|
||||
failures; explicit zero makes one attempt. `llm.repair_attempts` counts
|
||||
additional generations for schema-invalid model output. The operation timeout
|
||||
covers preparation, capacity waiting, retries, generation, and repair. Caller
|
||||
cancellation or an earlier deadline also applies. See [configuration](../config.md#settings)
|
||||
for defaults and the [PromptKit consumer contract](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.23.0/docs/consumers/pkg-promptkit.md)
|
||||
for protocol and retry details.
|
||||
|
||||
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).
|
||||
Exhausted structural validation, an incompatible response JSON, a live-parent
|
||||
operation timeout, capacity rejection, transport failure, malformed provider
|
||||
response, or provider HTTP failure is recoverable for the affected operation.
|
||||
Proposal generation contributes no candidates from a failed response; a failed
|
||||
validation batch makes its candidates unavailable while independent work can
|
||||
continue. Caller cancellation, broken assets or configuration, and internal
|
||||
programming failures remain fatal. Ordinary reports use safe reason codes and
|
||||
counts. Full interaction content is optional [debug evidence](../operations.md#debug-evidence).
|
||||
|
||||
@@ -105,7 +105,9 @@ transcript excerpts or correction lists.
|
||||
|
||||
With `--debug`, `correction-ledger.json` contains proposed candidates and
|
||||
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
|
||||
`stage_index` and optional `stage_id` where an entry is identified.
|
||||
These files are diagnostic evidence, not an alternate ordinary report schema.
|
||||
|
||||
@@ -15,11 +15,20 @@ directory. For stdout output, reports use the effective `reporting.stdout_dir`
|
||||
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
|
||||
`--debug` enables capture; the path flag alone does not.
|
||||
Supplying a configuration path also makes file selection predictable; only
|
||||
explicitly referenced credential variables are read from the environment.
|
||||
Supplying a configuration path also makes file selection predictable. Configured
|
||||
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 shared glossary 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
|
||||
its configured imports and automatic overlay, glossary, and prompt companions.
|
||||
its configured imports, selected overlay, and automatic prompt companions.
|
||||
Without a main path, Audita uses the configured discovery locations. The
|
||||
parent controls who can write those sources and which report destinations and
|
||||
retained debug directories the invocation will use. Native inspection is
|
||||
@@ -34,14 +43,30 @@ operations and completions. Debug enables progress by default, and
|
||||
`--progress=false` or quiet mode suppresses it. Consume progress as
|
||||
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
|
||||
|
||||
Interpret the exit result according to the
|
||||
[CLI output and exit contract](../cli.md#inspection-and-outcomes).
|
||||
Consume transcript/report data through the
|
||||
[output-file contract](output-files.md), and treat stderr as human-readable detail.
|
||||
Audita loads configuration and parses the input transcript before report
|
||||
initialization. Early destination failures can also leave no reports. After
|
||||
Audita loads configuration, parses and normalizes the transcript, and plans
|
||||
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
|
||||
failures and use the same report directory as successful runs.
|
||||
Exit `0` can include recoverable model errors and applied
|
||||
|
||||
@@ -30,9 +30,36 @@ types, duplicate supplied IDs, and the validation failures above are rejected.
|
||||
|
||||
## Glossary collections
|
||||
|
||||
Glossary definitions are composed as application configuration, including the
|
||||
optional companion inputs described by the [configuration reference](../config.md).
|
||||
The [local example](../../examples/local/glossary.yml) provides a complete
|
||||
collection. Configuration may contain empty collections; processing preflight
|
||||
requires every glossary-correction entry to select at least one glossary entry.
|
||||
The previous standalone `glossary` file format is not a processing input.
|
||||
Runtime glossary files supplied with `--glossary-file PATH` use the shared
|
||||
`glossary@0.2.0` contract from schemas distribution `2026.11.1`, with marker
|
||||
`maximumdirect.glossary.v1`. Audita bundles the selected schema and validates
|
||||
completed inputs offline. The upstream [schema](https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json)
|
||||
and [semantics](https://schemas.maximumdirect.net/glossary/v0.2.0/semantics.md)
|
||||
define its fields and extensions. Full conformance includes the
|
||||
[ConfigKit v1.4.0 loading boundary](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md).
|
||||
|
||||
```yaml
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
people:
|
||||
entries:
|
||||
- id: speaker
|
||||
name: Mira Chen
|
||||
category: person
|
||||
aliases: [Mira]
|
||||
```
|
||||
|
||||
Each path is relative to the invocation working directory. A file can hold one
|
||||
or many collections; repeated flags compose files in order. Native imports are
|
||||
resolved relative to their declaring file, and imported fragments can contribute
|
||||
to a completed envelope. All selected and imported paths are protected from
|
||||
output collisions. Loading does not select collections. Configure selections or
|
||||
use the CLI selection flags; empty collections are valid for inspection, while
|
||||
glossary correction needs at least one selected entry.
|
||||
|
||||
Audita no longer automatically loads `glossary.yml` or files in `glossary/`;
|
||||
pass those paths explicitly if needed. Automatic prompt companions remain.
|
||||
Collection extensions, including `instruction`, are data and do not become
|
||||
prompt guidance. See [configuration and composition](../config.md#loading-and-composition),
|
||||
[examples](../../examples/README.md#runtime-glossary-input), and the
|
||||
[v4.3 migration guide](../migrations/v4.3.md).
|
||||
|
||||
@@ -6,7 +6,8 @@ CLI wiring, and maintained examples. Definitions of behavior belong to the
|
||||
|
||||
## 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
|
||||
applicable. Preserve the precedence defined in the
|
||||
[configuration contract](../config.md#loading-and-composition), including the
|
||||
@@ -32,12 +33,26 @@ the [CLI contract](../cli.md) when changing the command; the
|
||||
adoption decision is recorded in [ADR 0001](../adr/0001-releasekit.md).
|
||||
|
||||
Processing preflight checks glossary selections before inspecting proposal,
|
||||
validation, and enabled repair profiles in pipeline order. The checked plan
|
||||
carries the resolved module specs and glossary views into execution. It reuses
|
||||
validation, and enabled repair profiles in pipeline order. The local plan
|
||||
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
|
||||
invocation. Native inspection commands continue to inspect configuration
|
||||
without running processing readiness checks.
|
||||
|
||||
Explicit shared glossary files use a preliminary ConfigKit load with ordered
|
||||
layers, native imports, and entry identities. The shared-glossary adapter
|
||||
validates the completed envelope against the bundled offline schema before
|
||||
projecting entries into the application load. Entry assignments share the
|
||||
glossary namespace with disjoint caller overrides; ordinary loads retain a
|
||||
single batch contribution to avoid consuming a native override record per
|
||||
collection, and empty maps contribute no override. Processing retains acquired
|
||||
source paths for output collision checks; inspection receives the final native
|
||||
result and CLI origin. Both sides of comparison use the same invocation file list.
|
||||
Automatic prompt companions remain; glossary companions are not discovered.
|
||||
|
||||
## Validating Examples
|
||||
|
||||
Keep complete copyable files in [examples](../../examples/) and link to them from
|
||||
@@ -45,7 +60,7 @@ their canonical contract documentation. Keep them valid and secret-free.
|
||||
Run the commands in the [example guide](../../examples/README.md) from each
|
||||
project's directory. `internal/cli/examples_integration_test.go` exercises the
|
||||
maintained projects with a controlled provider, and the preview fixture can be
|
||||
prepared without inference. Review automatic companion sources and overlays in
|
||||
prepared without inference. Review automatic prompt sources and overlays in
|
||||
their actual project directories. Keep service credentials synthetic in tests.
|
||||
|
||||
## Runtime Change Checks
|
||||
|
||||
@@ -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
|
||||
retain their execution counts and never produce a recovery record.
|
||||
|
||||
`internal/core/diagnostics.OutputSession` owns destination selection, report
|
||||
initialization, and publication. Transcript and report files share a staging
|
||||
`internal/core/diagnostics` checks destinations without opening resources and
|
||||
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
|
||||
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
|
||||
files and supplies those source paths to CLI;
|
||||
no second filename-based discovery rule is used.
|
||||
CLI composes it after configuration, transcript acquisition, and preflight
|
||||
readiness and before dispatching model work. It does not create ordinary report parents.
|
||||
CLI constructs it after local plan and destination checks and before dispatching
|
||||
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.
|
||||
When another failure becomes known, later writes use updated failed reports.
|
||||
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
|
||||
artifact path coordinates.
|
||||
|
||||
Execution diagnostics include a native-group invocation summary and per-call
|
||||
summaries. Terminal coverage is separate from usage completeness; unknown usage
|
||||
is distinct from known zero. Overlapping summaries must not be added together.
|
||||
Execution diagnostics put native group evidence under `promptkit` in the
|
||||
invocation summary and each logical call, and native events under `promptkit`
|
||||
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
|
||||
presentation order. Prepared evidence comes from `OnPrepared`, so preparation or
|
||||
admission failures may have no request snapshot. Coordinator execution failures
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
# Audita LLM Runtime
|
||||
|
||||
`llm.NewRuntime` assembles one captured PromptKit engine using its default
|
||||
catalog, Audita's embedded prompts and schemas, and optional operator sources
|
||||
anchored to the recorded application main context. Captured host sources and
|
||||
message files are passed to output collision checks. An embedded-only diagnostic
|
||||
construction distinguishes shipped asset failures from operator-source failures;
|
||||
it never replaces the requested engine.
|
||||
`internal/appconfig` assembles one shared result and bootstraps configured
|
||||
secrets before loading. `llm.NewRuntime` captures a PromptKit engine from that
|
||||
result. Effective host sources and message files are passed to output collision
|
||||
checks. Native errors and source evidence are retained for classification.
|
||||
|
||||
Each resolved pipeline entry receives role-bound clients with its selected
|
||||
profiles and effective budgets. Clients share engine-local backend admission.
|
||||
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
|
||||
repair. An expired parent context stops processing and retains any native cause.
|
||||
With an active parent, PromptKit's operation deadline remains recoverable even
|
||||
when a preparation error wraps it. A native transport timeout affects the HTTP
|
||||
attempt and is recorded as a transport failure. The prepared notification
|
||||
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,
|
||||
the CLI identifies the role, profile, and environment variable using the native
|
||||
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
|
||||
`Engine.Coordinate` branch from that exchange. PromptKit assembles continuation
|
||||
history, owns the additional-turn budget, and delivers the last permitted response
|
||||
for assessment. Follow-ups select the repair prompt, profile, and output schema
|
||||
directly; Audita does not rerender the original proposal or assemble replay messages.
|
||||
for assessment. Follow-ups select the repair prompt and profile; the prompt owns
|
||||
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
|
||||
modules and validators. The adapter shares request construction, notifications,
|
||||
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;
|
||||
see [prompt instruction ownership](prompts.md).
|
||||
|
||||
The observation collector tracks logical calls and execution events, and enrolls
|
||||
selected runs in a native `ExecutionGroup`. Proposal, repair, and nested validator
|
||||
clients explicitly share the invocation observer; history reuse adds no extra run.
|
||||
Native summaries deduplicate terminal totals by run ID and retain terminal coverage
|
||||
separately from usage presence and completeness. Logical calls and run membership
|
||||
can differ, especially on failures before execution.
|
||||
The optional debug collector tracks logical calls and native execution events,
|
||||
and replays selected events into a native `ExecutionGroup`. The invocation
|
||||
context also carries ckprompt's optional usage observer through proposal, repair,
|
||||
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)
|
||||
for native observation and aggregation semantics.
|
||||
|
||||
Processing operations retain the failure class, reason, and underlying error.
|
||||
When a client omits the reason, the operation uses `internal_failure` and keeps
|
||||
|
||||
@@ -45,8 +45,8 @@ Module packages own:
|
||||
|
||||
Each stage prepares the encoded glossary context and protected spellings once.
|
||||
Proposal generation adds the selected transcript section and trimmed description
|
||||
for each request. PromptKit renders the selected definition and validates the
|
||||
correction-set schema before Audita maps proposals. Domain validators still
|
||||
for each request. PromptKit renders the selected definition and applies its
|
||||
output contract before Audita decodes and maps proposals. Domain validators still
|
||||
check applicability, protected glossary terms, and replacement
|
||||
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
|
||||
|
||||
@@ -11,6 +11,7 @@ baseline commands, see the [contributor guide](../development.md).
|
||||
Executable and command orchestration:
|
||||
- `cmd/audita`: executable entry point.
|
||||
- `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:
|
||||
- `internal/core/config`
|
||||
@@ -58,16 +59,17 @@ These are current implementation boundaries, not bans on future work.
|
||||
|
||||
## Main Execution Path (`audita process`)
|
||||
|
||||
The CLI inspects configuration and profiles, preflights and initializes active
|
||||
outputs, optionally creates debug evidence, invokes the runner, and finalizes
|
||||
transcript and reports.
|
||||
The CLI prepares an invocation-local plan and checked destinations, initializes
|
||||
active outputs, optionally creates debug evidence, invokes the runner, and
|
||||
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
|
||||
[operations guide](../operations.md) owns the operator workflow and physical
|
||||
artifact lifecycle.
|
||||
|
||||
## 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,
|
||||
diagnostics artifact helpers, and public report structures.
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@ The [input contract](../integrations/transcript-glossary-files.md) owns input
|
||||
formats; [configuration](../config.md) owns settings; the
|
||||
[output contract](../integrations/output-files.md) owns serialized results.
|
||||
|
||||
1. CLI loads resolved configuration and transcript input. Preflight checks all
|
||||
selected glossary views and roles before the output session prepares resources.
|
||||
Transcript segments then enter canonical normalization.
|
||||
1. CLI acquires configuration and transcript input. `framework/preflight` checks
|
||||
selected glossary views and roles, normalizes the canonical transcript, and
|
||||
returns an invocation-local plan with fixed sections and ordered profile IDs.
|
||||
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
|
||||
estimate as chunking, then reassigns IDs where needed.
|
||||
3. The runner partitions the normalized transcript exactly once before its
|
||||
module loop. Initial section identity, segment membership, and token
|
||||
3. The core chunker partitions the normalized transcript during preparation.
|
||||
The runner consumes those sections: initial identity, membership, and token
|
||||
estimates stay fixed while text evolves.
|
||||
4. Module instances execute in configured order. Each section hands its decoded
|
||||
proposals and original local segment references to the runner along with
|
||||
@@ -64,3 +64,9 @@ for invariants.
|
||||
Key tests: `internal/framework/runner/*_test.go`,
|
||||
`internal/framework/validators/*_test.go`, and
|
||||
`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.
|
||||
|
||||
@@ -13,8 +13,8 @@ PromptKit composes embedded defaults with operator prompt sources. Shared
|
||||
instructions come from the embedded fragments in `assets/shared`; the request
|
||||
shared-variable helper fills absent `HardeningPolicy`, `ProposalContract`,
|
||||
`RepairContract`, and `ValidationContract` variables. The processing adapter
|
||||
supplies the embedded instruction fragments for those names. Processing supplies
|
||||
Audita's response-schema contract separately.
|
||||
supplies the embedded instruction fragments for those names. Each prompt owns
|
||||
its output contract and references the shared embedded schema assets.
|
||||
The operator's prompt definition controls which variables its template uses.
|
||||
|
||||
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
|
||||
and supply the template variables used by the selected prompt. The shipped
|
||||
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
|
||||
spelling list to `[]` when omitted. The validator definitions use `TranscriptDescriptionBlock` and
|
||||
`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
|
||||
retains its findings and available source text. An operator replacement may use
|
||||
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.
|
||||
|
||||
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
|
||||
`correction_set.v1.json`, `correction_repair.v1.json`, and
|
||||
`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
|
||||
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 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
|
||||
[LLM runtime](llm-runtime.md) for runtime assembly and
|
||||
[configuration](../config.md) for operator-selected profiles.
|
||||
|
||||
@@ -71,14 +71,14 @@ LLM validators:
|
||||
- build canonical validation request payloads;
|
||||
- batch using `validation.max_prompt_tokens` and the existing domain token estimator;
|
||||
- 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
|
||||
`validation_input_too_large` operation, without a provider call. Recoverable
|
||||
model failures make only their batch candidates unavailable while other
|
||||
batches continue. PromptKit validates each complete response against the
|
||||
validator-decision JSON Schema and performs configured structural repair before
|
||||
Audita receives decoded decisions. Each actual batch presents candidates
|
||||
batches continue. PromptKit applies the selected prompt's output contract before
|
||||
Audita decodes decisions. Shipped validator prompts select the validator-decision
|
||||
JSON Schema. Each actual batch presents candidates
|
||||
numbered from 1, independent of their internal proposal indices. Audita then
|
||||
reconciles those local references: one usable entry keeps its
|
||||
approval or editorial rejection; a missing or duplicate requested entry makes
|
||||
|
||||
65
docs/migrations/v4.1.md
Normal file
65
docs/migrations/v4.1.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Migrating to Audita v4.1
|
||||
|
||||
Audita v4.1 keeps application configuration version `3` and accepts existing
|
||||
wrapperless `prompts.yml` and `prompts/` companions. It changes how structural
|
||||
output contracts, configuration loading, inspection, and debug evidence work.
|
||||
Review the following changes before upgrading scripts or operator prompts.
|
||||
|
||||
## Move structural-repair budgets to prompts
|
||||
|
||||
Remove `llm.repair_attempts` from the root and every pipeline entry. Audita no
|
||||
longer accepts that setting or supplies an output contract at each call. The
|
||||
selected PromptKit prompt now owns its `output` format, validation mode, schema,
|
||||
and structural-repair budget. Shipped definitions omit `output.repair_attempts`;
|
||||
the PromptKit v0.25.0 default for enabled validation is one additional generation,
|
||||
where Audita previously defaulted to two. Set an explicit budget in a complete
|
||||
replacement prompt when needed; zero disables structural repair for that prompt.
|
||||
This is separate from Audita's `llm.correction_repair_attempts`, which controls
|
||||
semantic correction repair, and from transient retries.
|
||||
|
||||
For a working replacement with `output.repair_attempts: 2`, see
|
||||
[`examples/prompt-edit/prompts.yml`](../../examples/prompt-edit/prompts.yml).
|
||||
The example retains the complete grammar proposal definition, including its
|
||||
messages, format, validation mode, and schema path. A same-ID replacement is a
|
||||
whole record, not a field patch. Former per-entry budgets have no automatic
|
||||
one-to-one conversion: select or define prompts with budgets appropriate to each
|
||||
use. See the [PromptKit format reference](https://forge.maximumdirect.net/base-layer/promptkit/src/tag/v0.25.0/docs/formats.md)
|
||||
for prompt contracts and the [Audita prompt guide](../internal/prompts.md) for
|
||||
required request variables and response shapes.
|
||||
|
||||
Audita no longer replaces an operator prompt's output contract with its own
|
||||
schema. Make operator proposal, validator, and repair prompts produce the
|
||||
appropriate Audita response shapes. Responses that pass a weaker contract but
|
||||
cannot be decoded into the expected JSON types become recoverable invalid-output
|
||||
failures for that operation; domain validation still applies.
|
||||
|
||||
## Update inspection and diagnostics consumers
|
||||
|
||||
The shared application configuration includes native settings under `/promptkit`.
|
||||
Use these paths when inspecting the application scope; the separate PromptKit
|
||||
scope remains available. Existing wrapperless companions are mounted at that
|
||||
path, while main files and overlays can use a `promptkit` section. Configuration
|
||||
inspection now validates the shared result and may run configured secrets
|
||||
bootstrap. See [configuration](../config.md#loading-and-composition).
|
||||
|
||||
Debug `llm-execution.json` retains `summary`, `calls`, and `events`, with native
|
||||
PromptKit evidence nested under `promptkit`. Prepared interaction request payloads
|
||||
also include native contract, schema, and message-hash evidence under that key.
|
||||
Update scripts that read the former projected metric fields; native field names
|
||||
and duration representations differ. Ordinary reports retain their schemas.
|
||||
Native smoke reports now default to text; scripts consuming structured output
|
||||
should request `--format yaml` or `--format json`. See the
|
||||
[CLI reference](../cli.md#inspection-and-outcomes) and
|
||||
[debug output contract](../integrations/output-files.md#debug-only-files).
|
||||
|
||||
## Review startup failures
|
||||
|
||||
Application and PromptKit resources now share configuration loading and
|
||||
validation. Invalid native configuration can be reported during application
|
||||
inspection as well as processing; native configuration usage errors are
|
||||
classified as status `2`, while unclassified runtime preparation and bootstrap
|
||||
failures are status `1`. A failed
|
||||
bootstrap occurs before transcript and output preparation. Help, version, and
|
||||
other help-only paths do not perform the load. See [subprocess integration](../integrations/subprocess.md)
|
||||
for handling results and [ConfigKit bootstrap documentation](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md)
|
||||
for the native controls.
|
||||
43
docs/migrations/v4.3.md
Normal file
43
docs/migrations/v4.3.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# Migrating to Audita v4.3
|
||||
|
||||
Audita v4.3.0 adopts the shared `glossary@0.2.0` contract from schemas
|
||||
distribution `2026.11.1`. Runtime glossary files now require the
|
||||
`maximumdirect.glossary.v1` marker and a `collections` mapping. The former
|
||||
wrapperless runtime format is no longer accepted. See the
|
||||
[shared input contract](../integrations/transcript-glossary-files.md#glossary-collections)
|
||||
and [upstream semantics](https://schemas.maximumdirect.net/glossary/v0.2.0/semantics.md).
|
||||
|
||||
```yaml
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
people:
|
||||
entries:
|
||||
- {id: speaker, name: Mira Chen, category: person}
|
||||
```
|
||||
|
||||
Pass files explicitly to every configuration-consuming invocation:
|
||||
|
||||
```sh
|
||||
audita preflight --smoke=false --config config.yml --glossary-file glossary.yml --output corrected.json transcript.json
|
||||
audita process --config config.yml --glossary-file party.yml --glossary-file spells.yml --output corrected.json transcript.json
|
||||
```
|
||||
|
||||
One file can contain multiple collections, or repeated arguments can supply
|
||||
separate files or a mixture. Paths are relative to the invocation directory;
|
||||
native imports are relative to their declaring file. Formerly discovered
|
||||
`glossary.yml` and `glossary/` files must now be named explicitly. Automatic
|
||||
prompt companions, inline application vocabulary, and main configuration
|
||||
discovery remain available.
|
||||
|
||||
Explicit files have CLI assignment priority over main and overlay vocabulary,
|
||||
whereas automatic glossary companions previously acted as an underlay. Supplied
|
||||
entry lists replace configured lists at that boundary; unrelated configured
|
||||
collections remain. Files compose as ordered native layers before the completed
|
||||
envelope is validated and projected. Inheritance and value presence follow the
|
||||
[ConfigKit reference](https://forge.maximumdirect.net/base-layer/configkit/src/tag/v1.4.0/docs/config.md),
|
||||
within the boundaries described in [configuration](../config.md#loading-and-composition).
|
||||
|
||||
Loading does not select collections. Keep root or per-pipeline selections, or
|
||||
supply the applicable CLI overrides. Empty collections can be inspected, but
|
||||
glossary correction requires a selected entry. Application configuration remains
|
||||
version 3 and the Go module path remains `/v4`.
|
||||
@@ -17,16 +17,39 @@ history to the selected repair provider. A provider rejection ends that branch
|
||||
as unavailable; other approved edits can still be applied. See
|
||||
[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
|
||||
|
||||
Treat the selected main file, imports, overlay, and automatically loaded
|
||||
glossary and prompt companions as one trusted bundle. Choose the working
|
||||
Treat the selected main file, imports, overlay, explicit glossary files, and
|
||||
automatically loaded prompt companions as one trusted bundle. Choose the working
|
||||
directory deliberately when using automatic discovery. A bundle can select
|
||||
the provider, prompt content, and local files consumed by processing. Review
|
||||
these sources before running with sensitive transcript data. Native inspection
|
||||
describes the loaded configuration and resources. Processing readiness also
|
||||
depends on the profiles and glossaries selected by the pipeline. See
|
||||
[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
|
||||
|
||||
@@ -38,7 +61,7 @@ requires a transcript file or `/dev/null`; it suppresses optional messages, not
|
||||
failures. Stdout carries transcript JSON when selected.
|
||||
|
||||
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
|
||||
output is prepared in a sibling temporary file, leaving the final destination
|
||||
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
|
||||
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
|
||||
transcript is published before final reports; the files do not form a single
|
||||
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.
|
||||
Debug mode enables live progress by default. Use `--progress=false` to keep
|
||||
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
|
||||
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
|
||||
Material: All documents under `docs/policy/`, root `AGENTS.md`, and the Policy
|
||||
Reading Guide in `docs/development.md`, adapted for this repository.
|
||||
`docs/policy/documentation.md`, `docs/policy/oss.md`, and `docs/policy/release.md`
|
||||
incorporate revision `593c9b52273c5c879785ae9e995d21026df467b4`.
|
||||
`docs/policy/documentation.md` incorporates revision
|
||||
`5b9088601290564647a9e20c13f95c0da9f4cb15`.
|
||||
`docs/policy/oss.md` and `docs/policy/release.md` incorporate revision
|
||||
`593c9b52273c5c879785ae9e995d21026df467b4`.
|
||||
The remaining listed material incorporates revision
|
||||
`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) |
|
||||
[LICENSE](https://gitea.maximumdirect.net/eric/policy/src/commit/d84a38ebab26f048cafbe59a2246700c35d29843/LICENSE) |
|
||||
[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/593c9b52273c5c879785ae9e995d21026df467b4).
|
||||
|
||||
[Source](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15).
|
||||
|
||||
## 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
|
||||
|
||||
@@ -33,9 +39,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3](licenses/LGPL-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
|
||||
|
||||
@@ -59,7 +65,7 @@ License and notices: [LGPL v3](licenses/LGPL-3.0.txt) |
|
||||
|
||||
## 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
|
||||
|
||||
@@ -67,13 +73,13 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3](licenses/LGPL-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
|
||||
|
||||
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
|
||||
|
||||
@@ -81,13 +87,13 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3](licenses/LGPL-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
|
||||
|
||||
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
|
||||
|
||||
@@ -95,9 +101,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3](licenses/LGPL-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
|
||||
|
||||
@@ -213,7 +219,7 @@ License and notices: [Apache 2.0](licenses/Apache-2.0.txt).
|
||||
|
||||
## 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
|
||||
|
||||
@@ -221,9 +227,9 @@ SPDX-License-Identifier: LGPL-3.0-or-later
|
||||
|
||||
License and notices: [LGPL v3](licenses/LGPL-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
|
||||
|
||||
@@ -252,3 +258,16 @@ License and notices: [BSD 3-Clause](licenses/BSD-3-Clause-Go.txt) |
|
||||
[LICENSE](https://github.com/spf13/pflag/blob/f8a990678a6d44385313e9b19e40737f889f9b14/LICENSE).
|
||||
|
||||
[Source](https://github.com/spf13/pflag/tree/f8a990678a6d44385313e9b19e40737f889f9b14).
|
||||
|
||||
## Maximum Direct shared schemas
|
||||
|
||||
Material: `glossary/v0.2.0/` from schemas distribution `2026.11.1`.
|
||||
|
||||
Copyright 2026 Eric Rakestraw
|
||||
|
||||
SPDX-License-Identifier: CC0-1.0
|
||||
|
||||
License and notices: [CC0 1.0](licenses/CC0-1.0.txt) |
|
||||
[COPYRIGHT](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/COPYRIGHT).
|
||||
|
||||
[Source](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7).
|
||||
|
||||
121
docs/oss/licenses/CC0-1.0.txt
Normal file
121
docs/oss/licenses/CC0-1.0.txt
Normal file
@@ -0,0 +1,121 @@
|
||||
Creative Commons Legal Code
|
||||
|
||||
CC0 1.0 Universal
|
||||
|
||||
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
||||
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
||||
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
||||
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
||||
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
||||
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
||||
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
||||
HEREUNDER.
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator
|
||||
and subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for
|
||||
the purpose of contributing to a commons of creative, cultural and
|
||||
scientific works ("Commons") that the public can reliably and without fear
|
||||
of later claims of infringement build upon, modify, incorporate in other
|
||||
works, reuse and redistribute as freely as possible in any form whatsoever
|
||||
and for any purposes, including without limitation commercial purposes.
|
||||
These owners may contribute to the Commons to promote the ideal of a free
|
||||
culture and the further production of creative, cultural and scientific
|
||||
works, or to gain reputation or greater distribution for their Work in
|
||||
part through the use and efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any
|
||||
expectation of additional consideration or compensation, the person
|
||||
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
||||
is an owner of Copyright and Related Rights in the Work, voluntarily
|
||||
elects to apply CC0 to the Work and publicly distribute the Work under its
|
||||
terms, with knowledge of his or her Copyright and Related Rights in the
|
||||
Work and the meaning and intended legal effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not
|
||||
limited to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display,
|
||||
communicate, and translate a Work;
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
iii. publicity and privacy rights pertaining to a person's image or
|
||||
likeness depicted in a Work;
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data
|
||||
in a Work;
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation
|
||||
thereof, including any amended or successor version of such
|
||||
directive); and
|
||||
vii. other similar, equivalent or corresponding rights throughout the
|
||||
world based on applicable law or treaty, and any national
|
||||
implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention
|
||||
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
||||
irrevocably and unconditionally waives, abandons, and surrenders all of
|
||||
Affirmer's Copyright and Related Rights and associated claims and causes
|
||||
of action, whether now known or unknown (including existing as well as
|
||||
future claims and causes of action), in the Work (i) in all territories
|
||||
worldwide, (ii) for the maximum duration provided by applicable law or
|
||||
treaty (including future time extensions), (iii) in any current or future
|
||||
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
||||
including without limitation commercial, advertising or promotional
|
||||
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
||||
member of the public at large and to the detriment of Affirmer's heirs and
|
||||
successors, fully intending that such Waiver shall not be subject to
|
||||
revocation, rescission, cancellation, termination, or any other legal or
|
||||
equitable action to disrupt the quiet enjoyment of the Work by the public
|
||||
as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason
|
||||
be judged legally invalid or ineffective under applicable law, then the
|
||||
Waiver shall be preserved to the maximum extent permitted taking into
|
||||
account Affirmer's express Statement of Purpose. In addition, to the
|
||||
extent the Waiver is so judged Affirmer hereby grants to each affected
|
||||
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
||||
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
||||
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
||||
maximum duration provided by applicable law or treaty (including future
|
||||
time extensions), (iii) in any current or future medium and for any number
|
||||
of copies, and (iv) for any purpose whatsoever, including without
|
||||
limitation commercial, advertising or promotional purposes (the
|
||||
"License"). The License shall be deemed effective as of the date CC0 was
|
||||
applied by Affirmer to the Work. Should any part of the License for any
|
||||
reason be judged legally invalid or ineffective under applicable law, such
|
||||
partial invalidity or ineffectiveness shall not invalidate the remainder
|
||||
of the License, and in such case Affirmer hereby affirms that he or she
|
||||
will not (i) exercise any of his or her remaining Copyright and Related
|
||||
Rights in the Work or (ii) assert any associated claims and causes of
|
||||
action with respect to the Work, in either case contrary to Affirmer's
|
||||
express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
b. Affirmer offers the Work as-is and makes no representations or
|
||||
warranties of any kind concerning the Work, express, implied,
|
||||
statutory or otherwise, including without limitation warranties of
|
||||
title, merchantability, fitness for a particular purpose, non
|
||||
infringement, or the absence of latent or other defects, accuracy, or
|
||||
the present or absence of errors, whether or not discoverable, all to
|
||||
the greatest extent permissible under applicable law.
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without
|
||||
limitation any person's Copyright and Related Rights in the Work.
|
||||
Further, Affirmer disclaims responsibility for obtaining any necessary
|
||||
consents, permissions or other rights required for any use of the
|
||||
Work.
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to
|
||||
this CC0 or use of the Work.
|
||||
@@ -1,9 +1,9 @@
|
||||
# Documentation Policy
|
||||
|
||||
**Base Policy Version:** 1.12
|
||||
**Base Policy Version:** 1.13
|
||||
|
||||
**Last Updated**: 2026-11-11
|
||||
**Upstream Source:** [Standard Repository Policies documentation](https://gitea.maximumdirect.net/eric/policy/src/commit/593c9b52273c5c879785ae9e995d21026df467b4/docs/policy/documentation.md)
|
||||
**Last Updated**: 2026-11-22
|
||||
**Upstream Source:** [Standard Repository Policies documentation](https://forge.maximumdirect.net/eric/policy/src/commit/5b9088601290564647a9e20c13f95c0da9f4cb15/docs/policy/documentation.md)
|
||||
|
||||
## 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
|
||||
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
|
||||
|
||||
This policy owns what documentation and examples may contain. Architecture owns
|
||||
|
||||
@@ -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.
|
||||
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).
|
||||
This minimum is required by the selected application dependencies.
|
||||
Distributed executables do not require a Go installation. The selected release
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
# Release Notes
|
||||
|
||||
- [Audita v4.3.0](v4.3.0.md)
|
||||
- [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 v3.1.1](v3.1.1.md)
|
||||
- [Audita v3.1.0](v3.1.0.md)
|
||||
|
||||
38
docs/releases/v4.1.0.md
Normal file
38
docs/releases/v4.1.0.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Audita v4.1.0
|
||||
|
||||
Audita v4.1.0 upgrades ConfigKit, PromptKit, CommandKit, and their configuration
|
||||
and prompt integrations. Application and prompt settings now share one load,
|
||||
with configured secrets bootstrap available before processing and native
|
||||
inspection. The new `--show-tokens` option reports observed PromptKit usage
|
||||
without requiring debug artifacts or ordinary reports.
|
||||
|
||||
## Upgrade action
|
||||
|
||||
Remove root and pipeline-entry `llm.repair_attempts` settings. Prompt definitions
|
||||
now own their output contracts and structural-repair budgets; the shipped prompts'
|
||||
omitted budget selects one additional generation for enabled validation, where
|
||||
the previous Audita default was two. Operator replacement prompts must specify a
|
||||
contract compatible with Audita's response shapes. The semantic correction-repair
|
||||
budget remains separate. Follow the [v4.1 migration guide](../migrations/v4.1.md)
|
||||
for a complete replacement example and conversion details.
|
||||
|
||||
The application configuration remains version 3, and wrapperless prompt
|
||||
companions remain supported. Native PromptKit settings appear under `/promptkit`
|
||||
in the shared application result. Configured secrets bootstrap can populate the
|
||||
process environment during inspection or processing; bootstrap failures stop
|
||||
before transcript and output preparation. Configuration error classification
|
||||
follows the native diagnostics. See [configuration](../config.md) and
|
||||
[subprocess integration](../integrations/subprocess.md).
|
||||
|
||||
Debug execution and prepared-request payloads now nest native PromptKit evidence
|
||||
under `promptkit`; consumers of the former projected fields must update. Ordinary
|
||||
report schemas are unchanged. Native smoke tests default to text; structured
|
||||
consumers should request `--format yaml` or `--format json`. See the
|
||||
[output contract](../integrations/output-files.md#debug-only-files) and
|
||||
[CLI reference](../cli.md).
|
||||
|
||||
Source builds still require Go 1.27.0 or newer, and the Go module path remains
|
||||
`gitea.maximumdirect.net/eric/audita/v4`. This release selects ConfigKit v1.4.0,
|
||||
PromptKit v0.25.0, CommandKit v0.8.0, ckconfig v0.11.0, and ckprompt v0.12.0.
|
||||
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/COPYRIGHT) | [LICENSE](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/LICENSE) | [ATTRIBUTION](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.1.0/docs/oss/attribution.md)
|
||||
66
docs/releases/v4.2.0.md
Normal file
66
docs/releases/v4.2.0.md
Normal 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)
|
||||
51
docs/releases/v4.3.0.md
Normal file
51
docs/releases/v4.3.0.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Audita v4.3.0
|
||||
|
||||
Audita v4.3.0 adopts the Maximum Direct shared glossary contract for explicit
|
||||
runtime files. Applications such as Narratio can pass prepared shared vocabulary
|
||||
directly to Audita for correction and protection.
|
||||
|
||||
## Shared glossary inputs
|
||||
|
||||
Runtime files use `glossary@0.2.0` from schemas distribution `2026.11.1`.
|
||||
One YAML or JSON file can contain multiple collections; repeat `--glossary-file`
|
||||
to supply multiple files. Native imports and ordered composition remain available.
|
||||
Audita bundles the selected schema and validates the completed shared envelope
|
||||
offline before applying its collection entries to application configuration.
|
||||
|
||||
Processing, standalone preflight, and configuration-consuming inspection commands
|
||||
use the same glossary acquisition. Loading vocabulary remains separate from
|
||||
selecting collections for correction or protection. See the
|
||||
[input contract](../integrations/transcript-glossary-files.md#glossary-collections)
|
||||
and [updated examples](../../examples/README.md#runtime-glossary-input).
|
||||
|
||||
## Fixes
|
||||
|
||||
- Schema validation diagnostics identify the affected field and contributing
|
||||
source, including failures originating in an earlier glossary file.
|
||||
- Shared-file entries coexist with disjoint native `--set` glossary overrides.
|
||||
An empty collection map no longer creates an assignment that conflicts with
|
||||
those overrides. Native checks still reject genuinely overlapping assignments.
|
||||
|
||||
## Compatibility and migration
|
||||
|
||||
This release changes the runtime glossary input contract:
|
||||
|
||||
- Replace wrapperless glossary files with the shared envelope containing
|
||||
`schema_version: maximumdirect.glossary.v1` and a `collections` mapping.
|
||||
- Pass desired files explicitly. Automatic `glossary.yml` and recursive
|
||||
`glossary/` discovery have been removed.
|
||||
- Formerly discovered glossary companions acted as an underlay. Explicit files
|
||||
have CLI assignment priority; supplied entry lists replace configured lists,
|
||||
while unrelated configured collections remain.
|
||||
- An `instruction` extension in a shared collection is data and does not become
|
||||
prompt guidance. Inline application collection instructions remain supported.
|
||||
|
||||
See the [migration guide](../migrations/v4.3.md) and
|
||||
[configuration guide](../config.md#loading-and-composition) before upgrading.
|
||||
Automatic prompt companions and inline application vocabulary remain supported.
|
||||
Application configuration remains version 3, and transcript and report schemas
|
||||
are unchanged. Source builds still require Go 1.27.0 or newer; the Go module path
|
||||
remains `gitea.maximumdirect.net/eric/audita/v4`. Dependency versions are unchanged
|
||||
from v4.2.0.
|
||||
|
||||
[COPYRIGHT](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.3.0/COPYRIGHT) | [LICENSE](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.3.0/LICENSE) | [ATTRIBUTION](https://gitea.maximumdirect.net/eric/audita/src/tag/v4.3.0/docs/oss/attribution.md)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Deferred Feature Work
|
||||
|
||||
**Last updated:** 2026-11-15
|
||||
**Last updated:** 2026-11-26
|
||||
|
||||
**Status:** Deferred or exploratory work; not implemented or scheduled. These
|
||||
entries preserve work beyond completed feature and library upgrades.
|
||||
@@ -96,3 +96,13 @@ Broader validator context and combined semantic validation remain exploratory.
|
||||
A proposal to expand context should identify a captured case and the evidence
|
||||
missing from the validator request.
|
||||
See the [current validator context](../internal/validators.md#supplemental-validation-context).
|
||||
|
||||
## Narratio Runtime Glossary Adoption
|
||||
|
||||
Audita's shared glossary boundary accepts explicit `glossary@0.2.0` inputs;
|
||||
see the [input contract](../integrations/transcript-glossary-files.md) and
|
||||
[v4.3 migration guide](../migrations/v4.3.md). Narratio's adapter migration and
|
||||
updates to the separate [audita-pipelines-dnd recipes](https://forge.maximumdirect.net/eric/audita-pipelines-dnd/src/branch/main/README.md)
|
||||
remain separate work. They can pass prepared shared documents, choose explicit
|
||||
files and selections, and review their CLI and output assumptions. Publishing
|
||||
recipes and selecting an Audita release remain separate from implementation.
|
||||
|
||||
162
docs/roadmap/narratio-shared-glossary-feature-request.md
Normal file
162
docs/roadmap/narratio-shared-glossary-feature-request.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Feature request: adopt the shared glossary schema
|
||||
|
||||
## Requested outcome
|
||||
|
||||
Adopt the Maximum Direct shared glossary contract so operators can maintain one
|
||||
vocabulary source for Audita, Notarius, Narratio, and relevant Scriptorium prompts.
|
||||
Narratio should be able to supply its prepared glossary documents directly to
|
||||
Audita without producing an Audita-specific format or embedding task instructions
|
||||
in shared domain data.
|
||||
|
||||
This request describes external behavior and ownership. Audita owns its roadmap,
|
||||
implementation plan, internal representation, and correction strategy. No package
|
||||
structure, parsing library, or internal loading sequence is prescribed.
|
||||
|
||||
## Contract and adoption baseline
|
||||
|
||||
The initial [schemas distribution, 2026.11.0](https://forge.maximumdirect.net/eric/schemas/src/tag/2026.11.0)
|
||||
is published. Recommend adopting `glossary@0.1.0`, identified in operator documents
|
||||
by `maximumdirect.glossary.v1`.
|
||||
|
||||
Authoritative references:
|
||||
|
||||
- [Canonical schema](https://schemas.maximumdirect.net/glossary/v0.1.0/schema.json)
|
||||
and [versioned semantics](https://schemas.maximumdirect.net/glossary/v0.1.0/semantics.md).
|
||||
- [Published inventory](https://forge.maximumdirect.net/eric/schemas/src/tag/2026.11.0/catalog.json)
|
||||
and [source archive](https://forge.maximumdirect.net/eric/schemas/archive/2026.11.0.tar.gz).
|
||||
- [Validation profile](https://forge.maximumdirect.net/eric/schemas/src/tag/2026.11.0/docs/validation.md)
|
||||
and [compatibility guidance](https://forge.maximumdirect.net/eric/schemas/src/tag/2026.11.0/docs/compatibility.md).
|
||||
|
||||
The contracts are also available locally in `../schemas`. Schema and semantic
|
||||
document jointly define the contract. Repository releases use CalVer; individual
|
||||
schemas use independent SemVer. The document marker identifies a contract
|
||||
generation, not the exact schema or distribution version. Canonical hosting serves
|
||||
`main`; published tags and their inventories establish release status.
|
||||
|
||||
Pin the adopted schema version and source distribution. Ordinary validation should
|
||||
work offline, without resolving schemas from the network or depending on a moving
|
||||
latest inventory. The schema repository's internal Go harness is a development
|
||||
tool, not a consumer SDK. This request concerns glossary adoption only; Audita need
|
||||
not adopt the RPG party or campaign schemas to perform this work.
|
||||
|
||||
## External input behavior
|
||||
|
||||
The current [runtime glossary input](../integrations/transcript-glossary-files.md)
|
||||
is a wrapperless mapping keyed by collection name. Recommend replacing that
|
||||
external format with the shared `schema_version` and `collections` envelope.
|
||||
Prefer retaining the established repeated `--glossary-file` interface and its
|
||||
separate collection-selection controls; exact interface changes belong in Audita's
|
||||
roadmap and migration guidance.
|
||||
|
||||
Accept YAML-authored shared documents and equivalent JSON. Operators should not
|
||||
need to remove the envelope, rename shared fields, or maintain a second vocabulary
|
||||
file to use Audita. Composition through native ConfigKit imports and inheritance
|
||||
remains useful. Validate the completed shared document at that boundary; authoring
|
||||
fragments need not independently satisfy the complete-document schema.
|
||||
|
||||
Document how supplied documents interact with configured vocabulary, repeated
|
||||
files, and collection selections. Preserve ConfigKit ownership of composition,
|
||||
precedence, inheritance, and overrides. Do not add a parallel merge or collision
|
||||
policy for Narratio. Configuration inspection and other commands accepting runtime
|
||||
glossary inputs should expose behavior consistent with processing, using their
|
||||
native interfaces.
|
||||
|
||||
Narratio intends to supply four named collections: `party`, `campaign`, `setting`,
|
||||
and `spells`. It derives the party vocabulary from its canonical roster and saves
|
||||
all prepared glossaries as shared domain inputs. These are domain conventions,
|
||||
not an exhaustive schema enumeration or mandatory collection set for Audita.
|
||||
Audita should remain equally useful for weather, sports, and other domains.
|
||||
|
||||
Allow callers to select the collections relevant to each processing task without
|
||||
requiring unrelated collections. Loading vocabulary should not implicitly select
|
||||
all of it. Audita retains ownership of correction behavior, protected-term use,
|
||||
matching, and how domain information is presented to its prompts.
|
||||
|
||||
## Instructions and extension fields
|
||||
|
||||
The shared contract contains domain information, not consumer task instructions.
|
||||
Audita's correction instructions must come from its application configuration.
|
||||
Provide a documented way to associate those instructions with selected vocabulary
|
||||
without requiring the vocabulary itself to be duplicated in configuration.
|
||||
|
||||
Unlike the current runtime format, a collection or entry extension named
|
||||
`instruction` must not become executable guidance merely because it appears in a
|
||||
shared file. Shared input data must not replace or clear configured instructions
|
||||
through that field. Ordinary native configuration controls remain responsible
|
||||
for instruction selection and overrides.
|
||||
|
||||
Honor the shared contract's required fields and optional/null/empty distinctions,
|
||||
including nullable aliases and plural forms. Allow extensions at the envelope,
|
||||
collection, provenance, and entry levels as specified by the contract. Acceptance
|
||||
of an extension does not imply that Audita understands its meaning. Preserve
|
||||
extensions when forwarding a shared document; task-specific prompt views may
|
||||
omit irrelevant information.
|
||||
|
||||
Collection provenance describes source information. It does not supply processing
|
||||
instructions, establish transcript evidence, or require Audita to interpret
|
||||
RPG-specific metadata. A spell glossary may contain information useful only to
|
||||
Notarius, and Audita should not reject it solely for that reason.
|
||||
|
||||
## Validation and readiness
|
||||
|
||||
Apply the adopted structural and semantic contract to completed shared inputs,
|
||||
including exact entry-ID uniqueness within each collection. Shared schema validity
|
||||
is separate from readiness for an Audita task. For example, the schema permits
|
||||
empty collections, while Audita's selected glossary-correction task may require
|
||||
at least one selected entry. Keep that requirement explicit as Audita policy rather
|
||||
than tightening the shared schema.
|
||||
|
||||
Use the same glossary acceptance, composition, and selection semantics in
|
||||
[preflight and processing](../cli.md#preflight). Preflight should catch malformed
|
||||
shared inputs, unsupported contract generations, missing selected collections,
|
||||
and determinable task-input failures before expensive correction begins. Execution
|
||||
still validates its real inputs. Preserve native reporting and error outcomes,
|
||||
with actionable identification of the affected file, collection, or field where
|
||||
practical; no new error taxonomy or report protocol is requested.
|
||||
|
||||
Narratio runs early preflight with its real prepared glossary files and a known-good
|
||||
synthetic transcript, using the intended configuration and provider environment.
|
||||
Continue accepting that through the ordinary preflight interface. No fixture mode
|
||||
is requested, and successful inspection of the supplied transcript does not
|
||||
establish correctness of a future transcript. Preserve Audita's existing provider
|
||||
readiness responsibilities without making schema adoption a separate redesign of
|
||||
preflight.
|
||||
|
||||
## Decisions for Audita's roadmap
|
||||
|
||||
- How the shared envelope enters the public glossary-file interface and how native
|
||||
composition works across runtime files and application configuration.
|
||||
- How configured correction instructions are associated with shared collections,
|
||||
while instruction-named data extensions remain inert.
|
||||
- How root/stage glossary and protected-term selections apply to shared inputs,
|
||||
and which task-specific requirements supplement schema conformance.
|
||||
- The pinned schema version, exact public input behavior, release scope, and
|
||||
migration guidance for existing wrapperless files and embedded instructions.
|
||||
|
||||
Recommend a direct cutover with release documentation, without legacy conversion,
|
||||
compatibility shims, or duplicate operator-maintained vocabulary. Audita should
|
||||
identify genuine shared-contract gaps explicitly rather than silently defining
|
||||
another competing glossary format. No transcript input or corrected-output schema
|
||||
change is requested solely for this adoption.
|
||||
|
||||
## Observable acceptance
|
||||
|
||||
The resulting roadmap should establish that:
|
||||
|
||||
1. A shared glossary prepared by Narratio is accepted directly, in YAML or equivalent
|
||||
JSON, and the selected collections reach the intended correction/protection tasks.
|
||||
2. One authored spell glossary can support both Audita and Notarius after each
|
||||
consumer adopts it, without application-specific vocabulary copies.
|
||||
3. Generic collections work without D&D-specific names or metadata; unrelated
|
||||
collections need not be present or selected.
|
||||
4. Permitted extensions, source provenance, and nullable optional fields are accepted;
|
||||
malformed known fields and duplicate IDs in completed collections are rejected.
|
||||
5. Configured instructions guide processing, while an `instruction` field in shared
|
||||
data neither supplies guidance nor overrides those settings.
|
||||
6. Native composition and preflight expose the same effective glossary inputs and
|
||||
task requirements used by processing, with useful failure diagnostics.
|
||||
7. Ordinary glossary validation works offline, and maintained examples and migration
|
||||
guidance identify the supported contract and external interface.
|
||||
|
||||
Audita owns the roadmap, verification approach, and implementation plan. Narratio
|
||||
will adopt the resulting released interface in its subsequent work.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Build Audita from the repository root with Go 1.27 or newer. The commands below
|
||||
assume the executable is on `PATH`. Each project selects its main file from its
|
||||
own directory, which also determines companion resources and overlay context.
|
||||
own directory, which also determines prompt companions and overlay context.
|
||||
All models, credentials, names, and endpoints are illustrative.
|
||||
|
||||
## Local processing
|
||||
@@ -11,16 +11,20 @@ From `examples/local`, edit `prompts.yml` to match a reachable OpenAI-compatible
|
||||
local service and its model. Then run:
|
||||
|
||||
```sh
|
||||
audita config validate --config config.yml
|
||||
audita process --config config.yml --output corrected.json transcript.json
|
||||
audita config validate --config config.yml --glossary-file glossary.yml
|
||||
audita preflight --smoke=false --config config.yml --glossary-file glossary.yml --output corrected.json transcript.json
|
||||
audita process --config config.yml --glossary-file glossary.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
|
||||
unless disabled. For an offline validator preview, from the same directory:
|
||||
|
||||
```sh
|
||||
audita promptkit show prepared audita/validators.meaning_reversal_review \
|
||||
--config config.yml --profile local \
|
||||
--config config.yml --glossary-file glossary.yml --profile local \
|
||||
--var "PayloadJSON=$(cat validation-candidate.json)" \
|
||||
--var 'TranscriptDescriptionBlock='
|
||||
```
|
||||
@@ -29,7 +33,7 @@ To preview the repair instruction and its output schema without inference:
|
||||
|
||||
```sh
|
||||
audita promptkit show prepared audita/modules.grammar.repair \
|
||||
--config config.yml --profile local \
|
||||
--config config.yml --glossary-file glossary.yml --profile local \
|
||||
--var "RepairRequestJSON=$(cat repair-candidate.json)"
|
||||
```
|
||||
|
||||
@@ -49,34 +53,67 @@ audita promptkit show profile service-test --config config.yml
|
||||
|
||||
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. 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
|
||||
|
||||
From `examples/prompt-edit`, inspect the operator replacement:
|
||||
|
||||
```sh
|
||||
audita promptkit show prompt audita/modules.grammar.proposal --config config.yml
|
||||
audita promptkit show prompt audita/modules.grammar.proposal --config config.yml --glossary-file glossary.yml
|
||||
```
|
||||
|
||||
Edit its message in `prompts.yml`, repeat the inspection, and run `audita process
|
||||
--config config.yml --output corrected.json transcript.json` against a configured
|
||||
local service. Each invocation captures the files anew.
|
||||
--config config.yml --glossary-file glossary.yml --output corrected.json transcript.json` against a configured
|
||||
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
|
||||
|
||||
From `examples/campaigns`, `first.yml` and `second.yml` each consume the common
|
||||
`shared.yml` through the companion `glossary.yml`. Inspect each configuration:
|
||||
From `examples/campaigns`, `first.yml` and `second.yml` explicitly select the
|
||||
[shared multi-collection file](campaigns/glossary.yml), which imports the
|
||||
[synthetic party and spell data](campaigns/shared.yml). Inspect each configuration:
|
||||
|
||||
```sh
|
||||
audita config validate --config first.yml
|
||||
audita config validate --config second.yml
|
||||
audita config validate --config first.yml --glossary-file glossary.yml
|
||||
audita config validate --config second.yml --glossary-file glossary.yml
|
||||
```
|
||||
|
||||
The equivalent arrangement uses separate complete files:
|
||||
|
||||
```sh
|
||||
audita config validate --config first.yml --glossary-file party.yml --glossary-file spells.yml
|
||||
```
|
||||
|
||||
With a local service configured, process either campaign:
|
||||
|
||||
```sh
|
||||
audita process --config first.yml --output first-output.json transcript.json
|
||||
audita process --config second.yml --output second-output.json transcript.json
|
||||
audita process --config first.yml --glossary-file glossary.yml --output first-output.json transcript.json
|
||||
audita process --config second.yml --glossary-file glossary.yml --output second-output.json transcript.json
|
||||
```
|
||||
|
||||
Edit `prompts.yml` for a local service before processing either campaign. The
|
||||
first uses separate party and spell corrections; the second selects only party.
|
||||
The spell input is a shared document and needs no Audita-specific vocabulary copy.
|
||||
|
||||
@@ -2,3 +2,4 @@ config:
|
||||
imports:
|
||||
- path: shared.yml
|
||||
required: true
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
|
||||
8
examples/campaigns/party.yml
Normal file
8
examples/campaigns/party.yml
Normal file
@@ -0,0 +1,8 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries:
|
||||
- id: lyra
|
||||
name: Lyra
|
||||
category: character
|
||||
description: A fictional adventurer.
|
||||
@@ -1,12 +1,16 @@
|
||||
party:
|
||||
entries:
|
||||
- id: lyra
|
||||
name: Lyra
|
||||
category: character
|
||||
description: A fictional adventurer.
|
||||
spells:
|
||||
entries:
|
||||
- id: shield
|
||||
name: Shield
|
||||
category: spell
|
||||
aliases: [Ward]
|
||||
collections:
|
||||
party:
|
||||
entries:
|
||||
- id: lyra
|
||||
name: Lyra
|
||||
category: character
|
||||
description: A fictional adventurer.
|
||||
spells:
|
||||
provenance: {id: synthetic-spells, title: Synthetic spell catalog, version: "1"}
|
||||
entries:
|
||||
- id: shield
|
||||
name: Shield
|
||||
category: spell
|
||||
aliases: [Ward]
|
||||
casting_time: one reaction
|
||||
rank: 1
|
||||
|
||||
11
examples/campaigns/spells.yml
Normal file
11
examples/campaigns/spells.yml
Normal file
@@ -0,0 +1,11 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
spells:
|
||||
provenance: {id: synthetic-spells, title: Synthetic spell catalog, version: "1"}
|
||||
entries:
|
||||
- id: shield
|
||||
name: Shield
|
||||
category: spell
|
||||
aliases: [Ward]
|
||||
casting_time: one reaction
|
||||
rank: 1
|
||||
@@ -1,7 +1,9 @@
|
||||
party:
|
||||
entries:
|
||||
- id: jesters
|
||||
name: Jesters
|
||||
category: faction
|
||||
description: A traveling group of performers.
|
||||
aliases: [Jester]
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries:
|
||||
- id: jesters
|
||||
name: Jesters
|
||||
category: faction
|
||||
description: A traveling group of performers.
|
||||
aliases: [Jester]
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
party:
|
||||
entries:
|
||||
- id: jesters
|
||||
name: Jesters
|
||||
category: faction
|
||||
description: A traveling group of performers.
|
||||
aliases: [Jester]
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries:
|
||||
- id: jesters
|
||||
name: Jesters
|
||||
category: faction
|
||||
description: A traveling group of performers.
|
||||
aliases: [Jester]
|
||||
|
||||
@@ -21,3 +21,4 @@ collections:
|
||||
format: json
|
||||
validation_mode: json_schema
|
||||
schema_path: correction_set.v1.json
|
||||
repair_attempts: 2
|
||||
|
||||
12
examples/service/overlays/runtime-glossary.yml
Normal file
12
examples/service/overlays/runtime-glossary.yml
Normal 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
|
||||
9
examples/service/runtime-glossary.yml
Normal file
9
examples/service/runtime-glossary.yml
Normal file
@@ -0,0 +1,9 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
incoming:
|
||||
entries:
|
||||
- id: speaker
|
||||
name: Mira Chen
|
||||
category: person
|
||||
aliases: [Mira]
|
||||
source_note: Prepared for this recording
|
||||
10
go.mod
10
go.mod
@@ -4,11 +4,11 @@ go 1.27.0
|
||||
|
||||
require (
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
|
||||
go.maximumdirect.net/ckconfig v0.9.0
|
||||
go.maximumdirect.net/ckprompt v0.10.0
|
||||
go.maximumdirect.net/commandkit v0.7.0
|
||||
go.maximumdirect.net/configkit v1.2.1
|
||||
go.maximumdirect.net/promptkit v0.23.2
|
||||
go.maximumdirect.net/ckconfig v0.11.0
|
||||
go.maximumdirect.net/ckprompt v0.12.0
|
||||
go.maximumdirect.net/commandkit v0.8.0
|
||||
go.maximumdirect.net/configkit v1.4.0
|
||||
go.maximumdirect.net/promptkit v0.25.0
|
||||
go.maximumdirect.net/releasekit v0.10.0
|
||||
go.yaml.in/yaml/v4 v4.0.0
|
||||
)
|
||||
|
||||
20
go.sum
20
go.sum
@@ -13,16 +13,16 @@ github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
|
||||
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/yuin/goldmark/v2 v2.1.16 h1:MXvCVo+Cb2SVJ5cwJUzXetDjI7HECRJCkcqylEQtcJo=
|
||||
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.9.0/go.mod h1:yGjFVr2UzjJjiwDdMwsKehuQfvvtv7rTEOIk5NQOY00=
|
||||
go.maximumdirect.net/ckprompt v0.10.0 h1:t2UyWSke+bWH9aTDrw5/bteD+TO0y5LD0NWw0y2KniQ=
|
||||
go.maximumdirect.net/ckprompt v0.10.0/go.mod h1:vx8lZnelASctQtyxY2yV4PuTZfLpE9EqDa+LPj3+SHM=
|
||||
go.maximumdirect.net/commandkit v0.7.0 h1:toLDGhHoVe6gBX5HWuzQ/Joz0cBqEhJXolW21m3axBk=
|
||||
go.maximumdirect.net/commandkit v0.7.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
||||
go.maximumdirect.net/configkit v1.2.1 h1:f+/6WjNl6CULbMr6ZSVwi4aty9rmuDfJlvpeU7I+HZM=
|
||||
go.maximumdirect.net/configkit v1.2.1/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
||||
go.maximumdirect.net/promptkit v0.23.2 h1:nE+Qqqbw5GN4PHD2e5OEWUHXcYkESZm3ryZVBsKWwFQ=
|
||||
go.maximumdirect.net/promptkit v0.23.2/go.mod h1:vPFg76VXcffP0JBFMS2WADCHwV5FYvO2O4bvIoiDlwc=
|
||||
go.maximumdirect.net/ckconfig v0.11.0 h1:oTPW5R4vW5TNs97rqgABC/dir723rbGBz0FUyZ9QiNk=
|
||||
go.maximumdirect.net/ckconfig v0.11.0/go.mod h1:9phvXeLAgQSBKpJWqPyIQASKVJr0nRhiPMIQkfNhaRo=
|
||||
go.maximumdirect.net/ckprompt v0.12.0 h1:TPx4c0ohnG51F5eXk9SLHvkSKGNnWBhzkJAC5LdZCrE=
|
||||
go.maximumdirect.net/ckprompt v0.12.0/go.mod h1:6DsEfIbKsFFzdAAV2TZD2LiwMvEG//s7zFOVe2wDvN0=
|
||||
go.maximumdirect.net/commandkit v0.8.0 h1:EBDjr7SvfgvVDsA2S95hkOhgZe7oGZdDvURDJxHyX48=
|
||||
go.maximumdirect.net/commandkit v0.8.0/go.mod h1:sVp3JXKpm2YrP4Ie8Q3nWmQgwBdPN8uO+wQU72erDns=
|
||||
go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQD63o=
|
||||
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
|
||||
go.maximumdirect.net/promptkit v0.25.0 h1:vJOfxauwASllOSDceR2oypJ4NEwIh2s6F8dDexEzdM8=
|
||||
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/go.mod h1:cT5NZNEcf7SKDx4MPG40YNK9V4bNyIxcLLFuNlbGQ90=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
|
||||
186
internal/appconfig/config.go
Normal file
186
internal/appconfig/config.go
Normal file
@@ -0,0 +1,186 @@
|
||||
// Package appconfig composes Audita and PromptKit configuration sources.
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig/sharedglossary"
|
||||
"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 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}
|
||||
}
|
||||
glossaries, err := sharedglossary.Load(ctx, inputs)
|
||||
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)
|
||||
}
|
||||
}
|
||||
collections := glossaries.Config["collections"].(map[string]any)
|
||||
projected := make(map[string]any, len(collections))
|
||||
for name, value := range collections {
|
||||
collection := value.(map[string]any)
|
||||
projected[name] = map[string]any{"entries": collection["entries"]}
|
||||
}
|
||||
overrides = append(overrides, glossaryOverrides(projected, options.Overrides)...)
|
||||
}
|
||||
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 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
|
||||
}
|
||||
|
||||
func glossaryOverrides(projected map[string]any, supplied []ck.Override) []ck.Override {
|
||||
if len(projected) == 0 {
|
||||
return nil
|
||||
}
|
||||
root := ck.Keys("glossary_collections")
|
||||
for _, override := range supplied {
|
||||
path := override.Path.String()
|
||||
if path != root.String() && !strings.HasPrefix(path, root.String()+"/") {
|
||||
continue
|
||||
}
|
||||
// Only split when caller overrides need to share this namespace. The
|
||||
// usual batch keeps one native record regardless of collection count.
|
||||
names := make([]string, 0, len(projected))
|
||||
for name := range projected {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
result := make([]ck.Override, 0, len(names))
|
||||
for _, name := range names {
|
||||
entries := projected[name].(map[string]any)["entries"]
|
||||
result = append(result, ck.Override{Path: root.Key(name).Key("entries"), Value: entries, Flag: "--glossary-file"})
|
||||
}
|
||||
return result
|
||||
}
|
||||
return []ck.Override{{Path: root, Value: projected, Flag: "--glossary-file"}}
|
||||
}
|
||||
77
internal/appconfig/config_test.go
Normal file
77
internal/appconfig/config_test.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestLoadCombinesApplicationAndPromptSettings(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(dir, "overlays"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, data := range map[string]string{
|
||||
"config.yml": "version: 3\nllm:\n transient_retries: 4\n",
|
||||
"prompts.yml": "profiles:\n - id: local\n model: fixture\ncollections:\n example:\n prompts:\n - id: sample\n messages:\n - role: user\n content_file: message.txt\n output:\n format: text\n validation_mode: none\n",
|
||||
"message.txt": "A source-local message.",
|
||||
"overlays/selected.yml": "context:\n description: overlay\n",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
106
internal/appconfig/glossary_test.go
Normal file
106
internal/appconfig/glossary_test.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestGlossaryFilesRequireExplicitSelection(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, data string) {
|
||||
t.Helper()
|
||||
file := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(data), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("config.yml", "version: 3\nglossary_collections:\n party:\n entries: [{id: configured, name: Configured, category: person}]\n")
|
||||
write("glossary.yml", "invalid: [\n")
|
||||
write("glossary/nested/spells.yaml", "invalid: [\n")
|
||||
main := ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}
|
||||
result, _, err := Load(context.Background(), main, Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Config.Application.GlossaryCollections) != 1 || result.Config.Application.GlossaryCollections["party"].Entries[0].ID != "configured" {
|
||||
t.Fatalf("unexpected vocabulary: %+v", result.Config.Application.GlossaryCollections)
|
||||
}
|
||||
write("glossary.yml", `config:
|
||||
imports: [{path: shared/extra.yml, required: true}]
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries: [{id: selected, name: Selected, category: person}]
|
||||
`)
|
||||
write("shared/extra.yml", "collections:\n lore:\n entries: [{id: lore, name: Lore, category: topic}]\n")
|
||||
write("glossary/nested/spells.yaml", "schema_version: maximumdirect.glossary.v1\ncollections:\n spells:\n entries: [{id: bolt, name: Bolt, category: spell}]\n")
|
||||
paths := []string{filepath.Join(dir, "glossary.yml"), filepath.Join(dir, "glossary/nested/spells.yaml")}
|
||||
result, _, err = Load(context.Background(), main, Options{GlossaryFiles: paths})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collections := result.Config.Application.GlossaryCollections
|
||||
if collections["party"].Entries[0].ID != "selected" || len(collections["lore"].Entries) != 1 || len(collections["spells"].Entries) != 1 {
|
||||
t.Fatalf("explicit vocabulary = %+v", collections)
|
||||
}
|
||||
for _, name := range []string{"glossary.yml", "shared/extra.yml", "glossary/nested/spells.yaml"} {
|
||||
if !slices.Contains(result.GlossarySources, filepath.Join(dir, name)) {
|
||||
t.Errorf("missing source %s: %v", name, result.GlossarySources)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInlineGlossaryValidation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
main := filepath.Join(dir, "config.yml")
|
||||
write := func(path, data string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, data := range []string{
|
||||
"glossary_collections:\n empty: {entries: []}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: 'id with spaces', name: N, category: C}\n",
|
||||
} {
|
||||
write(main, data)
|
||||
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{}); err != nil {
|
||||
t.Fatalf("valid %q: %v", data, err)
|
||||
}
|
||||
}
|
||||
for _, data := range []string{
|
||||
"glossary_collections:\n x:\n entries:\n - {id: '', name: N, category: C}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: '', category: C}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, aliases: ['']}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, plural: ''}\n",
|
||||
} {
|
||||
write(main, data)
|
||||
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{}); err == nil {
|
||||
t.Fatalf("accepted %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "glossary.yml"), []byte("leak:\n entries:\n - {id: a, name: A, category: C}\n"), 0644); 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 len(result.Config.Application.GlossaryCollections) != 0 {
|
||||
t.Fatalf("unanchored glossary loaded: %+v", result.Config.Application.GlossaryCollections)
|
||||
}
|
||||
}
|
||||
183
internal/appconfig/runtime_glossary_test.go
Normal file
183
internal/appconfig/runtime_glossary_test.go
Normal file
@@ -0,0 +1,183 @@
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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}]
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
instruction: {not: executable}
|
||||
entries:
|
||||
- {id: shared, name: Old, category: person, aliases: [Former]}
|
||||
- {id: retained, name: Retained, category: person}
|
||||
`,
|
||||
"imported.yml": `collections:
|
||||
other:
|
||||
entries: [{id: imported, name: Imported, category: lore}]
|
||||
`,
|
||||
"last.yml": `schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries:
|
||||
- {id: shared, name: New, category: person, note: kept, aliases: null, plural: null}
|
||||
`,
|
||||
}
|
||||
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 TestRuntimeGlossaryLargeCollectionBatch(t *testing.T) {
|
||||
collections := make(map[string]any)
|
||||
for i := range 1100 {
|
||||
collections[fmt.Sprintf("collection-%d", i)] = map[string]any{"entries": []any{}}
|
||||
}
|
||||
data, err := json.Marshal(map[string]any{"schema_version": "maximumdirect.glossary.v1", "collections": collections})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := filepath.Join(t.TempDir(), "shared.json")
|
||||
if err := os.WriteFile(file, data, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, Options{
|
||||
GlossaryFiles: []string{file},
|
||||
Overrides: []ck.Override{{Path: ck.Keys("context", "description"), Value: "batch", Flag: "--set"}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.Config.Application.GlossaryCollections) != len(collections) {
|
||||
t.Fatalf("loaded %d collections, want %d", len(got.Config.Application.GlossaryCollections), len(collections))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeGlossaryPresence(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
valid bool
|
||||
wantEntries int
|
||||
}{
|
||||
{"empty", "party: {entries: []}", true, 0},
|
||||
{"missing entries", "party: {}", false, 0},
|
||||
{"null entries", "party: {entries: null}", false, 0},
|
||||
{"empty collections", "", true, 1},
|
||||
} {
|
||||
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)
|
||||
}
|
||||
body := "schema_version: maximumdirect.glossary.v1\ncollections:"
|
||||
if tc.body == "" {
|
||||
body += " {}\n"
|
||||
} else {
|
||||
body += "\n " + tc.body + "\n"
|
||||
}
|
||||
if err := os.WriteFile(incoming, []byte(body), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{GlossaryFiles: []string{incoming}})
|
||||
if !tc.valid {
|
||||
var inputErr *GlossaryInputError
|
||||
if !errors.As(err, &inputErr) {
|
||||
t.Fatalf("expected glossary input error, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
party := got.Config.Application.GlossaryCollections["party"]
|
||||
if party.Instruction != "original" || len(party.Entries) != tc.wantEntries {
|
||||
t.Fatalf("party = %+v", party)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
75
internal/appconfig/secrets_test.go
Normal file
75
internal/appconfig/secrets_test.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package appconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestLoadBootstrapsSecrets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
secrets := filepath.Join(dir, "secrets")
|
||||
if err := os.Mkdir(secrets, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("AUDITA_TEST_BOOTSTRAP", "original")
|
||||
if err := os.WriteFile(filepath.Join(secrets, "AUDITA_TEST_BOOTSTRAP"), []byte("synthetic"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := filepath.Join(dir, "config.yml")
|
||||
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Upstream compatibility guidance
|
||||
|
||||
See the [compatibility guide from the selected schemas distribution](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/compatibility.md).
|
||||
@@ -0,0 +1,3 @@
|
||||
# Upstream validation guidance
|
||||
|
||||
See the [validation guide from the selected schemas distribution](https://forge.maximumdirect.net/eric/schemas/src/commit/f7e3cedeca11ed903311cdf29ca4d81fb1f216b7/docs/validation.md).
|
||||
@@ -0,0 +1,21 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
campaign:
|
||||
entries:
|
||||
- id: lighthouse
|
||||
name: Glass Lantern
|
||||
category: place
|
||||
aliases: [The Lantern]
|
||||
description: A fictional lighthouse at the entrance to the bay.
|
||||
spells:
|
||||
provenance:
|
||||
id: lantern-coast-original
|
||||
title: Synthetic campaign spells
|
||||
version: "1"
|
||||
license: CC0-1.0
|
||||
entries:
|
||||
- id: ember-veil
|
||||
name: Ember Veil
|
||||
category: spell
|
||||
aliases: [Veil of Embers]
|
||||
casting_time: one action
|
||||
@@ -0,0 +1,16 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
clubs:
|
||||
sport: association football
|
||||
entries:
|
||||
- id: harbour
|
||||
name: Harbour Wanderers
|
||||
category: club
|
||||
aliases: []
|
||||
plural: null
|
||||
home_ground: Lantern Park
|
||||
venues:
|
||||
entries:
|
||||
- id: harbour
|
||||
name: Lantern Park
|
||||
category: venue
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"schema_version": "maximumdirect.glossary.v1",
|
||||
"collections": {
|
||||
"measurements": {
|
||||
"unit_system": "metric",
|
||||
"entries": [
|
||||
{"id": "temperature", "name": "Air temperature", "category": "measurement", "aliases": ["Temperature"], "unit": "degree Celsius"},
|
||||
{"id": "precipitation", "name": "Precipitation", "category": "measurement", "aliases": null, "unit": "millimetre"}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
measurements:
|
||||
unit_system: metric
|
||||
entries:
|
||||
- id: temperature
|
||||
name: Air temperature
|
||||
category: measurement
|
||||
aliases: [Temperature]
|
||||
unit: degree Celsius
|
||||
- id: precipitation
|
||||
name: Precipitation
|
||||
category: measurement
|
||||
aliases: null
|
||||
unit: millimetre
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json",
|
||||
"title": "MAXIMUMDIRECT Glossary v1",
|
||||
"type": "object",
|
||||
"required": ["schema_version", "collections"],
|
||||
"properties": {
|
||||
"schema_version": {"const": "maximumdirect.glossary.v1"},
|
||||
"collections": {
|
||||
"type": "object",
|
||||
"propertyNames": {"minLength": 1},
|
||||
"additionalProperties": {"$ref": "#/$defs/collection"}
|
||||
}
|
||||
},
|
||||
"$defs": {
|
||||
"text": {"type": "string", "minLength": 1},
|
||||
"aliases": {"type": ["array", "null"], "items": {"$ref": "#/$defs/text"}},
|
||||
"entry": {
|
||||
"type": "object",
|
||||
"required": ["id", "name", "category"],
|
||||
"properties": {
|
||||
"id": {"$ref": "#/$defs/text"},
|
||||
"name": {"$ref": "#/$defs/text"},
|
||||
"category": {"$ref": "#/$defs/text"},
|
||||
"description": {"type": "string"},
|
||||
"aliases": {"$ref": "#/$defs/aliases"},
|
||||
"plural": {"type": ["string", "null"], "minLength": 1}
|
||||
}
|
||||
},
|
||||
"provenance": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"$ref": "#/$defs/text"},
|
||||
"title": {"$ref": "#/$defs/text"},
|
||||
"version": {"type": "string"},
|
||||
"url": {"type": "string"},
|
||||
"license": {"type": "string"}
|
||||
}
|
||||
},
|
||||
"partialCollection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"entries": {"type": "array", "items": {"$ref": "#/$defs/entry"}},
|
||||
"provenance": {"$ref": "#/$defs/provenance"}
|
||||
}
|
||||
},
|
||||
"collection": {
|
||||
"allOf": [{"$ref": "#/$defs/partialCollection"}, {"required": ["entries"]}]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
# Glossary contract
|
||||
|
||||
## Native loading boundary
|
||||
|
||||
Full conformance includes acquisition through the public mapping-root handoff of
|
||||
[ConfigKit v1.4.0](https://forge.maximumdirect.net/base-layer/configkit/src/commit/4a7ae664a6287d71cba20f59c7c5b37b6f05b0a3/docs/config.md),
|
||||
followed by this schema and its semantic checks. ConfigKit owns syntax, structural
|
||||
controls, numeric binding, and resource limits, including its 8 MiB source limit.
|
||||
Dynamic integers bind as int64 and fractional/exponent values as finite float64;
|
||||
authored decimal precision is not guaranteed. Preserve supported resolved values.
|
||||
`extends` is structural input and source-root `config` is a control namespace;
|
||||
nested ordinary `config` follows upstream rules. Other supported domain extensions
|
||||
remain permitted. Schema validation adds no trimming, case folding, or defaults.
|
||||
Structural validation alone does not prove native loading compatibility. The
|
||||
pinned upstream contract defines this version's boundary independently of later
|
||||
changes to the repository's general guidance.
|
||||
|
||||
Contract: `maximumdirect.glossary.v1`. [Schema](schema.json).
|
||||
The [validation profile](../../docs/validation.md) and [compatibility rules](../../docs/compatibility.md)
|
||||
apply. Start with [campaign vocabulary](examples/glossary.yml),
|
||||
[weather](examples/weather.yml), or [sports](examples/sports.yml).
|
||||
|
||||
| Field | Required | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `schema_version` | Yes | Exactly `maximumdirect.glossary.v1`. |
|
||||
| `collections` | Yes | Mapping of nonempty collection names to collections; may be empty. |
|
||||
| `collections.<name>.entries` | Yes | List of entries; may be empty. |
|
||||
| `entries[].id` | Yes | Stable, nonempty identity unique within this collection. |
|
||||
| `entries[].name` | Yes | Nonempty canonical display name. |
|
||||
| `entries[].category` | Yes | Nonempty domain-defined category. |
|
||||
| `entries[].description` | No | Description; an empty string is valid. |
|
||||
| `entries[].aliases` | No | Alternative names for the same entity. May be null, empty, or a list of nonempty strings. |
|
||||
| `entries[].plural` | No | Nonempty plural display form, or null. |
|
||||
| `collections.<name>.provenance` | No | Source metadata object, possibly empty. Optional `id` and `title` are nonempty strings; optional `version`, `url`, and `license` are strings that may be empty. |
|
||||
|
||||
All objects permit extensions. Optional fields accept omission; only `aliases`
|
||||
and `plural` additionally accept null. Supported resolved values are preserved; schema validation adds no trimming,
|
||||
case folding, coercion, or defaults. IDs and names compare exactly. Distinct
|
||||
collections can reuse an ID. Display names, aliases, and categories need not be
|
||||
unique. Lists retain their authored order but establish no precedence or execution
|
||||
order. Collection names and categories are strings chosen by the domain, not a
|
||||
fixed set of D&D labels.
|
||||
|
||||
For example, `spells` entries contain names, aliases, and optionally extended
|
||||
domain information such as `casting_time`. Their collection's provenance can
|
||||
identify a source catalog. Domain-specific metadata can use extension fields.
|
||||
Provenance describes origin and applicability;
|
||||
it is not transcript evidence or a spell rule. If different source contexts
|
||||
matter, use separately named collections with their own provenance. A consumer
|
||||
can derive its recognition input from these entries instead of requiring a second
|
||||
operator-maintained spell list. Embedded vocabulary, source precedence,
|
||||
normalization, inference, and conflicts remain consumer policy.
|
||||
|
||||
Entry-ID uniqueness is a semantic rule checked separately from JSON Schema.
|
||||
The [validator](../../docs/validation.md) performs both checks. No cross-document identity or
|
||||
reference-resolution check is part of this initial contract.
|
||||
|
||||
## Extensions and task instructions
|
||||
|
||||
Extensions describe domain information. Consumers forwarding a shared document
|
||||
should retain them; task-specific projections may intentionally omit them.
|
||||
Acceptance and preservation do not claim interpretation. Defined fields retain
|
||||
their schema constraints in an extended document.
|
||||
|
||||
Task instructions belong to consumer configuration. `instruction` is not a
|
||||
defined field in this contract. Like other unknown fields, it can be retained
|
||||
without acquiring instruction semantics. Maintained examples contain domain
|
||||
data only.
|
||||
|
||||
## Authoring contributions
|
||||
|
||||
`#/$defs/partialCollection` is an editor-assistance definition with optional
|
||||
`entries`. `#/$defs/entry` and `#/$defs/collection` assist entry and complete
|
||||
collection editing. A partial contribution is not a standalone valid domain
|
||||
document. ConfigKit owns imports, inheritance, and composition before validation
|
||||
of the complete envelope.
|
||||
|
||||
## Differences from the reference catalog and Audita v4.2
|
||||
|
||||
The old format maps collection names directly at the root. The shared format
|
||||
requires `schema_version` and `collections`. It removes defined collection
|
||||
instructions, permits structural extensions, and adds defined provenance.
|
||||
Existing consumers must explicitly adopt this envelope and its semantics.
|
||||
77
internal/appconfig/sharedglossary/load.go
Normal file
77
internal/appconfig/sharedglossary/load.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package sharedglossary
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
// Load composes ordered shared documents and validates the completed envelope.
|
||||
// A nil result means no documents were supplied.
|
||||
func Load(ctx context.Context, inputs []ck.Input) (*ck.Result[map[string]any], error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(inputs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
validator, err := NewValidator()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
underlays := make([]ck.Underlay, 0, len(inputs)-1)
|
||||
for _, input := range inputs[:len(inputs)-1] {
|
||||
input.Imports = true
|
||||
underlays = append(underlays, ck.Underlay{Inputs: []ck.Input{input}})
|
||||
}
|
||||
main := inputs[len(inputs)-1]
|
||||
main.Imports = true
|
||||
result, err := ck.LoadLayered(main, ck.LayeredOptions[map[string]any]{
|
||||
Definition: ck.Definition[map[string]any]{
|
||||
SequenceIdentities: []ck.SequenceIdentity{config.GlossaryEntryIdentity(ck.SequenceSelector{ck.SequenceLiteralKey("collections")})},
|
||||
Validate: func(document *map[string]any, validation *ck.Validation) {
|
||||
if err := validator.Validate(*document, "input"); err != nil {
|
||||
var schemaError *jsonschema.ValidationError
|
||||
if errors.As(err, &schemaError) {
|
||||
reportSchemaError(validation, schemaError)
|
||||
} else {
|
||||
validation.Error(ck.Keys(), err.Error())
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
Underlays: underlays,
|
||||
})
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return nil, errors.Join(err, canceled)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func reportSchemaError(validation *ck.Validation, err *jsonschema.ValidationError) {
|
||||
if len(err.Causes) > 0 {
|
||||
for _, cause := range err.Causes {
|
||||
reportSchemaError(validation, cause)
|
||||
}
|
||||
return
|
||||
}
|
||||
path := ck.Keys()
|
||||
if len(err.InstanceLocation) > 0 {
|
||||
segments := make([]string, len(err.InstanceLocation))
|
||||
for i, segment := range err.InstanceLocation {
|
||||
segments[i] = strings.ReplaceAll(strings.ReplaceAll(segment, "~", "~0"), "/", "~1")
|
||||
}
|
||||
// Escaped instance segments always form a valid JSON Pointer. Parsing
|
||||
// leaves numeric keys/indexes for ConfigKit to resolve against the data.
|
||||
path, _ = ck.ParsePath("/" + strings.Join(segments, "/"))
|
||||
}
|
||||
validation.Error(path, err.Error())
|
||||
}
|
||||
223
internal/appconfig/sharedglossary/load_test.go
Normal file
223
internal/appconfig/sharedglossary/load_test.go
Normal file
@@ -0,0 +1,223 @@
|
||||
package sharedglossary
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestLoadComposition(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
files := map[string]string{
|
||||
"first.yml": `config:
|
||||
imports: [{path: fragment.yml, required: true}]
|
||||
schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
people:
|
||||
entries:
|
||||
- {id: one, name: Old, category: person}
|
||||
- {id: two, name: Two, category: person}
|
||||
places:
|
||||
entries: []
|
||||
`,
|
||||
"fragment.yml": `collections:
|
||||
lore:
|
||||
entries: [{id: lore, name: Lore, category: topic}]
|
||||
`,
|
||||
"second.yml": `schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
people:
|
||||
entries: [{id: one, name: New, category: person}]
|
||||
`,
|
||||
"third.json": `{"schema_version":"maximumdirect.glossary.v1","collections":{"spells":{"entries":[{"id":"one","name":"Spell","category":"spell"}]}}}`,
|
||||
}
|
||||
for name, body := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
files []string
|
||||
collections []string
|
||||
}{
|
||||
{"one multi collection file", []string{"first.yml"}, []string{"people", "places", "lore"}},
|
||||
{"multiple single collection files", []string{"second.yml", "third.json"}, []string{"people", "spells"}},
|
||||
{"mixed files", []string{"first.yml", "second.yml", "third.json"}, []string{"people", "places", "lore", "spells"}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var inputs []ck.Input
|
||||
for _, name := range tc.files {
|
||||
inputs = append(inputs, ck.Input{Source: ck.File(filepath.Join(dir, name))})
|
||||
}
|
||||
result, err := Load(context.Background(), inputs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collections := result.Config["collections"].(map[string]any)
|
||||
for _, name := range tc.collections {
|
||||
if _, ok := collections[name]; !ok {
|
||||
t.Errorf("missing collection %s in %v", name, collections)
|
||||
}
|
||||
}
|
||||
if slices.Contains(tc.files, "first.yml") {
|
||||
var paths []string
|
||||
for _, source := range result.Sources() {
|
||||
paths = append(paths, source.Path)
|
||||
}
|
||||
if !slices.Contains(paths, filepath.Join(dir, "fragment.yml")) {
|
||||
t.Errorf("missing imported source: %v", paths)
|
||||
}
|
||||
}
|
||||
if slices.Contains(tc.files, "first.yml") && slices.Contains(tc.files, "second.yml") {
|
||||
entries := collections["people"].(map[string]any)["entries"].([]any)
|
||||
if len(entries) != 2 || entries[0].(map[string]any)["name"] != "New" {
|
||||
t.Fatalf("layered entries = %#v", entries)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadErrorsAndEmptyInput(t *testing.T) {
|
||||
result, err := Load(context.Background(), nil)
|
||||
if err != nil || result != nil {
|
||||
t.Fatalf("no inputs = %v, %v", result, err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := Load(ctx, nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation = %v", err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
for _, tc := range []struct{ name, body, contains string }{
|
||||
{"duplicates", "schema_version: maximumdirect.glossary.v1\ncollections:\n people:\n entries: [{id: a, name: A, category: person}, {id: a, name: B, category: person}]\n", "a"},
|
||||
{"missing marker", "collections: {}\n", "schema_version"},
|
||||
{"invalid type", "schema_version: maximumdirect.glossary.v1\ncollections: []\n", "collections"},
|
||||
{"unsupported input", "schema_version: !!str maximumdirect.glossary.v1\ncollections: {}\n", ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
path := filepath.Join(dir, strings.ReplaceAll(tc.name, " ", "_")+".yml")
|
||||
if err := os.WriteFile(path, []byte(tc.body), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := Load(context.Background(), []ck.Input{{Source: ck.File(path)}})
|
||||
var loadErr *ck.LoadError
|
||||
if !errors.As(err, &loadErr) {
|
||||
t.Fatalf("expected native load error, got %v", err)
|
||||
}
|
||||
var messages []string
|
||||
for _, diagnostic := range loadErr.Diagnostics() {
|
||||
messages = append(messages, diagnostic.Message)
|
||||
}
|
||||
if !strings.Contains(strings.Join(messages, " "), tc.contains) {
|
||||
t.Fatalf("diagnostics = %v", messages)
|
||||
}
|
||||
var paths []string
|
||||
for _, source := range loadErr.Sources() {
|
||||
paths = append(paths, source.Path)
|
||||
}
|
||||
if !slices.Contains(paths, path) {
|
||||
t.Fatalf("missing source context: %v", paths)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaFailureUsesContributingSource(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
first := filepath.Join(dir, "first.yml")
|
||||
last := filepath.Join(dir, "last.yml")
|
||||
if err := os.WriteFile(last, []byte("schema_version: maximumdirect.glossary.v1\ncollections: {}\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ name, entry, path string }{
|
||||
{"invalid value", "{id: a, name: 17, category: person}", "/collections/7~1~0/entries/0/name"},
|
||||
{"missing field", "{id: a, category: person}", "/collections/7~1~0/entries/0"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
body := "schema_version: maximumdirect.glossary.v1\ncollections:\n '7/~':\n entries: [" + tc.entry + "]\n"
|
||||
if err := os.WriteFile(first, []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := Load(context.Background(), []ck.Input{{Source: ck.File(first)}, {Source: ck.File(last)}})
|
||||
var loadErr *ck.LoadError
|
||||
if !errors.As(err, &loadErr) {
|
||||
t.Fatalf("expected native load error, got %v", err)
|
||||
}
|
||||
sources := make(map[string]string)
|
||||
for _, source := range loadErr.Sources() {
|
||||
sources[source.ID] = source.Path
|
||||
}
|
||||
diagnostics := loadErr.Diagnostics()
|
||||
if len(diagnostics) != 1 || diagnostics[0].Path.String() != tc.path {
|
||||
t.Fatalf("unexpected diagnostics: %+v", diagnostics)
|
||||
}
|
||||
location := diagnostics[0].Primary
|
||||
if location == nil || sources[location.SourceID] != first {
|
||||
t.Fatalf("diagnostic points to %v with sources %v", location, sources)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadResolvesInheritanceAndPreservesExtensions(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "shared.yml")
|
||||
body := `schema_version: maximumdirect.glossary.v1
|
||||
custom: {revision: 1, ratio: 1.5}
|
||||
collections:
|
||||
original:
|
||||
provenance: {title: Synthetic source, custom: true}
|
||||
entries: [{id: a, name: Alpha, category: spell, rank: 1}]
|
||||
derived:
|
||||
extends: original
|
||||
instruction: {text: data}
|
||||
`
|
||||
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := Load(context.Background(), []ck.Input{{Source: ck.File(path)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collections := result.Config["collections"].(map[string]any)
|
||||
derived := collections["derived"].(map[string]any)
|
||||
entries := derived["entries"].([]any)
|
||||
if len(entries) != 1 || entries[0].(map[string]any)["rank"] != int64(1) || derived["provenance"].(map[string]any)["title"] != "Synthetic source" || derived["instruction"].(map[string]any)["text"] != "data" {
|
||||
t.Fatalf("resolved data = %#v", result.Config)
|
||||
}
|
||||
custom := result.Config["custom"].(map[string]any)
|
||||
if custom["revision"] != int64(1) || custom["ratio"] != 1.5 {
|
||||
t.Fatalf("extensions = %#v", custom)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEquivalentYAMLAndJSON(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
documents := map[string]string{
|
||||
"input.yml": "schema_version: maximumdirect.glossary.v1\ncollections:\n terms:\n entries: [{id: a, name: Alpha, category: term}, {id: A, name: Alpha, category: term}]\n",
|
||||
"input.json": `{"schema_version":"maximumdirect.glossary.v1","collections":{"terms":{"entries":[{"id":"a","name":"Alpha","category":"term"},{"id":"A","name":"Alpha","category":"term"}]}}}`,
|
||||
}
|
||||
var results []map[string]any
|
||||
for name, body := range documents {
|
||||
path := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(path, []byte(body), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := Load(context.Background(), []ck.Input{{Source: ck.File(path)}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
results = append(results, result.Config)
|
||||
}
|
||||
if !reflect.DeepEqual(results[0], results[1]) {
|
||||
t.Fatalf("documents differ: %#v, %#v", results[0], results[1])
|
||||
}
|
||||
}
|
||||
52
internal/appconfig/sharedglossary/schema.go
Normal file
52
internal/appconfig/sharedglossary/schema.go
Normal file
@@ -0,0 +1,52 @@
|
||||
// Package sharedglossary implements the boundary for shared glossary documents.
|
||||
package sharedglossary
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
|
||||
const schemaID = "https://schemas.maximumdirect.net/glossary/v0.2.0/schema.json"
|
||||
|
||||
//go:embed assets/glossary/v0.2.0/schema.json
|
||||
var schemaData []byte
|
||||
|
||||
// Validator validates completed shared glossary envelopes.
|
||||
type Validator struct {
|
||||
schema *jsonschema.Schema
|
||||
}
|
||||
|
||||
// NewValidator compiles the locally bundled schema for reuse.
|
||||
func NewValidator() (*Validator, error) {
|
||||
var document any
|
||||
if err := json.Unmarshal(schemaData, &document); err != nil {
|
||||
return nil, fmt.Errorf("decode shared glossary schema: %w", err)
|
||||
}
|
||||
compiler := jsonschema.NewCompiler()
|
||||
compiler.UseLoader(offlineLoader{})
|
||||
if err := compiler.AddResource(schemaID, document); err != nil {
|
||||
return nil, fmt.Errorf("register shared glossary schema: %w", err)
|
||||
}
|
||||
schema, err := compiler.Compile(schemaID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compile shared glossary schema: %w", err)
|
||||
}
|
||||
return &Validator{schema: schema}, nil
|
||||
}
|
||||
|
||||
// Validate checks an envelope without modifying it, retaining source context.
|
||||
func (v *Validator) Validate(document map[string]any, source string) error {
|
||||
if err := v.schema.Validate(document); err != nil {
|
||||
return fmt.Errorf("shared glossary %s: %w", source, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type offlineLoader struct{}
|
||||
|
||||
func (offlineLoader) Load(url string) (any, error) {
|
||||
return nil, fmt.Errorf("unregistered schema resource %q", url)
|
||||
}
|
||||
81
internal/appconfig/sharedglossary/schema_test.go
Normal file
81
internal/appconfig/sharedglossary/schema_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package sharedglossary
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
validator, err := NewValidator()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, document, location string
|
||||
valid bool
|
||||
}{
|
||||
{"ordinary", `{"schema_version":"maximumdirect.glossary.v1","collections":{"terms":{"entries":[{"id":"one","name":"One","category":"number"}]}}}`, "", true},
|
||||
{"empty collections", `{"schema_version":"maximumdirect.glossary.v1","collections":{}}`, "", true},
|
||||
{"nullable and extensions", `{"schema_version":"maximumdirect.glossary.v1","extra":true,"collections":{"terms":{"instruction":42,"provenance":{"extra":true},"entries":[{"id":"one","name":"One","category":"number","aliases":null,"plural":null,"extra":{"n":1}}]}}}`, "", true},
|
||||
{"missing marker", `{"collections":{}}`, "schema_version", false},
|
||||
{"wrong marker", `{"schema_version":"wrong","collections":{}}`, "schema_version", false},
|
||||
{"missing entries", `{"schema_version":"maximumdirect.glossary.v1","collections":{"terms":{}}}`, "entries", false},
|
||||
{"invalid name", `{"schema_version":"maximumdirect.glossary.v1","collections":{"terms":{"entries":[{"id":"one","name":3,"category":"number"}]}}}`, "name", false},
|
||||
{"invalid aliases", `{"schema_version":"maximumdirect.glossary.v1","collections":{"terms":{"entries":[{"id":"one","name":"One","category":"number","aliases":3}]}}}`, "aliases", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var document, before map[string]any
|
||||
if err := json.Unmarshal([]byte(tc.document), &document); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := json.Unmarshal([]byte(tc.document), &before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err := validator.Validate(document, "example.yml")
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("Validate() = %v", err)
|
||||
}
|
||||
if !tc.valid && (!strings.Contains(err.Error(), "example.yml") || !strings.Contains(err.Error(), tc.location)) {
|
||||
t.Fatalf("error lacks source or field location: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(document, before) {
|
||||
t.Fatal("validation modified the document")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBundledExamples(t *testing.T) {
|
||||
validator, err := NewValidator()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"glossary.yml", "sports.yml", "weather.yml", "weather.json"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := filepath.Join("assets", "glossary", "v0.2.0", "examples", name)
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var document map[string]any
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := validator.Validate(document, path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfflineLoader(t *testing.T) {
|
||||
if _, err := (offlineLoader{}).Load("https://example.invalid/schema.json"); err == nil {
|
||||
t.Fatal("unregistered resource was accepted")
|
||||
}
|
||||
}
|
||||
118
internal/appconfig/sources_test.go
Normal file
118
internal/appconfig/sources_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"reflect"
|
||||
"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/prompts"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
@@ -24,10 +24,15 @@ type invocationState struct {
|
||||
}
|
||||
type engineEntry struct {
|
||||
selection ckconfig.Selection
|
||||
input acquisitionInput
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -40,10 +45,19 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct
|
||||
} else {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -55,10 +69,10 @@ func loadPromptEngine(ctx context.Context, selection ckconfig.Selection, input s
|
||||
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 {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -68,30 +82,49 @@ func capturePromptEngine(ctx context.Context, selection ckconfig.Selection, inpu
|
||||
return nil, err
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
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) {
|
||||
return buildApplicationWithClient(nil, extra...)
|
||||
}
|
||||
|
||||
func buildApplicationWithClient(client *http.Client, extra ...commandkit.Declaration) (*commandkit.App, error) {
|
||||
selector := commandkit.RepeatFlag(commandkit.FlagMeta{Name: "glossary-file", Usage: "Shared glossary YAML or JSON 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.Features.Overrides = true
|
||||
promptScope := ckprompt.ConfigScope(loadPromptEngine)
|
||||
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}})
|
||||
appScope = shareComparisonGlossaries(withBootstrapContext(appScope))
|
||||
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.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
|
||||
})
|
||||
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
|
||||
})
|
||||
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, extra...)
|
||||
return commandkit.New(commandkit.Identity{Name: "audita", Version: buildinfo.Version()}, declarations...)
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
@@ -96,15 +98,15 @@ func TestPromptConfigurationComparisonAcquiresEqualSelectionsIndependently(t *te
|
||||
}
|
||||
}
|
||||
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)
|
||||
writeProfile("after")
|
||||
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},
|
||||
}}
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
|
||||
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: "schema_version: maximumdirect.glossary.v1\ncollections: {one: {entries: []}}\n", second: "schema_version: maximumdirect.glossary.v1\ncollections: {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) {
|
||||
dir := t.TempDir()
|
||||
file := filepath.Join(dir, "config.yml")
|
||||
@@ -192,11 +220,15 @@ collections:
|
||||
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(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...)
|
||||
if outcome.Status != 0 || !strings.Contains(out, "teh cat") {
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationBootstrapReportsAndPreservesFailure(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
secrets := filepath.Join(dir, "secrets")
|
||||
if err := os.Mkdir(secrets, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("AUDITA_BOOTSTRAP_TEST", "prior")
|
||||
if err := os.WriteFile(filepath.Join(secrets, "AUDITA_BOOTSTRAP_TEST"), []byte("synthetic-secret"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
main := filepath.Join(dir, "config.yml")
|
||||
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: secrets\n secrets_overwrite: true\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app, err := buildApplication()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--verbose"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if result.Status != 0 || os.Getenv("AUDITA_BOOTSTRAP_TEST") != "synthetic-secret" || !strings.Contains(stderr.String(), "AUDITA_BOOTSTRAP_TEST") || strings.Contains(stderr.String(), "synthetic-secret") {
|
||||
t.Fatalf("status=%d stdout=%q stderr=%q", result.Status, out.String(), stderr.String())
|
||||
}
|
||||
if err := os.WriteFile(main, []byte("version: 3\nconfig:\n secrets_dir: missing\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
result = app.Execute(context.Background(), []string{"config", "show", "--scope", "app", "--config", main, "--quiet"}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
var native *ck.SecretsError
|
||||
if result.Status != 1 || !errors.As(result.Cause, &native) || !strings.Contains(stderr.String(), "secrets.") || strings.Contains(stderr.String(), "synthetic-secret") {
|
||||
t.Fatalf("status=%d cause=%v stdout=%q stderr=%q", result.Status, result.Cause, out.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
117
internal/cli/bootstrap.go
Normal file
117
internal/cli/bootstrap.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
type bootstrapReporterKey struct{}
|
||||
|
||||
func bootstrapFeature() commandkit.InvocationFeature {
|
||||
return commandkit.NewInvocationFeature(commandkit.InvocationFeatureSpec[struct{}]{
|
||||
Start: func(inv commandkit.Invocation, _ struct{}) (context.Context, func() commandkit.Report) {
|
||||
return context.WithValue(inv.Context, bootstrapReporterKey{}, inv.Reporter()), nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type bootstrapError struct {
|
||||
cause error
|
||||
report *ck.SecretsReport
|
||||
}
|
||||
|
||||
func (e *bootstrapError) Error() string {
|
||||
var output bytes.Buffer
|
||||
fmt.Fprintln(&output, e.cause)
|
||||
var native *ck.SecretsError
|
||||
if errors.As(e.cause, &native) {
|
||||
for _, diagnostic := range native.Diagnostics() {
|
||||
fmt.Fprintf(&output, "%s: %s\n", diagnostic.Code, diagnostic.Message)
|
||||
}
|
||||
}
|
||||
if e.report != nil {
|
||||
_, _ = e.report.WriteTo(&output)
|
||||
}
|
||||
return output.String()
|
||||
}
|
||||
|
||||
func (e *bootstrapError) Unwrap() error { return e.cause }
|
||||
|
||||
func reportBootstrap(ctx context.Context, report *ck.SecretsReport, err error) error {
|
||||
var native *ck.SecretsError
|
||||
if errors.As(err, &native) {
|
||||
return &bootstrapError{cause: err, report: report}
|
||||
}
|
||||
if report != nil && len(report.Entries()) > 0 {
|
||||
if reporter, ok := ctx.Value(bootstrapReporterKey{}).(*commandkit.Reporter); ok {
|
||||
_ = reporter.Info("Secrets bootstrap", func(w io.Writer) error {
|
||||
_, writeErr := report.WriteTo(w)
|
||||
return writeErr
|
||||
})
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// withBootstrapContext retains safe bootstrap evidence in configuration outcomes.
|
||||
func withBootstrapContext[I, S any](scope ckconfig.Scope[I, S]) ckconfig.Scope[I, S] {
|
||||
acquire := scope.Acquire
|
||||
scope.Acquire = func(ctx context.Context, request ckconfig.Request, input I, state S) (commandkit.Acquired[ckconfig.View], error) {
|
||||
result, err := acquire(ctx, request, input, state)
|
||||
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||
return result, err
|
||||
}
|
||||
compare := scope.Compare
|
||||
scope.Compare = func(ctx context.Context, request ckconfig.ComparisonRequest[I], state S) (commandkit.Acquired[[]ck.Difference], error) {
|
||||
result, err := compare(ctx, request, state)
|
||||
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||
return result, err
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func bootstrapExplanation(explanation commandkit.Explanation, err error) commandkit.Explanation {
|
||||
var failure *bootstrapError
|
||||
if errors.As(err, &failure) {
|
||||
explanation.Details = append(explanation.Details, func(w io.Writer) error {
|
||||
_, writeErr := io.WriteString(w, failure.Error())
|
||||
return writeErr
|
||||
})
|
||||
}
|
||||
return explanation
|
||||
}
|
||||
|
||||
func withBootstrapAcquisition[R, I, S, T any](load func(context.Context, R, I, S) (commandkit.Acquired[T], error)) func(context.Context, R, I, S) (commandkit.Acquired[T], error) {
|
||||
if load == nil {
|
||||
return nil
|
||||
}
|
||||
return func(ctx context.Context, request R, input I, state S) (commandkit.Acquired[T], error) {
|
||||
result, err := load(ctx, request, input, state)
|
||||
result.Explanation = bootstrapExplanation(result.Explanation, err)
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
|
||||
func withPromptBootstrapContext[I, S any](suite ckprompt.Suite[I, S]) ckprompt.Suite[I, S] {
|
||||
suite.InspectPrompt = withBootstrapAcquisition(suite.InspectPrompt)
|
||||
suite.InspectProfile = withBootstrapAcquisition(suite.InspectProfile)
|
||||
suite.InspectBackend = withBootstrapAcquisition(suite.InspectBackend)
|
||||
suite.InspectRequirements = withBootstrapAcquisition(suite.InspectRequirements)
|
||||
suite.ValidateRequest = withBootstrapAcquisition(suite.ValidateRequest)
|
||||
suite.PrepareRequest = withBootstrapAcquisition(suite.PrepareRequest)
|
||||
suite.SmokeTest = withBootstrapAcquisition(suite.SmokeTest)
|
||||
suite.ListPrompts = withBootstrapAcquisition(suite.ListPrompts)
|
||||
suite.ListProfiles = withBootstrapAcquisition(suite.ListProfiles)
|
||||
suite.ListBackends = withBootstrapAcquisition(suite.ListBackends)
|
||||
suite.ListNamespaces = withBootstrapAcquisition(suite.ListNamespaces)
|
||||
suite.ListCollections = withBootstrapAcquisition(suite.ListCollections)
|
||||
return suite
|
||||
}
|
||||
136
internal/cli/bootstrap_test.go
Normal file
136
internal/cli/bootstrap_test.go
Normal 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 }
|
||||
@@ -6,18 +6,23 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"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/framework/llm"
|
||||
auditaprompts "gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
||||
@@ -33,15 +38,48 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
||||
} {
|
||||
t.Run(tc.dir+"/"+tc.main, func(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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")
|
||||
}
|
||||
var glossaryFiles []string
|
||||
if tc.dir != "service" {
|
||||
glossaryFiles = []string{filepath.Join(root, tc.dir, "glossary.yml")}
|
||||
}
|
||||
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, appconfig.Options{Overlay: tc.overlay, GlossaryFiles: glossaryFiles})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded.Config.Reporting.Enabled = false
|
||||
loaded.Config.Application.Reporting.Enabled = false
|
||||
var calls atomic.Int32
|
||||
var mu sync.Mutex
|
||||
var models, prompts []string
|
||||
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)
|
||||
var request struct {
|
||||
Model string `json:"model"`
|
||||
@@ -62,7 +100,7 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
||||
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
|
||||
})
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -74,21 +112,27 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
|
||||
if err != nil {
|
||||
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{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
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())
|
||||
}
|
||||
if tc.dir == "service" && (len(models) != 1 || models[0] != "example-testing-model") {
|
||||
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 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)
|
||||
@@ -120,11 +164,11 @@ func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
|
||||
}
|
||||
}
|
||||
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{GlossaryFiles: []string{filepath.Join(dir, "glossary.yml")}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
engine, err := llm.NewRuntime(context.Background(), loaded, nil)
|
||||
engine, err := llm.NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -148,3 +192,100 @@ func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
|
||||
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, "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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCampaignGlossaryArrangementsAgree(t *testing.T) {
|
||||
_, file, _, ok := runtime.Caller(0)
|
||||
if !ok {
|
||||
t.Fatal("cannot locate examples")
|
||||
}
|
||||
dir := filepath.Join(filepath.Dir(file), "..", "..", "examples", "campaigns")
|
||||
input := ck.Input{Source: ck.File(filepath.Join(dir, "first.yml"))}
|
||||
load := func(names ...string) *appconfig.Acquisition {
|
||||
t.Helper()
|
||||
var files []string
|
||||
for _, name := range names {
|
||||
files = append(files, filepath.Join(dir, name))
|
||||
}
|
||||
result, _, err := appconfig.Load(context.Background(), input, appconfig.Options{GlossaryFiles: files})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
combined := load("glossary.yml").Config.Application.GlossaryCollections
|
||||
separate := load("party.yml", "spells.yml").Config.Application.GlossaryCollections
|
||||
if !reflect.DeepEqual(combined, separate) {
|
||||
t.Fatalf("combined=%+v separate=%+v", combined, separate)
|
||||
}
|
||||
}
|
||||
|
||||
136
internal/cli/preflight.go
Normal file
136
internal/cli/preflight.go
Normal 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"
|
||||
}
|
||||
303
internal/cli/preflight_test.go
Normal file
303
internal/cli/preflight_test.go
Normal 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": "schema_version: maximumdirect.glossary.v1\ncollections: {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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,10 @@ import (
|
||||
"fmt"
|
||||
"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/reporting"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
@@ -26,29 +25,11 @@ type processResult struct {
|
||||
func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcome {
|
||||
loaded, err := loadProcessInputs(inv.Context, input, inv.ReportingMode())
|
||||
if err != nil {
|
||||
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 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)
|
||||
return acquisitionOutcome(inv, err)
|
||||
}
|
||||
prepared, err := prepareProcess(inv.Context, input, loaded, inv.Reporter().Output())
|
||||
if err != nil {
|
||||
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)
|
||||
return preparationOutcome(inv, err)
|
||||
}
|
||||
defer prepared.Prepared.Output.Close()
|
||||
var warningsMu sync.Mutex
|
||||
@@ -65,14 +46,9 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
|
||||
warn(debug.WriteSourceTranscript(loaded.Source, loaded.RawTranscript))
|
||||
}
|
||||
loaded.RawTranscript = nil
|
||||
cfg := &loaded.Configuration.Config
|
||||
normalizer := normalization.NewNormalizer(normalization.NormalizationConfig{
|
||||
MaxSegmentGap: cfg.Normalization.MaxSegmentGap, EllipsisGap: cfg.Normalization.EllipsisGap,
|
||||
MaxSegmentDuration: cfg.Normalization.MaxSegmentDuration, MaxSegmentTokens: cfg.Normalization.MaxSegmentTokens,
|
||||
})
|
||||
transcript := loaded.Source.Canonical()
|
||||
cfg := &loaded.Configuration.Config.Application
|
||||
normalized, summary := prepared.Invocation.Plan.Transcript, prepared.Invocation.Plan.Summary
|
||||
loaded.Source = nil
|
||||
normalized, summary := normalizer.Normalize(transcript)
|
||||
if debug != nil {
|
||||
warn(debug.WriteNormalizedTranscript(normalized))
|
||||
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})
|
||||
}
|
||||
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)
|
||||
})
|
||||
if runErr != nil {
|
||||
@@ -108,3 +84,37 @@ func (p *preparedProcess) DebugPath() string {
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -9,17 +9,20 @@ import (
|
||||
)
|
||||
|
||||
type processInput struct {
|
||||
Config commandkit.Supplied[string]
|
||||
Overlay commandkit.Supplied[string]
|
||||
Transcript string
|
||||
Output commandkit.Supplied[string]
|
||||
Debug commandkit.Supplied[bool]
|
||||
Overrides []ck.Override
|
||||
Config commandkit.Supplied[string]
|
||||
Overlay commandkit.Supplied[string]
|
||||
Transcript string
|
||||
Output commandkit.Supplied[string]
|
||||
Debug commandkit.Supplied[bool]
|
||||
Smoke commandkit.Supplied[bool]
|
||||
Overrides []ck.Override
|
||||
GlossaryFiles []string
|
||||
}
|
||||
|
||||
func processCommand() commandkit.Command {
|
||||
func processingFlags() []commandkit.Flag[processInput] {
|
||||
stringValue := func(s string) (string, error) { return s, nil }
|
||||
flags := []commandkit.Flag[processInput]{
|
||||
commandkit.RepeatFlag(commandkit.FlagMeta{Name: "glossary-file", Usage: "Shared glossary YAML or JSON 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: "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 }),
|
||||
@@ -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"})
|
||||
}
|
||||
}))
|
||||
return commandkit.NewCommand(commandkit.CommandSpec[processInput]{Name: "process", Summary: "Polish a transcript.", Flags: flags, Run: runProcess,
|
||||
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 })},
|
||||
})
|
||||
return flags
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"path/filepath"
|
||||
"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"
|
||||
coreio "gitea.maximumdirect.net/eric/audita/v4/internal/core/io"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
||||
@@ -26,25 +26,38 @@ import (
|
||||
)
|
||||
|
||||
type processInputs struct {
|
||||
Configuration *ck.Result[config.Config]
|
||||
Configuration *ck.Result[appconfig.Config]
|
||||
Runtime *llm.Runtime
|
||||
Source *schema.SourceTranscript
|
||||
RawTranscript []byte
|
||||
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 == "" {
|
||||
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}
|
||||
loaded, err := loadApplication(ctx, selection, struct{}{}, nil)
|
||||
acquired, err := acquireApplication(ctx, selection, acquisitionInput{GlossaryFiles: input.GlossaryFiles})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
loaded := acquired.Result
|
||||
runtime, err := llm.NewRuntime(ctx, loaded, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, &runtimePreparationError{cause: err}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
@@ -64,6 +77,7 @@ func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.
|
||||
raw = nil
|
||||
}
|
||||
protected := append([]string(nil), runtime.SourcePaths...)
|
||||
protected = append(protected, acquired.GlossarySources...)
|
||||
for _, entry := range loaded.Sources() {
|
||||
if entry.Kind == ck.SourceKindFile && 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.
|
||||
type preparedProcess struct {
|
||||
Prepared *preflight.Prepared
|
||||
RunID string
|
||||
Started time.Time
|
||||
Prepared *preparedOutput
|
||||
Invocation *preparedInvocation
|
||||
RunID string
|
||||
Started time.Time
|
||||
}
|
||||
|
||||
func prepareProcess(ctx context.Context, input processInput, loaded *processInputs, stdout io.Writer) (*preparedProcess, error) {
|
||||
cfg := &loaded.Configuration.Config
|
||||
type preparedInvocation struct {
|
||||
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 := ""
|
||||
reportDirSet := false
|
||||
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()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -120,42 +183,21 @@ func prepareProcess(ctx context.Context, input processInput, loaded *processInpu
|
||||
return renderReportBundle(processreport.Failed(failedSnapshot, primary, "initialization", failures))
|
||||
}
|
||||
}
|
||||
var debug *preflight.DebugInput
|
||||
var debug *debugInput
|
||||
var warnings []error
|
||||
if input.Debug.Value {
|
||||
var effective bytes.Buffer
|
||||
if err := loaded.Configuration.WriteEffective(&effective); err != nil {
|
||||
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 := 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})
|
||||
prepared, err := prepareOutput(ctx, local.Destinations, initial, failed, debug)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package cli
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -9,6 +10,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight"
|
||||
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
"sync"
|
||||
"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/schema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
||||
@@ -72,11 +72,6 @@ func TestProcessingUsesPerEntryProfilesInOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
files := map[string]string{
|
||||
"config.yml": `version: 3
|
||||
glossary_collections:
|
||||
party:
|
||||
entries: [{id: alice, name: Alice, category: person}]
|
||||
spells:
|
||||
entries: [{id: shield, name: Shield, category: spell}]
|
||||
protected_terms: [party, spells]
|
||||
llm: {validation_profile: review}
|
||||
pipeline:
|
||||
@@ -92,6 +87,15 @@ pipeline:
|
||||
- module: grammar
|
||||
glossaries: [party, spells]
|
||||
llm: {proposal_profile: three}
|
||||
`,
|
||||
"shared.yml": `schema_version: maximumdirect.glossary.v1
|
||||
collections:
|
||||
party:
|
||||
entries: [{id: alice, name: Alice, category: person}]
|
||||
spells:
|
||||
entries: [{id: shield, name: Shield, category: spell}]
|
||||
unused:
|
||||
entries: [{id: unused, name: Unselected, category: topic}]
|
||||
`,
|
||||
"prompts.yml": fmt.Sprintf("profiles:\n - {id: one, endpoint: %q, model: model-one, api_key_required: false}\n - {id: two, endpoint: %q, model: model-two, api_key_required: false}\n - {id: three, endpoint: %q, model: model-three, api_key_required: false}\n - {id: review, endpoint: %q, model: review, api_key_required: false}\n", "https://example.invalid/v1", "https://example.invalid/v1", "https://example.invalid/v1", "https://example.invalid/v1"),
|
||||
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"Alyce casts Sheeld."}]`,
|
||||
@@ -101,11 +105,11 @@ pipeline:
|
||||
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{GlossaryFiles: []string{filepath.Join(dir, "shared.yml")}})
|
||||
if err != nil {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -113,15 +117,28 @@ pipeline:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
||||
loaded.Config.Diagnostics.WorkDir = dir
|
||||
loaded.Config.Reporting.StdoutDir = dir
|
||||
inputs := &processInputs{Configuration: loaded.Result, Runtime: runtime, Source: source}
|
||||
loaded.Config.Application.Diagnostics.WorkDir = 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{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer prepared.Prepared.Output.Close()
|
||||
result, err := executePipeline(context.Background(), inputs, prepared, source.Canonical(), func(error) {}, nil)
|
||||
specs := prepared.Invocation.Plan.Specs
|
||||
if len(specs[0].Glossary) != 1 || specs[0].Glossary[0].Name != "Alice" || len(specs[1].Glossary) != 1 || specs[1].Glossary[0].Name != "Shield" {
|
||||
t.Fatalf("selected glossary views: %+v %+v", specs[0].Glossary, specs[1].Glossary)
|
||||
}
|
||||
protectedShield := false
|
||||
for _, term := range specs[0].ProtectedTerms {
|
||||
if term.Spelling == "Shield" && !term.Exempt {
|
||||
protectedShield = true
|
||||
}
|
||||
}
|
||||
if !protectedShield {
|
||||
t.Fatalf("missing protected spell: %+v", specs[0].ProtectedTerms)
|
||||
}
|
||||
result, err := executePipeline(context.Background(), prepared, func(error) {}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -213,14 +230,14 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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
|
||||
})
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -228,14 +245,14 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
|
||||
loaded.Config.Reporting.StdoutDir = dir
|
||||
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(), inputs, prepared, source.Canonical(), func(error) {}, nil)
|
||||
result, err := executePipeline(context.Background(), prepared, func(error) {}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -243,3 +260,64 @@ func TestRecoverableModelFailureKeepsNormalizedTranscript(t *testing.T) {
|
||||
t.Fatalf("result=%+v errors=%+v", result.Transcript, result.Snapshot.Errors)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
files := map[string]string{
|
||||
"config.yml": "version: 3\nllm: {validation_profile: review}\npipeline:\n stages:\n - module: grammar\n llm: {proposal_profile: invalid}\n - module: homophones\n llm: {proposal_profile: good}\n",
|
||||
"prompts.yml": "profiles:\n - {id: invalid, endpoint: 'https://example.invalid/v1', model: invalid, api_key_required: false}\n - {id: good, endpoint: 'https://example.invalid/v1', model: good, api_key_required: false}\n - {id: review, endpoint: 'https://example.invalid/v1', model: review, api_key_required: false}\ncollections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: [{role: user, content: 'operator prompt'}]\n output: {format: text, validation_mode: none}\n",
|
||||
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"helo"}]`,
|
||||
}
|
||||
for name, value := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"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/reporting"
|
||||
"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)
|
||||
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)
|
||||
}
|
||||
_ = reporter.AtEnd().Info(reporting.CompletionLine(snapshot))
|
||||
|
||||
@@ -156,7 +156,7 @@ func TestCanceledEmptyPipelineLeavesTranscriptAndFinalizesReports(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
|
||||
"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/schema"
|
||||
"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/processreport"
|
||||
@@ -15,9 +14,10 @@ import (
|
||||
"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) {
|
||||
cfg := &loaded.Configuration.Config
|
||||
specs := prepared.Prepared.Specs
|
||||
func executePipeline(ctx context.Context, prepared *preparedProcess, warn func(error), progress func(string)) (processResult, error) {
|
||||
loaded := prepared.Invocation.Loaded
|
||||
cfg := prepared.Invocation.Plan.Config
|
||||
specs := prepared.Invocation.Plan.Specs
|
||||
debug := prepared.Prepared.Debug
|
||||
evidence := runner.EvidenceSelection{Reports: cfg.Reporting.Enabled, Debug: debug != nil}
|
||||
var observer *llm.ObservationCollector
|
||||
@@ -62,7 +62,7 @@ func executePipeline(ctx context.Context, loaded *processInputs, prepared *prepa
|
||||
interactions = writer
|
||||
}
|
||||
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),
|
||||
})
|
||||
if debug != nil {
|
||||
|
||||
49
internal/cli/process_prepare_output.go
Normal file
49
internal/cli/process_prepare_output.go
Normal 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
|
||||
}
|
||||
@@ -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) {
|
||||
main := writeRuntimeErrorConfig(t, "profiles: []\n")
|
||||
companion := filepath.Join(filepath.Dir(main), "prompts.yml")
|
||||
|
||||
297
internal/cli/runtime_glossary_test.go
Normal file
297
internal/cli/runtime_glossary_test.go
Normal file
@@ -0,0 +1,297 @@
|
||||
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}]\nschema_version: maximumdirect.glossary.v1\ncollections: {party: {entries: []}}\n", imported),
|
||||
imported: "collections: {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": "schema_version: maximumdirect.glossary.v1\ncollections: {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": "schema_version: maximumdirect.glossary.v1\ncollections: {party: {entries: [{id: c, name: Runtime, category: C}]}}\n",
|
||||
"bad.yml": "party: [\n",
|
||||
"invalid.yml": "schema_version: wrong\ncollections: {}\n",
|
||||
"empty-shared.yml": "schema_version: maximumdirect.glossary.v1\ncollections: {}\n",
|
||||
"additional.yml": "schema_version: maximumdirect.glossary.v1\ncollections: {extra: {entries: [{id: d, name: Additional, category: C}]}}\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")
|
||||
additional := filepath.Join(dir, "additional.yml")
|
||||
code, out, stderr := run("config", "show", "--scope=app", "--config", main, "--glossary-file", file, "--glossary-file", additional)
|
||||
if code != 0 || !strings.Contains(out, "Runtime") || !strings.Contains(out, "Additional") || 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, "--glossary-file", additional)
|
||||
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)
|
||||
}
|
||||
}
|
||||
code, _, stderr = run("config", "show", "--scope=app", "--config", main, "--glossary-file", filepath.Join(dir, "empty-shared.yml"))
|
||||
if code != 0 {
|
||||
t.Fatalf("empty shared inspection: %d %s", code, stderr)
|
||||
}
|
||||
for _, args := range [][]string{{"config", "show", "--scope=app"}, {"promptkit", "list", "prompts"}} {
|
||||
args = append(args, "--config", main, "--glossary-file", filepath.Join(dir, "invalid.yml"))
|
||||
code, _, stderr = run(args...)
|
||||
if code != 2 || !strings.Contains(stderr, "invalid.yml") || !strings.Contains(stderr, "schema_version") {
|
||||
t.Fatalf("invalid shared data %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}]}\nschema_version: maximumdirect.glossary.v1\ncollections: {party: {entries: [{id: a, name: Incoming, category: C}]}}\n",
|
||||
filepath.Join(invocation, "imported.yml"): "collections: {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())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedGlossaryReadinessBeforeRequests(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()
|
||||
files := map[string]string{
|
||||
"config.yml": "version: 3\nglossaries: [party]\nllm: {proposal_profile: fixture, validation_profile: fixture}\npipeline: {stages: [{module: glossary}]}\nreporting: {enabled: false}\n",
|
||||
"prompts.yml": fmt.Sprintf("profiles: [{id: fixture, endpoint: '%s/v1', model: fixture, api_key_required: false}]\n", server.URL),
|
||||
"input.json": `[{"speaker":"A","start":0,"end":1,"text":"hello"}]`,
|
||||
"good.yml": "schema_version: maximumdirect.glossary.v1\ncollections: {party: {entries: [{id: a, name: Alice, category: person}]}, other: {entries: []}}\n",
|
||||
"empty.yml": "schema_version: maximumdirect.glossary.v1\ncollections: {party: {entries: []}}\n",
|
||||
"invalid.yml": "schema_version: wrong\ncollections: {}\n",
|
||||
}
|
||||
for name, body := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, command := range []string{"preflight", "process"} {
|
||||
for _, tc := range []struct {
|
||||
file string
|
||||
extra []string
|
||||
wantStatus int
|
||||
}{
|
||||
{"invalid.yml", nil, 2},
|
||||
{"empty.yml", nil, 2},
|
||||
{"good.yml", []string{"--glossaries", `["missing"]`}, 2},
|
||||
} {
|
||||
args := []string{command, "--config", filepath.Join(dir, "config.yml"), "--glossary-file", filepath.Join(dir, tc.file), "--output", filepath.Join(dir, "out.json")}
|
||||
args = append(args, tc.extra...)
|
||||
args = append(args, filepath.Join(dir, "input.json"))
|
||||
var stdout, stderr bytes.Buffer
|
||||
if status := Run(context.Background(), args, &stdout, &stderr); status != tc.wantStatus || calls.Load() != 0 {
|
||||
t.Fatalf("%s %s: status=%d calls=%d stderr=%s", command, tc.file, status, calls.Load(), stderr.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
var stdout, stderr bytes.Buffer
|
||||
status := Run(context.Background(), []string{"preflight", "--smoke=false", "--config", filepath.Join(dir, "config.yml"), "--glossary-file", filepath.Join(dir, "good.yml"), "--output", filepath.Join(dir, "out.json"), filepath.Join(dir, "input.json")}, &stdout, &stderr)
|
||||
if status != 0 || calls.Load() != 0 {
|
||||
t.Fatalf("local preflight: status=%d calls=%d stderr=%s", status, calls.Load(), stderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSharedGlossaryWithDisjointNativeOverrides(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
main := filepath.Join(dir, "config.yml")
|
||||
if err := os.WriteFile(main, []byte("version: 3\nglossary_collections:\n people:\n entries: [{id: configured, name: Configured, category: person}]\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct{ name, collections, wantName string }{
|
||||
{"populated", "{people: {entries: [{id: a, name: Alice, category: person}]}}", "Alice"},
|
||||
{"empty", "{}", "Configured"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
file := filepath.Join(dir, tc.name+".yml")
|
||||
if err := os.WriteFile(file, []byte("schema_version: maximumdirect.glossary.v1\ncollections: "+tc.collections+"\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
common := []string{"--scope=app", "--config", main, "--glossary-file", file, "--set", `/glossary_collections/other/entries=[{"id":"b","name":"Bob","category":"person"}]`}
|
||||
var out, stderr bytes.Buffer
|
||||
if code := Run(context.Background(), append([]string{"config", "show"}, common...), &out, &stderr); code != 0 || !strings.Contains(out.String(), "name: "+tc.wantName) || !strings.Contains(out.String(), "name: Bob") {
|
||||
t.Fatalf("show: code=%d out=%s stderr=%s", code, out.String(), stderr.String())
|
||||
}
|
||||
for _, origin := range []struct{ path, flag string }{
|
||||
{"/glossary_collections/other/entries", "--set"},
|
||||
{"/glossary_collections/people/entries", "--glossary-file"},
|
||||
} {
|
||||
if tc.name == "empty" && origin.flag == "--glossary-file" {
|
||||
continue
|
||||
}
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
args := append([]string{"config", "explain"}, common...)
|
||||
args = append(args, "--path", origin.path)
|
||||
if code := Run(context.Background(), args, &out, &stderr); code != 0 || !strings.Contains(out.String(), origin.flag) {
|
||||
t.Fatalf("explain: code=%d out=%s stderr=%s", code, out.String(), stderr.String())
|
||||
}
|
||||
}
|
||||
if tc.name == "populated" {
|
||||
out.Reset()
|
||||
stderr.Reset()
|
||||
args := append([]string{"config", "show"}, common...)
|
||||
args = append(args, "--set", `/glossary_collections/people={"entries":[]}`)
|
||||
if code := Run(context.Background(), args, &out, &stderr); code != 2 || !strings.Contains(stderr.String(), "override.overlap") {
|
||||
t.Fatalf("overlap: code=%d stderr=%s", code, stderr.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
72
internal/cli/schema_collision_test.go
Normal file
72
internal/cli/schema_collision_test.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
commandkit "go.maximumdirect.net/commandkit"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProcessingProtectsOperatorSchemas(t *testing.T) {
|
||||
for _, mode := range []string{"transcript", "report", "separate"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
fmt.Fprint(w, `{"choices":[{"message":{"content":"{\"corrections\":[]}"}}]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
schemaName := "contract.json"
|
||||
if mode == "report" {
|
||||
schemaName = "errors.yml"
|
||||
}
|
||||
schema := filepath.Join(dir, schemaName)
|
||||
original := `{"type":"object","required":["corrections"],"properties":{"corrections":{"type":"array"}}}`
|
||||
files := map[string]string{
|
||||
"config.yml": "version: 3\nllm: {proposal_profile: fixture}\npipeline:\n stages: [{module: grammar}]\n",
|
||||
"input.json": `[{"speaker":"Alice","start":0,"end":1,"text":"Hello."}]`,
|
||||
schemaName: original,
|
||||
"prompts.yml": fmt.Sprintf("profiles:\n - id: fixture\n endpoint: %s/v1\n model: test\n api_key_required: false\ncollections:\n audita:\n prompts:\n - id: modules.grammar.proposal\n messages: [{role: user, content: Return an empty correction set.}]\n output:\n format: json\n validation_mode: json_schema\n schema_file: %s\n", server.URL, schemaName),
|
||||
}
|
||||
for name, data := range files {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(data), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
output := filepath.Join(dir, "output.json")
|
||||
if mode == "transcript" {
|
||||
output = schema
|
||||
}
|
||||
app, err := buildApplication()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, stderr bytes.Buffer
|
||||
result := app.Execute(context.Background(), []string{"process", "--config", filepath.Join(dir, "config.yml"), "--output", output, filepath.Join(dir, "input.json")}, commandkit.Streams{Out: &out, Err: &stderr})
|
||||
if mode == "separate" {
|
||||
if result.Status != 0 || calls.Load() != 1 {
|
||||
t.Fatalf("status=%d calls=%d err=%s", result.Status, calls.Load(), stderr.String())
|
||||
}
|
||||
} else {
|
||||
if result.Status == 0 || calls.Load() != 0 || !strings.Contains(stderr.String(), "conflicts with input") {
|
||||
t.Fatalf("status=%d calls=%d err=%s", result.Status, calls.Load(), stderr.String())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "recoveries.yml")); !os.IsNotExist(err) {
|
||||
t.Fatalf("report created before collision check: %v", err)
|
||||
}
|
||||
}
|
||||
raw, err := os.ReadFile(schema)
|
||||
if err != nil || string(raw) != original {
|
||||
t.Fatalf("schema changed: %s %v", raw, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,8 @@ type Config struct {
|
||||
}
|
||||
|
||||
type GlossaryCollection struct {
|
||||
Entries []GlossaryEntry `yaml:"entries"`
|
||||
Instruction string `yaml:"instruction"`
|
||||
Entries []GlossaryEntry `yaml:"entries"`
|
||||
}
|
||||
type GlossaryEntry struct {
|
||||
ID string `yaml:"id"`
|
||||
@@ -50,7 +51,6 @@ type LLM struct {
|
||||
CorrectionRepairProfile *string `yaml:"correction_repair_profile"`
|
||||
CorrectionRepairAttempts int `yaml:"correction_repair_attempts"`
|
||||
TransientRetries int `yaml:"transient_retries"`
|
||||
RepairAttempts int `yaml:"repair_attempts"`
|
||||
OperationTimeout time.Duration `yaml:"operation_timeout"`
|
||||
}
|
||||
type Pipeline struct {
|
||||
@@ -96,7 +96,7 @@ type Reporting struct {
|
||||
func defaults() Config {
|
||||
return Config{
|
||||
Version: 3,
|
||||
LLM: LLM{TransientRetries: 2, RepairAttempts: 2, CorrectionRepairAttempts: 1, OperationTimeout: 15 * time.Minute},
|
||||
LLM: LLM{TransientRetries: 2, CorrectionRepairAttempts: 1, OperationTimeout: 15 * time.Minute},
|
||||
Pipeline: Pipeline{Stages: []Stage{{Module: "glossary"}, {Module: "homophones"}, {Module: "glossary"}, {Module: "spoken_word"}, {Module: "grammar"}}},
|
||||
Output: Output{Schema: "bare-segments"},
|
||||
Validation: Validation{MaxPromptTokens: DefaultValidationMaxPromptTokens},
|
||||
@@ -107,37 +107,27 @@ func defaults() Config {
|
||||
}
|
||||
}
|
||||
|
||||
const glossaryImports = `config:
|
||||
imports:
|
||||
- path: glossary.yml
|
||||
required: false
|
||||
destination: [glossary_collections]
|
||||
- dir: glossary
|
||||
required: false
|
||||
recursive: true
|
||||
pattern: ["*.yml", "*.yaml"]
|
||||
destination: [glossary_collections]
|
||||
`
|
||||
// GlossaryEntryIdentity identifies entries beneath a collections mapping.
|
||||
func GlossaryEntryIdentity(prefix ck.SequenceSelector) ck.SequenceIdentity {
|
||||
selector := append(ck.SequenceSelector(nil), prefix...)
|
||||
selector = append(selector, ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries"))
|
||||
return ck.SequenceIdentityMatching(selector, "id")
|
||||
}
|
||||
|
||||
// Load resolves the selected main source and preserves native source evidence.
|
||||
func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) {
|
||||
input.Imports = true
|
||||
return ck.LoadLayered(input, ck.LayeredOptions[Config]{
|
||||
Overlay: overlay, Overrides: overrides,
|
||||
Underlays: []ck.Underlay{{Inputs: []ck.Input{{Source: ck.Bytes("Audita glossary imports", []byte(glossaryImports)), Imports: true, MainRelative: ck.MainRelative()}}}},
|
||||
Definition: ck.Definition[Config]{
|
||||
Defaults: defaults,
|
||||
SequenceIdentities: []ck.SequenceIdentity{ck.SequenceIdentityMatching(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections"), ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries")}, "id")},
|
||||
Version: &ck.VersionRule{Path: ck.Keys("version"), Check: func(version ck.Version, v *ck.Validation) error {
|
||||
if version.Present && (version.Null || version.Text != "3") {
|
||||
v.Error(ck.Keys("version"), "use application configuration version 3; see docs/migrations/v3.md")
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
Resolve: resolveSettings,
|
||||
Validate: validate,
|
||||
},
|
||||
})
|
||||
// Definition describes the application settings independently of their sources.
|
||||
func Definition() ck.Definition[Config] {
|
||||
return ck.Definition[Config]{
|
||||
Defaults: defaults,
|
||||
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 {
|
||||
if version.Present && (version.Null || version.Text != "3") {
|
||||
v.Error(ck.Keys("version"), "use application configuration version 3; see docs/migrations/v3.md")
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
Resolve: resolveSettings,
|
||||
Validate: validate,
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
llm := base.Key("llm")
|
||||
check(settings.TransientRetries >= 0, llm.Key("transient_retries"), "retry budget must be non-negative")
|
||||
check(settings.RepairAttempts >= 0 && settings.RepairAttempts <= 3, llm.Key("repair_attempts"), "repair attempts must be between zero and three")
|
||||
check(settings.CorrectionRepairAttempts >= 0, llm.Key("correction_repair_attempts"), "correction repair attempts must be non-negative")
|
||||
check(settings.CorrectionRepairProfile == nil || *settings.CorrectionRepairProfile != "", llm.Key("correction_repair_profile"), "correction repair profile must not be empty; use null to clear it")
|
||||
check(settings.OperationTimeout > 0, llm.Key("operation_timeout"), "operation timeout must be positive")
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"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) {
|
||||
path := filepath.Join(t.TempDir(), "config.yml")
|
||||
for _, tc := range []struct {
|
||||
@@ -156,7 +51,8 @@ func TestSchemaConstraintsAndExplicitValues(t *testing.T) {
|
||||
{"unknown module", "pipeline:\n stages:\n - module: unknown\n", false},
|
||||
{"invalid chunk limit", "chunking:\n target_sections: 0\n", false},
|
||||
{"null group", "llm: null\n", false},
|
||||
{"zero budgets", "llm:\n transient_retries: 0\n repair_attempts: 0\n", true},
|
||||
{"zero retries", "llm:\n transient_retries: 0\n", true},
|
||||
{"retired repair budget", "llm:\n repair_attempts: 0\n", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := os.WriteFile(path, []byte(tc.text), 0644); err != nil {
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
func TestGlossarySourcesComposeAndRetainExtensions(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
write := func(name, data string) {
|
||||
t.Helper()
|
||||
file := filepath.Join(dir, name)
|
||||
if err := os.MkdirAll(filepath.Dir(file), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(data), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("config.yml", `version: 3
|
||||
config:
|
||||
imports: []
|
||||
glossary_collections:
|
||||
party:
|
||||
entries:
|
||||
- id: hero
|
||||
name: Revised
|
||||
category: character
|
||||
level: 5
|
||||
`)
|
||||
write("glossary.yml", `config:
|
||||
imports:
|
||||
- path: shared/extra.yml
|
||||
required: true
|
||||
party:
|
||||
entries:
|
||||
- id: hero
|
||||
name: Original
|
||||
category: character
|
||||
aliases: [Old]
|
||||
- id: other
|
||||
name: Other
|
||||
category: place
|
||||
`)
|
||||
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")
|
||||
result, err := Load(ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
|
||||
if err != nil {
|
||||
t.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics())
|
||||
}
|
||||
party := result.Config.GlossaryCollections["party"].Entries
|
||||
if len(party) != 2 || party[0].Name != "Revised" || len(party[0].Aliases) != 0 || party[1].ID != "other" {
|
||||
t.Fatalf("party=%+v", party)
|
||||
}
|
||||
if party[0].Extra["level"] == nil {
|
||||
t.Fatalf("extension missing: %+v", party[0])
|
||||
}
|
||||
if got := result.Config.GlossaryCollections["lore"].Entries; len(got) != 1 || got[0].ID != "hero" {
|
||||
t.Fatalf("lore=%+v", got)
|
||||
}
|
||||
discovered, err := Load(ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "")
|
||||
if err != nil || len(discovered.Config.GlossaryCollections["party"].Entries) != 2 {
|
||||
t.Fatalf("discovered glossary: %+v %v", discovered, err)
|
||||
}
|
||||
spells := result.Config.GlossaryCollections["spells"].Entries
|
||||
if len(spells) != 1 || spells[0].Plural == nil || *spells[0].Plural != "Bolts" || spells[0].Extra["extra"] == nil {
|
||||
t.Fatalf("spells=%+v", spells)
|
||||
}
|
||||
var paths []string
|
||||
for _, source := range result.Sources() {
|
||||
if source.Kind == ck.SourceKindFile {
|
||||
paths = append(paths, source.Path)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"glossary.yml", "shared/extra.yml", "glossary/nested/spells.yaml"} {
|
||||
if !slices.Contains(paths, filepath.Join(dir, name)) {
|
||||
t.Errorf("missing source %s: %v", name, paths)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
main := filepath.Join(dir, "config.yml")
|
||||
write := func(path, data string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(data), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, data := range []string{
|
||||
"glossary_collections:\n empty: {entries: []}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: 'id with spaces', name: N, category: C}\n",
|
||||
} {
|
||||
write(main, data)
|
||||
if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err != nil {
|
||||
t.Fatalf("valid %q: %v", data, err)
|
||||
}
|
||||
}
|
||||
for _, data := range []string{
|
||||
"glossary_collections:\n x:\n entries:\n - {id: '', name: N, category: C}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: '', category: C}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, aliases: ['']}\n",
|
||||
"glossary_collections:\n x:\n entries:\n - {id: x, name: N, category: C, plural: ''}\n",
|
||||
} {
|
||||
write(main, data)
|
||||
if _, err := Load(ck.Input{Source: ck.File(main)}, ""); err == nil {
|
||||
t.Fatalf("accepted %q", data)
|
||||
}
|
||||
}
|
||||
write(main, "version: 3\n")
|
||||
write(filepath.Join(dir, "glossary.yml"), "x:\n entries:\n - {id: same, name: One, category: C}\n")
|
||||
if err := os.Mkdir(filepath.Join(dir, "glossary"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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 {
|
||||
t.Fatal("peer conflict accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "glossary.yml"), []byte("leak:\n entries:\n - {id: a, name: A, category: C}\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(dir)
|
||||
result, err := Load(ck.Input{Source: ck.NoSource()}, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Config.GlossaryCollections) != 0 {
|
||||
t.Fatalf("unanchored glossary loaded: %+v", result.Config.GlossaryCollections)
|
||||
}
|
||||
}
|
||||
12
internal/core/config/loader_test.go
Normal file
12
internal/core/config/loader_test.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package config
|
||||
|
||||
import ck "go.maximumdirect.net/configkit"
|
||||
|
||||
func Load(input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], error) {
|
||||
input.Imports = true
|
||||
return ck.LoadLayered(input, ck.LayeredOptions[Config]{
|
||||
Definition: Definition(),
|
||||
Overlay: overlay,
|
||||
Overrides: overrides,
|
||||
})
|
||||
}
|
||||
@@ -63,7 +63,6 @@ func resolveSettings(c *Config, r *ck.Resolution) error {
|
||||
proposal := llm.Key("proposal_profile")
|
||||
ck.Default(r, proposal, &item.LLM.ProposalProfile, cloneSelection(c.LLM.ProposalProfile), "inherit proposal profile", rootLLM.Key("proposal_profile"))
|
||||
ck.Default(r, llm.Key("transient_retries"), &item.LLM.TransientRetries, c.LLM.TransientRetries, "inherit retry budget", rootLLM.Key("transient_retries"))
|
||||
ck.Default(r, llm.Key("repair_attempts"), &item.LLM.RepairAttempts, c.LLM.RepairAttempts, "inherit repair budget", rootLLM.Key("repair_attempts"))
|
||||
ck.Default(r, llm.Key("correction_repair_attempts"), &item.LLM.CorrectionRepairAttempts, c.LLM.CorrectionRepairAttempts, "inherit correction repair budget", rootLLM.Key("correction_repair_attempts"))
|
||||
ck.Default(r, llm.Key("operation_timeout"), &item.LLM.OperationTimeout, c.LLM.OperationTimeout, "inherit operation timeout", rootLLM.Key("operation_timeout"))
|
||||
ck.Default(r, base.Key("validation").Key("max_prompt_tokens"), &item.Validation.MaxPromptTokens, c.Validation.MaxPromptTokens, "inherit validation budget", ck.Keys("validation", "max_prompt_tokens"))
|
||||
|
||||
@@ -27,7 +27,6 @@ func TestResolutionCopiesRootOverridesAndHonorsClears(t *testing.T) {
|
||||
glossaries: [party]
|
||||
llm:
|
||||
proposal_profile: A
|
||||
repair_attempts: 2
|
||||
context:
|
||||
description: root
|
||||
pipeline:
|
||||
@@ -36,7 +35,6 @@ pipeline:
|
||||
glossaries: [party]
|
||||
llm:
|
||||
proposal_profile: B
|
||||
repair_attempts: 0
|
||||
context:
|
||||
description: ""
|
||||
- module: grammar
|
||||
@@ -52,7 +50,7 @@ pipeline:
|
||||
if !reflect.DeepEqual(cfg.ProtectedTerms, []string{"spells"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[0].Glossaries, []string{"party"}) || !reflect.DeepEqual(cfg.Pipeline.Stages[1].Glossaries, []string{"spells"}) || len(cfg.Pipeline.Stages[2].Glossaries) != 0 {
|
||||
t.Fatalf("resolved: %+v", cfg)
|
||||
}
|
||||
if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].LLM.RepairAttempts != 0 || cfg.Pipeline.Stages[0].Context.Description != "" {
|
||||
if cfg.Pipeline.Stages[1].ProtectedTerms != nil || cfg.Pipeline.Stages[0].Context.Description != "" {
|
||||
t.Fatalf("clears lost: %+v", cfg.Pipeline.Stages)
|
||||
}
|
||||
if *cfg.Pipeline.Stages[0].LLM.ValidationProfile != "B" || *cfg.Pipeline.Stages[1].LLM.ValidationProfile != "A" {
|
||||
|
||||
71
internal/core/diagnostics/output_probe.go
Normal file
71
internal/core/diagnostics/output_probe.go
Normal 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()
|
||||
}
|
||||
157
internal/core/diagnostics/output_probe_test.go
Normal file
157
internal/core/diagnostics/output_probe_test.go
Normal 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))
|
||||
}
|
||||
}
|
||||
@@ -68,10 +68,20 @@ type OutputSession struct {
|
||||
stdout io.Writer
|
||||
}
|
||||
|
||||
// SelectOutput checks active destinations before any output resources are opened.
|
||||
func SelectOutput(selection OutputSelection) (*OutputSession, error) {
|
||||
session := &OutputSession{enabled: selection.ReportingEnabled, stdout: selection.Stdout}
|
||||
session.replace = session.replaceReport
|
||||
// CheckedDestinations records destination paths and kinds without opening them.
|
||||
type CheckedDestinations struct {
|
||||
transcript string
|
||||
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 {
|
||||
display string
|
||||
path string
|
||||
@@ -89,7 +99,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
|
||||
return destination{display: path, path: resolved, info: info}, nil
|
||||
}
|
||||
var resolvedDir string
|
||||
if session.enabled {
|
||||
if checked.enabled {
|
||||
if strings.TrimSpace(selection.ReportDir) == "" {
|
||||
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() {
|
||||
return nil, fmt.Errorf("transcript output %q is a directory", target.display)
|
||||
}
|
||||
session.transcript, session.publishPath = target.display, target.path
|
||||
session.direct = target.info != nil && !target.info.Mode().IsRegular()
|
||||
checked.transcript, checked.publishPath = target.display, target.path
|
||||
checked.direct = target.info != nil && !target.info.Mode().IsRegular()
|
||||
active = append(active, target)
|
||||
}
|
||||
if session.enabled {
|
||||
if checked.enabled {
|
||||
label := selection.ReportDir
|
||||
if !os.IsPathSeparator(label[len(label)-1]) {
|
||||
label += string(filepath.Separator)
|
||||
@@ -133,7 +143,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
|
||||
if target.info != nil && !target.info.Mode().IsRegular() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
if len(active) == 0 {
|
||||
return session, nil
|
||||
return checked, nil
|
||||
}
|
||||
var protected []destination
|
||||
for _, path := range selection.ProtectedPaths {
|
||||
@@ -154,7 +164,7 @@ func SelectOutput(selection OutputSelection) (*OutputSession, error) {
|
||||
}
|
||||
}
|
||||
var input destination
|
||||
if session.enabled && selection.InputTranscriptPath != "" {
|
||||
if checked.enabled && selection.InputTranscriptPath != "" {
|
||||
var err error
|
||||
input, err = check(selection.InputTranscriptPath)
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
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.
|
||||
func PrepareOutput(selection OutputSelection) (*OutputSession, error) {
|
||||
session, err := SelectOutput(selection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
// NewOutputSession constructs a session without acquiring output resources.
|
||||
func NewOutputSession(checked *CheckedDestinations) *OutputSession {
|
||||
session := &OutputSession{
|
||||
transcript: checked.transcript, publishPath: checked.publishPath,
|
||||
reports: checked.reports, reportDestinations: checked.reportDestinations,
|
||||
enabled: checked.enabled, direct: checked.direct, stdout: checked.stdout,
|
||||
}
|
||||
if err := session.Prepare(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
session.replace = session.replaceReport
|
||||
return session
|
||||
}
|
||||
|
||||
// Prepare opens a sibling temporary file for regular transcript output.
|
||||
|
||||
@@ -33,20 +33,20 @@ func TestPrepareOutputAllowsInPlaceTranscriptButRejectsReportCollisions(t *testi
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
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")
|
||||
}
|
||||
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")
|
||||
}
|
||||
if err := os.Symlink(input, filepath.Join(dir, ErrorsFile)); err != nil {
|
||||
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")
|
||||
}
|
||||
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 {
|
||||
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")
|
||||
}
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: output})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -85,10 +85,10 @@ func TestPrepareOutputPreservesExistingTranscriptAndChecksParent(t *testing.T) {
|
||||
if info, _ := os.Stat(output); info.Mode().Perm() != 0600 {
|
||||
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")
|
||||
}
|
||||
if _, err := PrepareOutput(OutputSelection{TranscriptPath: dir}); err == nil {
|
||||
if _, err := prepareOutputForTest(OutputSelection{TranscriptPath: dir}); err == nil {
|
||||
t.Fatal("directory target accepted")
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
@@ -115,7 +115,7 @@ func TestOutputPathsUseFilesystemParent(t *testing.T) {
|
||||
}
|
||||
parent := alias + string(filepath.Separator) + ".."
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -146,7 +146,7 @@ func TestOutputPublishesThroughTranscriptAndReportSymlinks(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func TestStagingCleansTemporaryResourcesAfterPublicationFailure(t *testing.T) {
|
||||
|
||||
func TestDisabledReportingIgnoresUnusableDirectory(t *testing.T) {
|
||||
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 {
|
||||
t.Fatalf("disabled reports probed: %+v %v", session, err)
|
||||
}
|
||||
@@ -210,7 +210,7 @@ func TestDisabledReportingIgnoresUnusableDirectory(t *testing.T) {
|
||||
|
||||
func TestEnabledReportingRequiresExistingDirectory(t *testing.T) {
|
||||
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")
|
||||
}
|
||||
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) {
|
||||
dir := t.TempDir()
|
||||
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -251,7 +251,7 @@ func TestStdoutModeInitializesAndFinalizesReports(t *testing.T) {
|
||||
|
||||
func TestInitializeFailureMarksPriorReportFailedBeforeModelWork(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -286,7 +286,7 @@ func TestInitializeFailureMarksPriorReportFailedBeforeModelWork(t *testing.T) {
|
||||
func TestFinalizationCollectsFailuresAndRetainsPublishedTranscript(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -330,7 +330,7 @@ func TestFailedRenderingKeepsInitializedEvidenceAfterStreamError(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
delivery := errors.New("stream delivery 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 }),
|
||||
ReportDir: dir, ReportingEnabled: true,
|
||||
})
|
||||
@@ -390,7 +390,7 @@ func TestFailedReportsIncludeLaterDeliveryFailures(t *testing.T) {
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -430,7 +430,7 @@ func TestFailedReportsIncludeLaterDeliveryFailures(t *testing.T) {
|
||||
|
||||
func TestRepeatedFailureOfOneReportCountsOnce(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
session, err := PrepareOutput(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
session, err := prepareOutputForTest(OutputSelection{ReportDir: dir, ReportingEnabled: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -471,7 +471,7 @@ func TestCancellationAfterStreamDeliveryUsesOnlyFailedReports(t *testing.T) {
|
||||
defer cancel()
|
||||
delivery := errors.New("late stream error")
|
||||
var escaped []byte
|
||||
session, err := PrepareOutput(OutputSelection{
|
||||
session, err := prepareOutputForTest(OutputSelection{
|
||||
Stdout: writerFunc(func(payload []byte) (int, error) {
|
||||
escaped = append(escaped, payload...)
|
||||
cancel()
|
||||
@@ -502,7 +502,7 @@ func TestCancellationAfterStreamDeliveryUsesOnlyFailedReports(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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -600,13 +600,14 @@ func TestSelectionAndAbortPreserveTranscript(t *testing.T) {
|
||||
if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session, err := SelectOutput(OutputSelection{TranscriptPath: output})
|
||||
checked, err := CheckOutput(OutputSelection{TranscriptPath: output})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if entries, err := os.ReadDir(dir); err != nil || len(entries) != 1 {
|
||||
t.Fatalf("selection changed directory: %v %v", entries, err)
|
||||
}
|
||||
session := NewOutputSession(checked)
|
||||
if err := session.Prepare(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -627,7 +628,7 @@ func TestSelectionAndAbortPreserveTranscript(t *testing.T) {
|
||||
|
||||
func TestStdoutAndDeviceDelivery(t *testing.T) {
|
||||
var stdout bytes.Buffer
|
||||
session, err := PrepareOutput(OutputSelection{Stdout: &stdout})
|
||||
session, err := prepareOutputForTest(OutputSelection{Stdout: &stdout})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -637,7 +638,7 @@ func TestStdoutAndDeviceDelivery(t *testing.T) {
|
||||
if stdout.String() != "transcript" {
|
||||
t.Fatalf("stdout=%q", stdout.String())
|
||||
}
|
||||
session, err = PrepareOutput(OutputSelection{TranscriptPath: os.DevNull})
|
||||
session, err = prepareOutputForTest(OutputSelection{TranscriptPath: os.DevNull})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -655,7 +656,7 @@ func TestFinishRetainsPrimaryFailureAndAttemptsReports(t *testing.T) {
|
||||
if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -707,7 +708,7 @@ type shortOutput struct{}
|
||||
func (shortOutput) Write(b []byte) (int, error) { return len(b) / 2, nil }
|
||||
|
||||
func TestShortStdoutWriteIsFailure(t *testing.T) {
|
||||
session, err := PrepareOutput(OutputSelection{Stdout: shortOutput{}})
|
||||
session, err := prepareOutputForTest(OutputSelection{Stdout: shortOutput{}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -723,7 +724,7 @@ func TestTranscriptWriteFailureCleansTemporaryResource(t *testing.T) {
|
||||
if err := os.WriteFile(output, []byte("original"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: output})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: output})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -746,7 +747,7 @@ func TestTranscriptWriteFailureCleansTemporaryResource(t *testing.T) {
|
||||
func TestNamedPipeIsNotOpenedDuringPreparation(t *testing.T) {
|
||||
pipe := filepath.Join(t.TempDir(), "output-pipe")
|
||||
makeNamedPipe(t, pipe)
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: pipe})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: pipe})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -761,7 +762,7 @@ func TestNamedPipeIsNotOpenedDuringPreparation(t *testing.T) {
|
||||
func TestLateNamedPipeIsPreserved(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "output")
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: path})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: path})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -784,7 +785,7 @@ func TestLateNamedPipeIsPreserved(t *testing.T) {
|
||||
func TestStreamChangedToRegularFileIsPreserved(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "output")
|
||||
makeNamedPipe(t, path)
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: path})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: path})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -814,3 +815,15 @@ func makeNamedPipe(t *testing.T, path string) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestTranscriptStreamDestinations(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func TestTranscriptStreamWriteFailure(t *testing.T) {
|
||||
if _, err := os.Stat("/dev/full"); os.IsNotExist(err) {
|
||||
t.Skip("/dev/full unavailable")
|
||||
}
|
||||
session, err := PrepareOutput(OutputSelection{TranscriptPath: "/dev/full"})
|
||||
session, err := prepareOutputForTest(OutputSelection{TranscriptPath: "/dev/full"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -68,3 +68,17 @@ func TestTranscriptStreamWriteFailure(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -31,6 +31,8 @@ type TranscriptModule interface {
|
||||
type StructuredCompletionRequest = structuredoutput.Request
|
||||
type StructuredCompletionResponse = structuredoutput.Response
|
||||
|
||||
type GlossaryInstruction = promptcontext.GlossaryInstruction
|
||||
|
||||
// ModuleRunSpec identifies one resolved module instance in a pipeline.
|
||||
type ModuleRunSpec struct {
|
||||
ModuleKey string `json:"module_key"`
|
||||
@@ -40,6 +42,7 @@ type ModuleRunSpec struct {
|
||||
ID *string `json:"-"`
|
||||
Settings config.Stage `json:"-"`
|
||||
Glossary []glossary.Entry `json:"-"`
|
||||
GlossaryInstructions []GlossaryInstruction `json:"-"`
|
||||
ProtectedTerms []glossary.Term `json:"-"`
|
||||
GlossaryView *validators.GlossaryView `json:"-"`
|
||||
GlossaryVariables *promptcontext.GlossaryVariables `json:"-"`
|
||||
@@ -56,6 +59,7 @@ func (s *ModuleRunSpec) PrepareGlossary() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
variables.InstructionsBlock = promptcontext.GlossaryInstructionsBlock(s.GlossaryInstructions)
|
||||
s.GlossaryVariables = &variables
|
||||
}
|
||||
if s.GlossaryView == nil {
|
||||
@@ -140,10 +144,16 @@ func ResolveModuleRunSpecs(cfg *config.Config) []ModuleRunSpec {
|
||||
key := GlossarySelection(item)
|
||||
if prior, ok := selections[key]; ok {
|
||||
spec.Glossary = specs[prior].Glossary
|
||||
spec.GlossaryInstructions = specs[prior].GlossaryInstructions
|
||||
spec.ProtectedTerms = specs[prior].ProtectedTerms
|
||||
continue
|
||||
}
|
||||
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)
|
||||
var excluded []glossary.Entry
|
||||
if key.exempt {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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) {
|
||||
section := chunking.Section{
|
||||
Index: 3,
|
||||
|
||||
@@ -5,12 +5,12 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
@@ -55,6 +55,39 @@ type pendingCall struct {
|
||||
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) {
|
||||
p.once.Do(func() {
|
||||
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 {
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "invalid structured output target", Cause: err})
|
||||
}
|
||||
contract, err := OutputContract(req.Schema, c.settings.RepairAttempts)
|
||||
if err != nil {
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "unknown structured response schema", Cause: err})
|
||||
}
|
||||
call.request = pk.RunRequest{
|
||||
PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables),
|
||||
CaptureExchange: req.CaptureExchange,
|
||||
TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout,
|
||||
Validation: contract,
|
||||
Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) {
|
||||
if event.Kind == pk.ExecutionFinished {
|
||||
mu.Lock()
|
||||
@@ -165,7 +193,7 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
||||
metadata := promptMetadata(details)
|
||||
var snapshot *structuredoutput.PreparedSnapshot
|
||||
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()
|
||||
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 {
|
||||
var typeError *json.UnmarshalTypeError
|
||||
if errors.As(decodeErr, &typeError) {
|
||||
var syntaxError *json.SyntaxError
|
||||
if errors.As(decodeErr, &typeError) || errors.As(decodeErr, &syntaxError) {
|
||||
return &structuredoutput.Failure{Class: structuredoutput.FailureRecoverable, Reason: outcomes.ReasonInvalidOutput, Message: "structured output contains an unusable value", Cause: decodeErr}
|
||||
}
|
||||
return &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "validated structured output could not be decoded", Cause: decodeErr}
|
||||
@@ -216,15 +245,6 @@ func (c *RoleClient) CompleteStructured(ctx context.Context, req structuredoutpu
|
||||
return call.finish(result, err)
|
||||
}
|
||||
|
||||
// OutputContract maps an Audita domain schema to the native request contract.
|
||||
func OutputContract(schema responseschema.Key, repairs int) (*pk.OutputContract, error) {
|
||||
path, ok := responseschema.AssetPath(schema)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("schema %q", schema)
|
||||
}
|
||||
return &pk.OutputContract{Format: pk.FormatJSON, ValidationMode: pk.ValidationJSONSchema, SchemaPath: path, RepairAttempts: repairs}, nil
|
||||
}
|
||||
|
||||
// classifiedFailure deliberately checks setup defects before broad PromptKit
|
||||
// validation/generation wrappers. Provider text is kept only in the typed cause.
|
||||
func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure {
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
"testing"
|
||||
"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/framework/responseschema"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
)
|
||||
|
||||
@@ -24,11 +24,11 @@ func capacityFixture(t *testing.T, resources string, transport http.RoundTripper
|
||||
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 {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func TestRolesShareBackendCapacityAndReleaseAfterCancellation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := adapterRequest(responseschema.CorrectionSetKey)
|
||||
request := adapterRequest("proposal")
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := proposal.CompleteStructured(context.Background(), request, &map[string]any{})
|
||||
@@ -112,7 +112,7 @@ func TestDistinctBackendsHaveIndependentCapacity(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := adapterRequest(responseschema.CorrectionSetKey)
|
||||
request := adapterRequest("proposal")
|
||||
done := make(chan error, 2)
|
||||
go func() {
|
||||
_, err := first.CompleteStructured(context.Background(), request, &map[string]any{})
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -15,9 +17,9 @@ import (
|
||||
"testing"
|
||||
"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/framework/outcomes"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
@@ -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, "")
|
||||
}
|
||||
|
||||
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()
|
||||
var count atomic.Int32
|
||||
t.Setenv("ADAPTER_KEY", "adapter-secret")
|
||||
@@ -79,7 +86,26 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
|
||||
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 {
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime.Config.LLM = config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries, RepairAttempts: repairs}
|
||||
return runtime, &count, dir
|
||||
settings := config.Config{LLM: config.LLM{OperationTimeout: 10 * time.Second, TransientRetries: retries}}
|
||||
return &testRuntime{Runtime: runtime, Config: settings}, &count, dir
|
||||
}
|
||||
|
||||
func operatorPromptDocument(system, user string) string {
|
||||
return fmt.Sprintf("collections:\n audita:\n prompts:\n - id: modules.glossary.proposal\n messages:\n - role: system\n content: %q\n - role: user\n content: %q\n output:\n format: text\n validation_mode: none\n", system, user)
|
||||
}
|
||||
|
||||
func adapterRequest(schema responseschema.Key) structuredoutput.Request {
|
||||
func adapterRequest(schema string) structuredoutput.Request {
|
||||
id := prompts.PromptIDModuleGlossaryProposal
|
||||
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
|
||||
if schema == responseschema.ValidatorDecisionSetKey {
|
||||
if schema == "validation" {
|
||||
id = prompts.PromptIDValidatorEditorialReview
|
||||
vars = map[string]string{"TranscriptDescriptionBlock": "", "PayloadJSON": "[]"}
|
||||
}
|
||||
return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Schema: schema, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}}
|
||||
return structuredoutput.Request{CaptureDiagnostics: true, PromptID: id, Variables: vars, Context: structuredoutput.DiagnosticContext{ModuleKey: "glossary"}}
|
||||
}
|
||||
|
||||
func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
|
||||
for _, schema := range []responseschema.Key{responseschema.CorrectionSetKey, responseschema.ValidatorDecisionSetKey} {
|
||||
for _, schema := range []string{"proposal", "validation"} {
|
||||
valid := `{"corrections":[]}`
|
||||
if schema == responseschema.ValidatorDecisionSetKey {
|
||||
if schema == "validation" {
|
||||
valid = `{"validations":[]}`
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
@@ -155,7 +181,7 @@ func TestPreparedAdapterRepairsAndClassifies(t *testing.T) {
|
||||
t.Run(string(schema)+"/"+tc.name, func(t *testing.T) {
|
||||
runtime, count, _ := adapterFixture(t, tc.replies, tc.retries, tc.repairs, nil)
|
||||
role := "proposal"
|
||||
if schema == responseschema.ValidatorDecisionSetKey {
|
||||
if schema == "validation" {
|
||||
role = "validation"
|
||||
}
|
||||
var events []pk.ExecutionEvent
|
||||
@@ -245,7 +271,7 @@ func TestCorrectionSchemaReplacementValuesThroughAdapter(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out map[string]any
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &out)
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &out)
|
||||
if got := count.Load(); got != 1 {
|
||||
t.Fatalf("expected one provider generation, got %d", got)
|
||||
}
|
||||
@@ -290,7 +316,7 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
req.Variables["HardeningPolicy"] = "attacker-controlled"
|
||||
var out map[string]any
|
||||
response, err := client.CompleteStructured(context.Background(), req, &out)
|
||||
@@ -300,6 +326,17 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
||||
if !requestSeen || count.Load() != 1 || response.Prepared == nil || len(response.Prepared.Messages) == 0 {
|
||||
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) {
|
||||
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 {
|
||||
name string
|
||||
system string
|
||||
@@ -337,8 +408,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
|
||||
name: "operator text without shared references",
|
||||
system: "Operator system instructions.",
|
||||
user: "Operator request without variables.",
|
||||
replies: []reply{{200, `{"wrong":true}`}, {200, `{"corrections":[]}`}},
|
||||
repairs: 1,
|
||||
replies: []reply{{200, `{"wrong":true}`}},
|
||||
wantSystem: "Operator system instructions.",
|
||||
wantUser: "Operator request without variables.",
|
||||
},
|
||||
@@ -370,7 +440,7 @@ func TestOperatorPromptOverridesUsePerCallSchemaAndOptionalSharedText(t *testing
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
if tc.name == "operator text with shared references" {
|
||||
req.Variables["HardeningPolicy"] = "attacker-controlled"
|
||||
}
|
||||
@@ -410,7 +480,7 @@ func TestPreparedAdapterRejectsTargetDriftAndPreparationErrors(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
req.PromptID = "missing.prompt"
|
||||
var out map[string]any
|
||||
if _, err := client.CompleteStructured(context.Background(), req, &out); err == nil || count.Load() != 0 {
|
||||
@@ -432,7 +502,7 @@ func TestPreparedAdapterCancellationStopsRetryWait(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out map[string]any
|
||||
_, err = client.CompleteStructured(ctx, adapterRequest(responseschema.CorrectionSetKey), &out)
|
||||
_, err = client.CompleteStructured(ctx, adapterRequest("proposal"), &out)
|
||||
if !errors.Is(err, context.Canceled) || count.Load() != 1 {
|
||||
t.Fatalf("cancellation: %v, HTTP calls=%d", err, count.Load())
|
||||
}
|
||||
@@ -447,7 +517,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output map[string]any
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonOperationTimeout || !errors.Is(err, pk.ErrOperationTimeout) || !response.Execution.Available {
|
||||
t.Fatalf("local timeout: failure=%#v counts=%+v", failure, response.Execution)
|
||||
@@ -455,7 +525,7 @@ func TestPreparedAdapterDistinguishesOperationTimeoutFromParentCancellation(t *t
|
||||
|
||||
parent, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
response, err = client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output)
|
||||
response, err = client.CompleteStructured(parent, adapterRequest("proposal"), &output)
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureCanceled || failure.Reason != outcomes.ReasonCanceled || !errors.Is(err, context.Canceled) || response.Execution.Available {
|
||||
t.Fatalf("parent cancellation: failure=%#v counts=%+v", failure, response.Execution)
|
||||
}
|
||||
@@ -482,7 +552,7 @@ func TestPreparedAdapterDistinguishesAttemptTimeoutFromParentDeadline(t *testing
|
||||
defer cancel()
|
||||
before := count.Load()
|
||||
var output map[string]any
|
||||
response, err := client.CompleteStructured(parent, adapterRequest(responseschema.CorrectionSetKey), &output)
|
||||
response, err := client.CompleteStructured(parent, adapterRequest("proposal"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != tc.class || failure.Reason != tc.reason ||
|
||||
!errors.Is(err, context.DeadlineExceeded) || errors.Is(err, pk.ErrOperationTimeout) ||
|
||||
@@ -504,7 +574,7 @@ func TestPreparedAdapterMissingCredentialRetainsSetupCause(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output map[string]any
|
||||
_, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
|
||||
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure ||
|
||||
!errors.Is(err, pk.ErrAPIKeyEnvMissing) || !strings.Contains(err.Error(), "ADAPTER_KEY") ||
|
||||
@@ -524,21 +594,16 @@ func TestPreparedAdapterClassifiesSetupAndDomainDecodeFailures(t *testing.T) {
|
||||
CorrectionIndex int `json:"correction_index"`
|
||||
} `json:"validations"`
|
||||
}
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.ValidatorDecisionSetKey), &output)
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest("validation"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || !response.Execution.Available {
|
||||
t.Fatalf("decode overflow: failure=%#v counts=%+v", failure, response.Execution)
|
||||
}
|
||||
_, err = client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), nil)
|
||||
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), nil)
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
|
||||
t.Fatalf("invalid target: %#v", failure)
|
||||
}
|
||||
req := adapterRequest("missing_schema")
|
||||
_, err = client.CompleteStructured(context.Background(), req, &output)
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
|
||||
t.Fatalf("unknown schema: %#v", failure)
|
||||
}
|
||||
req = adapterRequest(responseschema.ValidatorDecisionSetKey)
|
||||
req := adapterRequest("validation")
|
||||
req.PromptID = "missing.prompt"
|
||||
_, err = client.CompleteStructured(context.Background(), req, &output)
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure {
|
||||
@@ -553,7 +618,7 @@ func TestPreparedAdapterNonRetryableProviderStatus(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output map[string]any
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest(responseschema.CorrectionSetKey), &output)
|
||||
response, err := client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonProviderFailed || count.Load() != 1 || response.Execution.HTTPStatus == nil || *response.Execution.HTTPStatus != http.StatusBadRequest {
|
||||
t.Fatalf("non-retryable provider failure: failure=%#v calls=%d counts=%+v", failure, count.Load(), response.Execution)
|
||||
@@ -580,3 +645,28 @@ func TestOperationTimeoutDuringPreparationIsRecoverable(t *testing.T) {
|
||||
t.Fatalf("failure = %#v", failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissivePromptReturnsRecoverableDecodeFailures(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
}{
|
||||
{"malformed JSON", `{"corrections": [`},
|
||||
{"incompatible value", `{"corrections":"not-an-array"}`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
runtime, calls, _ := adapterFixtureWithPrompt(t, []reply{{200, tc.body}}, 0, 0, nil, operatorPromptDocument("system", "user"))
|
||||
client, err := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, CallHooks{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var output struct {
|
||||
Corrections []struct{} `json:"corrections"`
|
||||
}
|
||||
_, err = client.CompleteStructured(context.Background(), adapterRequest("proposal"), &output)
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput || calls.Load() != 1 {
|
||||
t.Fatalf("failure=%v calls=%d", err, calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,9 @@ import (
|
||||
"testing"
|
||||
"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/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/prompts"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
@@ -31,7 +32,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -56,7 +57,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -69,8 +70,15 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
|
||||
initial, err := proposal.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: vars, CaptureExchange: true}, &map[string]any{})
|
||||
selected := contracts.ResolveModuleRunSpecs(&config.Config{
|
||||
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 {
|
||||
t.Fatalf("capture: %+v %v", initial, err)
|
||||
}
|
||||
@@ -86,7 +94,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
if turns == 2 {
|
||||
return nil, nil
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": []string{"first", "second"}[turns]}}, nil
|
||||
})
|
||||
if err != nil || exhausted || turns != 2 {
|
||||
t.Fatalf("coordinated dialogue: turns=%d exhausted=%v error=%v", turns, exhausted, err)
|
||||
@@ -95,6 +103,11 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
t.Fatalf("models = %v", models)
|
||||
}
|
||||
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) {
|
||||
t.Fatalf("prefixes: %+v", messages)
|
||||
}
|
||||
@@ -111,7 +124,7 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
|
||||
if turn.Response != nil {
|
||||
return nil, turn.Err
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "independent"}}, nil
|
||||
}
|
||||
_, err = repair.Coordinate(context.Background(), initial.Exchange, 1, independent)
|
||||
if err != nil || len(messages) != 4 || len(messages[3]) != len(prefix)+2 || !strings.Contains(string(messages[3][len(prefix)+1].Content), "independent") {
|
||||
@@ -136,7 +149,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -154,15 +167,15 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: 1}, CallHooks{})
|
||||
client, err := runtime.NewRoleClient("repair", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{})
|
||||
base, err := client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}, CaptureExchange: true}, &map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -172,7 +185,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
|
||||
result = turn.Response
|
||||
return nil, turn.Err
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "fixture"}}, nil
|
||||
})
|
||||
if err != nil || exhausted || result == nil {
|
||||
t.Fatalf("coordinated structural repair: result=%+v exhausted=%v error=%v", result, exhausted, err)
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
pk "go.maximumdirect.net/promptkit"
|
||||
@@ -31,7 +30,7 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
req.CaptureExchange = true
|
||||
base, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
|
||||
if err != nil {
|
||||
@@ -55,14 +54,14 @@ func TestCoordinatorFinalTurnFailuresAndAccounting(t *testing.T) {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
})
|
||||
if err != nil || exhausted != tc.again || deliveries != 1 || count.Load() != 2 {
|
||||
t.Fatalf("exhausted=%v delivered=%d calls=%d err=%v", exhausted, deliveries, count.Load(), err)
|
||||
}
|
||||
snapshot := collector.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)
|
||||
}
|
||||
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)
|
||||
collector := NewObservationCollector()
|
||||
proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
req.CaptureExchange = true
|
||||
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
|
||||
if err != nil {
|
||||
@@ -102,12 +101,12 @@ func TestCoordinatorCanceledDeliveryRetainsEvidence(t *testing.T) {
|
||||
}
|
||||
return nil, turn.Err
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) || deliveries != 1 {
|
||||
t.Fatalf("deliveries=%d err=%v", deliveries, err)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -118,7 +117,7 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) {
|
||||
proposal, _ := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, collector.Hooks())
|
||||
repair, _ := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, collector.Hooks())
|
||||
validation, _ := runtime.NewRoleClient("validation", "base", runtime.Config.LLM, collector.Hooks())
|
||||
req := adapterRequest(responseschema.CorrectionSetKey)
|
||||
req := adapterRequest("proposal")
|
||||
req.CaptureExchange = true
|
||||
base, err := proposal.CompleteStructured(context.Background(), req, &map[string]any{})
|
||||
if err != nil {
|
||||
@@ -129,13 +128,43 @@ func TestCoordinatorReleasesAdmissionBeforeNestedValidation(t *testing.T) {
|
||||
if turn.Err != nil {
|
||||
return nil, turn.Err
|
||||
}
|
||||
_, err := validation.CompleteStructured(ctx, adapterRequest(responseschema.ValidatorDecisionSetKey), &map[string]any{})
|
||||
_, err := validation.CompleteStructured(ctx, adapterRequest("validation"), &map[string]any{})
|
||||
return nil, err
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Schema: responseschema.CorrectionRepairKey, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, CaptureDiagnostics: true, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
})
|
||||
summary := Summarize(collector.Snapshot())
|
||||
if err != nil || count.Load() != 3 || summary.ProviderAttempts != 3 || summary.LogicalCalls != 3 || !summary.TerminalCoverageComplete {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorDeliversRecoverableMalformedOutput(t *testing.T) {
|
||||
operator := "collections:\n audita:\n prompts:\n - id: modules.grammar.repair\n messages:\n - role: user\n content: '{{.RepairRequestJSON}}'\n output:\n format: text\n validation_mode: none\n"
|
||||
runtime, count, _ := adapterFixtureWithPrompt(t, []reply{{200, `{"corrections":[]}`}, {200, `{"decision":[`}}, 0, 0, nil, operator)
|
||||
client, err := runtime.NewRoleClient("repair", "base", runtime.Config.LLM, CallHooks{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := adapterRequest("proposal")
|
||||
request.CaptureExchange = true
|
||||
base, err := client.CompleteStructured(context.Background(), request, &map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delivered := false
|
||||
_, err = client.Coordinate(context.Background(), base.Exchange, 1, func(_ context.Context, turn structuredoutput.Turn) (*structuredoutput.Request, error) {
|
||||
if turn.Response != nil {
|
||||
delivered = true
|
||||
var failure *structuredoutput.Failure
|
||||
if !errors.As(turn.Err, &failure) || failure.Class != structuredoutput.FailureRecoverable || failure.Reason != outcomes.ReasonInvalidOutput {
|
||||
t.Fatalf("turn error = %v", turn.Err)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
return &structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarRepair, Variables: map[string]string{"RepairRequestJSON": "{}"}}, nil
|
||||
})
|
||||
if err != nil || !delivered || count.Load() != 2 {
|
||||
t.Fatalf("error=%v delivered=%v calls=%d", err, delivered, count.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"slices"
|
||||
"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"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
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("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")
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := NewRuntime(context.Background(), loaded, nil)
|
||||
first, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -60,7 +60,7 @@ func TestEngineCapturesAutomaticPromptSources(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write("message.txt", "second")
|
||||
second, err := NewRuntime(context.Background(), loaded, nil)
|
||||
second, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -70,11 +70,11 @@ func TestEngineCapturesAutomaticPromptSources(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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
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/instruction.md", "inherited content")
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
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")
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -144,12 +144,12 @@ func TestEngineUsesRecordedContextWithWiderRoot(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Chdir(t.TempDir())
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
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 {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -211,11 +211,11 @@ func TestRepairPromptReplacementUsesMessageFile(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/testsupport/promptfixture"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -13,9 +15,9 @@ import (
|
||||
"testing"
|
||||
"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/framework/outcomes"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/responseschema"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
|
||||
ck "go.maximumdirect.net/configkit"
|
||||
@@ -35,7 +37,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
|
||||
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(document), 0644); err != nil {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -48,7 +50,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
|
||||
}
|
||||
return nil, providerErr
|
||||
})}
|
||||
runtime, err := NewRuntime(context.Background(), loaded, httpClient)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, httpClient)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -57,7 +59,7 @@ func TestRoleClientUsesSelectedNativeCredential(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out map[string]any
|
||||
_, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out)
|
||||
_, err = client.CompleteStructured(context.Background(), structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}, &out)
|
||||
if err == nil || calls != 1 {
|
||||
t.Fatalf("error = %v, calls = %d", err, calls)
|
||||
}
|
||||
@@ -73,11 +75,11 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
repair int
|
||||
@@ -90,6 +92,22 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
|
||||
{"no repair", 0, []string{`{"wrong":true}`}, 1, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
prompt, err := fs.ReadFile(prompts.Filesystem(), "assets/prompts/modules.grammar.proposal.yaml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prompt = 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
|
||||
httpClient := &http.Client{Transport: transportFunc(func(r *http.Request) (*http.Response, error) {
|
||||
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)
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second, RepairAttempts: tc.repair}, CallHooks{})
|
||||
client, err := runtime.NewRoleClient("proposal", "fixture", config.LLM{OperationTimeout: 10 * time.Second}, CallHooks{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -127,7 +145,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
runtime, err := NewRuntime(context.Background(), loaded, nil)
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -151,7 +169,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -162,7 +180,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -175,7 +193,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
request := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := first.CompleteStructured(context.Background(), request, &map[string]any{})
|
||||
@@ -200,7 +218,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
|
||||
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 {
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -221,7 +239,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
response, err := client.CompleteStructured(context.Background(), req, &map[string]any{})
|
||||
if err != nil || calls != 2 || response.Execution.TransientRetries != 1 {
|
||||
t.Fatalf("error=%v calls=%d execution=%+v", err, calls, response.Execution)
|
||||
@@ -241,7 +259,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
|
||||
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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -251,11 +269,11 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
|
||||
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
|
||||
})
|
||||
runtime, err := NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
|
||||
runtime, err := NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Schema: responseschema.CorrectionSetKey, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
req := structuredoutput.Request{PromptID: prompts.PromptIDModuleGrammarProposal, Variables: map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}}
|
||||
for _, tc := range []struct{ profile, auth string }{{"inherited", "Bearer backend-secret-value"}, {"explicit", "Bearer profile-secret-value"}, {"cleared", ""}} {
|
||||
t.Run(tc.profile, func(t *testing.T) {
|
||||
client, err := runtime.NewRoleClient("proposal", tc.profile, config.LLM{OperationTimeout: 5 * time.Second}, CallHooks{})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user