59 Commits

Author SHA1 Message Date
6f97f31ccb Complete the Audita v4.3.0 release notes
All checks were successful
ci/woodpecker/tag/release Pipeline was successful
2026-11-29 18:46:52 +00:00
0e565b3abf Remove completed shared glossary planning documents 2026-11-29 18:44:21 +00:00
fb612b361d Allow disjoint glossary overrides alongside shared files 2026-11-29 18:43:13 +00:00
e72f69c68b Attribute glossary schema errors to their source fields 2026-11-29 18:39:07 +00:00
c15204bdc7 Record glossary override integration conflict 2026-11-29 18:34:42 +00:00
8699ec442a Record glossary validation diagnostic finding 2026-11-29 18:27:50 +00:00
00a3628451 Clarify completed glossary roadmap markers 2026-11-29 18:20:11 +00:00
9af2c146f1 Complete shared glossary validation and acceptance checks 2026-11-29 18:19:50 +00:00
3b7baed65e Document shared glossary inputs and migration 2026-11-29 18:16:18 +00:00
04546acee0 Verify shared glossary selection across CLI workflows 2026-11-29 18:14:11 +00:00
994cba3ba2 Retire automatic glossary companion discovery 2026-11-29 18:11:49 +00:00
ff4f98d2f7 Apply shared glossary entries to application configuration 2026-11-29 18:11:07 +00:00
009373130c Compose shared glossary files with ConfigKit 2026-11-29 18:10:21 +00:00
3e287503eb Bundle and validate the shared glossary contract 2026-11-29 18:09:08 +00:00
c0d2280305 Use explicit files for glossary adoption 2026-11-29 18:06:20 +00:00
38c5f3c290 Plan shared glossary implementation 2026-11-29 17:59:11 +00:00
1ded570158 Target the ConfigKit aligned glossary schema 2026-11-29 17:44:40 +00:00
7ee50d1a3f Clarify glossary adoption maintenance boundaries 2026-11-29 16:28:19 +00:00
4543d66e21 Clarify shared glossary scope and ConfigKit limits 2026-11-29 15:56:05 +00:00
5a842f6a7f Simplify glossary adoption for v4.3.0 2026-11-29 15:34:04 +00:00
0b9c7912c2 Plan shared glossary adoption 2026-11-29 15:21:33 +00:00
4c2b11aa45 Request shared glossary schema adoption for Narratio 2026-11-29 15:01:26 +00:00
973b24e466 Configure ignored local ReleaseKit token
All checks were successful
ci/woodpecker/tag/release Pipeline was successful
2026-11-27 04:25:36 +00:00
cbb2f768be Prepare v4.2.0 notes and retire completed plans 2026-11-27 04:19:36 +00:00
b96eeb57ba Report preflight smoke usage with its correct scope 2026-11-27 04:12:41 +00:00
f5cef61bb5 Update preflight roadmap completion status 2026-11-27 04:04:48 +00:00
7ba1846e63 Show progress for each preflight profile 2026-11-27 04:04:30 +00:00
2eae2a4af2 Explain native preflight failures 2026-11-27 04:03:24 +00:00
bed9424329 Record preflight usage reporting integration gap 2026-11-27 03:56:36 +00:00
330044b207 Record preflight review findings 2026-11-27 03:43:43 +00:00
7874ea648b Document and validate preflight readiness 2026-11-27 01:26:07 +00:00
a9ab8e59b3 Report preflight provider verification and usage 2026-11-27 01:22:58 +00:00
a0292a3ba0 Verify structured output for selected profiles 2026-11-27 01:21:08 +00:00
a980fbbb09 Add preflight command and run alias 2026-11-27 01:19:17 +00:00
b4bc5e5640 Run processing from the prepared invocation 2026-11-27 01:17:45 +00:00
2dc057b97e Prepare normalized processing plans and fixed chunks 2026-11-27 01:15:40 +00:00
e761512c1c Probe output destinations with temporary files 2026-11-27 01:11:57 +00:00
bd3a22754a Separate output checks from session creation 2026-11-27 01:10:44 +00:00
645931c5e3 Plan shared preflight preparation and provider checks 2026-11-27 01:06:24 +00:00
604ae631b3 Record preflight destination requirements and write probes 2026-11-26 23:57:36 +00:00
9dadd97ee6 Plan run as an alias for process 2026-11-26 23:03:11 +00:00
be2846847b Plan standalone preflight with shared readiness preparation 2026-11-26 23:02:45 +00:00
8411a69187 Record completed D&D overlay implementation 2026-11-26 21:30:08 +00:00
33d9e0428d Retire completed runtime glossary planning documents 2026-11-26 21:20:41 +00:00
1ebf39bd6f Document runtime glossary inheritance boundaries 2026-11-26 21:16:22 +00:00
51cb6b2059 Clarify collection guidance during correction repair 2026-11-26 21:15:29 +00:00
4b1812995f Preserve native glossary loading error classifications 2026-11-26 21:14:32 +00:00
bf3184cf0a Record runtime glossary review findings 2026-11-26 19:40:47 +00:00
889ac766a5 Document and verify runtime glossary workflows 2026-11-26 18:25:43 +00:00
e0445abe48 Include glossary guidance in proposal conversations 2026-11-26 18:22:52 +00:00
20db09bd2a Share runtime glossaries with inspection commands 2026-11-26 18:20:54 +00:00
39087675e1 Accept and protect processing glossary files 2026-11-26 18:18:34 +00:00
a4b8fd0976 Compose runtime glossary files with native configuration 2026-11-26 18:17:16 +00:00
b1cde637a2 Retain selected glossary instructions 2026-11-26 18:14:27 +00:00
d2c4c63580 Plan runtime glossary input implementation 2026-11-26 16:02:21 +00:00
f85a07c14d Plan optional collection instructions for proposals and repair 2026-11-26 15:54:03 +00:00
3a5ea78b80 Record agreed D&D overlay contracts and model profiles 2026-11-26 15:48:34 +00:00
178b0cfa9c Separate D&D recipe ownership from Audita 2026-11-26 15:33:10 +00:00
892cff8088 Plan runtime glossary inputs and overlay recipes 2026-11-26 15:26:19 +00:00
111 changed files with 3920 additions and 673 deletions

1
.gitignore vendored
View File

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

View File

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

View File

@@ -14,6 +14,9 @@ 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
@@ -41,17 +44,52 @@ 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. Request `--format yaml` or `--format json` for
machine-readable smoke results; their default is text. Shared loading can run
configured secrets bootstrap for inspection as well as processing.
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.
@@ -59,5 +97,7 @@ Exit status `0` means success, `1` runtime or output failure, `2` invalid usage
or input, and native comparison may return `3` for differences. ConfigKit
classifies native configuration diagnostics; unclassified runtime preparation
and bootstrap failures, and cancellation, are operational. A missing
processing profile or required glossary selection is an input failure. See the
processing profile, 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).

View File

@@ -15,13 +15,39 @@ 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.4.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
@@ -51,7 +77,11 @@ 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

View File

@@ -19,8 +19,16 @@ 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
@@ -35,14 +43,29 @@ 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. Bootstrap failure also occurs before transcript and output
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.

View File

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

View File

@@ -33,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
@@ -46,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

View File

@@ -20,15 +20,17 @@ validator entries yield `validation_decisions_filtered` only for a successful
operation; they do not count as filtered correction proposals. Failed operations
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

View File

@@ -59,9 +59,10 @@ 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.

View File

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

View File

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

43
docs/migrations/v4.3.md Normal file
View 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`.

View File

@@ -17,10 +17,28 @@ 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
@@ -56,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.

View File

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

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

View File

@@ -12,6 +12,13 @@ remote is `origin`, which must point to `ssh://git@forge.maximumdirect.net:22222
primary branch is `main`. Source publication needs no delivery credential.
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

View File

@@ -1,5 +1,7 @@
# 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)

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

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

51
docs/releases/v4.3.0.md Normal file
View 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)

View File

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

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

View File

@@ -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,16 +53,37 @@ 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
--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
@@ -67,20 +92,28 @@ and [ckprompt guide](https://forge.maximumdirect.net/base-layer/commandkit/src/t
## 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.

View File

@@ -2,3 +2,4 @@ config:
imports:
- path: shared.yml
required: true
schema_version: maximumdirect.glossary.v1

View File

@@ -0,0 +1,8 @@
schema_version: maximumdirect.glossary.v1
collections:
party:
entries:
- id: lyra
name: Lyra
category: character
description: A fictional adventurer.

View File

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

View 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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,9 @@
schema_version: maximumdirect.glossary.v1
collections:
incoming:
entries:
- id: speaker
name: Mira Chen
category: person
aliases: [Mira]
source_note: Prepared for this recording

View File

@@ -5,7 +5,11 @@ 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"
@@ -30,17 +34,22 @@ type Config struct {
PromptKit pk.Settings `yaml:"promptkit"`
}
const glossaryImports = `config:
imports:
- path: glossary.yml
required: false
destination: [glossary_collections]
- dir: glossary
required: false
recursive: true
pattern: ["*.yml", "*.yaml"]
destination: [glossary_collections]
`
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:
@@ -71,7 +80,7 @@ func Definition() ck.Definition[Config] {
}
// Load composes built-in resources and optional companions with the selected input.
func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.Override) (*ck.Result[Config], *ck.SecretsReport, error) {
func Load(ctx context.Context, input ck.Input, options Options) (*Acquisition, *ck.SecretsReport, error) {
if err := ctx.Err(); err != nil {
return nil, nil, err
}
@@ -83,6 +92,37 @@ func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.O
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)}
@@ -99,13 +139,12 @@ func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.O
input.Imports = true
result, err := ck.LoadLayered(input, ck.LayeredOptions[Config]{
Definition: Definition(),
Overlay: overlay,
Overlay: options.Overlay,
Overrides: overrides,
Underlays: []ck.Underlay{
pk.BundledOpenRouterUnderlay(),
{Inputs: embedded},
{Inputs: []ck.Input{
{Source: ck.Bytes("Audita glossary imports", []byte(glossaryImports)), Imports: true, MainRelative: ck.MainRelative()},
{Source: ck.Bytes("Audita automatic prompt imports", []byte(operatorImports)), Destination: ck.Keys("promptkit"), Imports: true, MainRelative: ck.MainRelative()},
}},
},
@@ -113,5 +152,35 @@ func Load(ctx context.Context, input ck.Input, overlay string, overrides ...ck.O
if canceled := ctx.Err(); canceled != nil {
return nil, report, errors.Join(err, canceled)
}
return result, report, err
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"}}
}

View File

@@ -26,7 +26,7 @@ func TestLoadCombinesApplicationAndPromptSettings(t *testing.T) {
t.Fatal(err)
}
}
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "selected")
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, Options{Overlay: "selected"})
if err != nil {
t.Fatal(err)
}
@@ -62,7 +62,7 @@ func TestLoadWithoutMainDoesNotDiscoverCompanions(t *testing.T) {
t.Fatal(err)
}
t.Chdir(dir)
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, Options{})
if err != nil {
t.Fatal(err)
}

View File

@@ -10,7 +10,7 @@ import (
ck "go.maximumdirect.net/configkit"
)
func TestGlossarySourcesComposeAndRetainExtensions(t *testing.T) {
func TestGlossaryFilesRequireExplicitSelection(t *testing.T) {
dir := t.TempDir()
write := func(name, data string) {
t.Helper()
@@ -22,69 +22,43 @@ func TestGlossarySourcesComposeAndRetainExtensions(t *testing.T) {
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(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
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.Fatalf("%v: %+v", err, err.(*ck.LoadError).Diagnostics())
t.Fatal(err)
}
party := result.Config.Application.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 len(result.Config.Application.GlossaryCollections) != 1 || result.Config.Application.GlossaryCollections["party"].Entries[0].ID != "configured" {
t.Fatalf("unexpected vocabulary: %+v", result.Config.Application.GlossaryCollections)
}
if party[0].Extra["level"] == nil {
t.Fatalf("extension missing: %+v", party[0])
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)
}
if got := result.Config.Application.GlossaryCollections["lore"].Entries; len(got) != 1 || got[0].ID != "hero" {
t.Fatalf("lore=%+v", got)
}
discovered, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", ck.SearchDirectory(dir))}, "")
if err != nil || len(discovered.Config.Application.GlossaryCollections["party"].Entries) != 2 {
t.Fatalf("discovered glossary: %+v %v", discovered, err)
}
spells := result.Config.Application.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)
}
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(paths, filepath.Join(dir, name)) {
t.Errorf("missing source %s: %v", name, paths)
if !slices.Contains(result.GlossarySources, filepath.Join(dir, name)) {
t.Errorf("missing source %s: %v", name, result.GlossarySources)
}
}
}
func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
func TestInlineGlossaryValidation(t *testing.T) {
dir := t.TempDir()
main := filepath.Join(dir, "config.yml")
write := func(path, data string) {
@@ -98,7 +72,7 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
"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)}, ""); err != nil {
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{}); err != nil {
t.Fatalf("valid %q: %v", data, err)
}
}
@@ -109,19 +83,11 @@ func TestGlossaryValidationAndPeerConflicts(t *testing.T) {
"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)}, ""); err == nil {
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{}); 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(context.Background(), ck.Input{Source: ck.File(main)}, ""); err == nil {
t.Fatal("peer conflict accepted")
}
}
func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) {
@@ -130,7 +96,7 @@ func TestGlossaryUnderlaySkipsAbsentMain(t *testing.T) {
t.Fatal(err)
}
t.Chdir(dir)
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
result, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, Options{})
if err != nil {
t.Fatal(err)
}

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

View File

@@ -24,7 +24,7 @@ func TestLoadBootstrapsSecrets(t *testing.T) {
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)}, "")
result, report, err := Load(context.Background(), ck.Input{Source: ck.File(main)}, Options{})
if err != nil {
t.Fatal(err)
}
@@ -39,14 +39,14 @@ func TestLoadRetainsBootstrapErrorAndCancellation(t *testing.T) {
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)}, "")
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)}, "")
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)
}
@@ -65,7 +65,7 @@ func TestLoadReusesPreparedMainSnapshot(t *testing.T) {
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}}, "")
result, _, err := Load(context.Background(), ck.Input{Source: prepared, Filesystem: &ck.FilesystemContext{Root: dir}}, Options{})
if err != nil {
t.Fatal(err)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

View File

@@ -24,7 +24,7 @@ func TestMainContextImportsAndOverlay(t *testing.T) {
t.Fatal(err)
}
}
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "selected", ck.Override{Path: ck.Keys("context", "description"), Value: "override", Flag: "--description"})
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)
}
@@ -51,10 +51,10 @@ func TestMainContextImportsAndOverlay(t *testing.T) {
if !found {
t.Fatal("main source missing")
}
if _, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "main.yml"))}, "missing"); err == nil {
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()}, "selected"); err == nil {
if _, _, err := Load(context.Background(), ck.Input{Source: ck.NoSource()}, Options{Overlay: "selected"}); err == nil {
t.Fatal("overlay without context accepted")
}
}
@@ -63,8 +63,11 @@ func TestDiscoveryAndSelectedFailure(t *testing.T) {
first, second := t.TempDir(), t.TempDir()
search := ck.Searches(ck.SearchDirectory(first), ck.SearchDirectory(second))
load := func() (*ck.Result[Config], error) {
result, _, err := Load(context.Background(), ck.Input{Source: ck.SearchConfig("audita", search)}, "")
return result, err
result, _, err := Load(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 {
@@ -105,7 +108,7 @@ func TestOverlayUsesMainDirectoryWithinWiderRoot(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "overlays", "local.yml"), []byte("context:\n description: project\n"), 0644); err != nil {
t.Fatal(err)
}
result, _, err := Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "local")
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)
}

View File

@@ -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[appconfig.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,11 +45,19 @@ func loadApplication(ctx context.Context, selection ckconfig.Selection, _ struct
} else {
source = ck.SearchConfig("audita", ck.Searches(ck.WorkingDirectory(), ck.UserConfigDirectory(), ck.UnixSystemDirectories()))
}
loaded, report, err := appconfig.Load(ctx, 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
@@ -56,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
}
}
@@ -69,32 +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
appScope = withBootstrapContext(appScope)
promptScope := withBootstrapContext(ckprompt.ConfigScope(loadPromptEngine))
configCommand := ckconfig.Command(ckconfig.Suite[struct{}, *invocationState]{NewState: func() *invocationState { return &invocationState{client: client} }, Scopes: []ckconfig.Scope[struct{}, *invocationState]{appScope, promptScope}})
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)
definitions = withPromptBootstrapContext(definitions)
declarations := []commandkit.Declaration{configCommand, commandkit.Completion("audita"), commandkit.WithInvocationFeature(processCommand(), bootstrapFeature())}
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...)

View File

@@ -98,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)
}
@@ -118,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")

View File

@@ -37,8 +37,11 @@ func TestBootstrapConfigurationOutcomes(t *testing.T) {
loads := 0
load := func(ctx context.Context, selection ckconfig.Selection, _, _ struct{}) (*ck.Result[appconfig.Config], error) {
loads++
result, report, err := appconfig.Load(ctx, ck.Input{Source: ck.File(selection.Config.Value)}, "")
return result, reportBootstrap(ctx, report, err)
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}})
@@ -87,7 +90,7 @@ func TestBootstrapPreservesJoinedCancellation(t *testing.T) {
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)}, "")
_, 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
@@ -110,7 +113,7 @@ func TestPromptBootstrapFailureReportsTerminalDetails(t *testing.T) {
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)}, "")
_, 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))

View File

@@ -6,8 +6,10 @@ import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
@@ -18,6 +20,7 @@ import (
"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"
)
@@ -61,7 +64,11 @@ func TestMaintainedProjectsWithControlledProvider(t *testing.T) {
t.Setenv("AUDITA_EXAMPLE_KEY", "")
main = filepath.Join(dir, "config.yml")
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(main)}, tc.overlay)
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)
}
@@ -93,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)
}
@@ -105,13 +112,13 @@ 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.Application.Pipeline.Stages) {
@@ -157,11 +164,11 @@ func TestExamplePromptEditIsCapturedOnNextLoad(t *testing.T) {
}
}
inspect := func() string {
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
}
@@ -185,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
View File

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

View File

@@ -0,0 +1,303 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
commandkit "go.maximumdirect.net/commandkit"
pk "go.maximumdirect.net/promptkit"
)
func TestPreflightBindingsAndRunAlias(t *testing.T) {
dir := t.TempDir()
for name, contents := range map[string]string{
"config.yml": "version: 3\npipeline: {stages: []}\nreporting: {enabled: false}\n",
"transcript.json": `[{"speaker":"Alice","start":0,"end":1,"text":"hello"}]`,
"glossary.yml": "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())
}
})
}
}

View File

@@ -6,7 +6,6 @@ import (
"sync"
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/normalization"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/outputschema"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
@@ -26,37 +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)
}
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)
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
@@ -74,13 +47,8 @@ func runProcess(inv commandkit.Invocation, input processInput) commandkit.Outcom
}
loaded.RawTranscript = nil
cfg := &loaded.Configuration.Config.Application
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()
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))
@@ -89,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 {
@@ -116,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)
}

View File

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

View File

@@ -38,15 +38,23 @@ type runtimePreparationError struct{ cause error }
func (e *runtimePreparationError) Error() string { return e.cause.Error() }
func (e *runtimePreparationError) Unwrap() error { return e.cause }
func loadProcessInputs(ctx context.Context, input processInput, mode commandkit.ReportingMode) (*processInputs, error) {
func 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, &runtimePreparationError{cause: err}
@@ -69,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)
@@ -79,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) {
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 {
@@ -102,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
@@ -125,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) {

View File

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

View File

@@ -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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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,7 +117,7 @@ pipeline:
if err != nil {
t.Fatal(err)
}
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
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{})
@@ -121,7 +125,20 @@ pipeline:
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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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}
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)
}
@@ -256,7 +273,7 @@ func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -281,7 +298,7 @@ func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) {
body := fmt.Sprintf(`{"model":%q,"choices":[{"message":{"content":%s}}]}`, request.Model, encoded)
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})
runtime, err := llm.NewRuntime(context.Background(), loaded, &http.Client{Transport: transport})
runtime, err := llm.NewRuntime(context.Background(), loaded.Result, &http.Client{Transport: transport})
if err != nil {
t.Fatal(err)
}
@@ -289,14 +306,14 @@ func TestMalformedPermissivePromptKeepsLaterWork(t *testing.T) {
if err != nil {
t.Fatal(err)
}
inputs := &processInputs{Configuration: loaded, Runtime: runtime, Source: source}
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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -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"`
@@ -106,11 +107,18 @@ func defaults() Config {
}
}
// 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")
}
// Definition describes the application settings independently of their sources.
func Definition() ck.Definition[Config] {
return ck.Definition[Config]{
Defaults: defaults,
SequenceIdentities: []ck.SequenceIdentity{ck.SequenceIdentityMatching(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections"), ck.SequenceAnyMappingKey(), ck.SequenceLiteralKey("entries")}, "id")},
SequenceIdentities: []ck.SequenceIdentity{GlossaryEntryIdentity(ck.SequenceSelector{ck.SequenceLiteralKey("glossary_collections")})},
Version: &ck.VersionRule{Path: ck.Keys("version"), Check: func(version ck.Version, v *ck.Validation) error {
if version.Present && (version.Null || version.Text != "3") {
v.Error(ck.Keys("version"), "use application configuration version 3; see docs/migrations/v3.md")

View File

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

View File

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

View File

@@ -68,10 +68,20 @@ type OutputSession struct {
stdout io.Writer
}
// 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.

View File

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

View File

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

View File

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

View File

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

View File

@@ -24,11 +24,11 @@ func capacityFixture(t *testing.T, resources string, transport http.RoundTripper
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
}

View File

@@ -105,7 +105,7 @@ func adapterFixtureWithPrompt(t *testing.T, replies []reply, retries, repairs in
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -131,7 +131,7 @@ 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)
}

View File

@@ -16,6 +16,7 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/appconfig"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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,7 +70,14 @@ func TestRoleClientCoordinatesIndependentRepairConversations(t *testing.T) {
if err != nil {
t.Fatal(err)
}
vars := map[string]string{"TranscriptDescriptionBlock": "", "GlossaryJSON": "[]", "SectionJSON": "[]"}
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)
@@ -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)
}
@@ -136,7 +149,7 @@ func TestCoordinatedRepairUsesReplacementAndCountsStructuralRepair(t *testing.T)
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -154,7 +167,7 @@ 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)
}

View File

@@ -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 := appconfig.Load(context.Background(), 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 := appconfig.Load(context.Background(), 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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, ""); err == nil || appconfig.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 := appconfig.Load(context.Background(), 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 := appconfig.Load(context.Background(), 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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
}

View File

@@ -37,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 := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -50,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)
}
@@ -75,7 +75,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -104,7 +104,7 @@ func TestRoleClientExecutionBudgetsAndFailureClasses(t *testing.T) {
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"))}, "")
selected, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -116,7 +116,7 @@ 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(), selected, httpClient)
runtime, err := NewRuntime(context.Background(), selected.Result, httpClient)
if err != nil {
t.Fatal(err)
}
@@ -145,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)
}
@@ -169,7 +169,7 @@ func TestRoleClientsShareBackendCapacity(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -180,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)
}
@@ -218,7 +218,7 @@ func TestRoleClientRetriesFollowRequestBudget(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -231,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)
}
@@ -259,7 +259,7 @@ func TestNativeCredentialSelectionAndOptionalAbsence(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
@@ -269,7 +269,7 @@ 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)
}

View File

@@ -11,7 +11,7 @@ import (
)
func TestRuntimeCapturesShippedPromptsAndHonorsCancellation(t *testing.T) {
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}

View File

@@ -20,7 +20,7 @@ func (r rejectingTransport) RoundTrip(*http.Request) (*http.Response, error) {
}
func TestRuntimeInspectionDoesNotRequireCredentialsOrProvider(t *testing.T) {
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.NoSource()}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}

View File

@@ -26,11 +26,11 @@ func TestRuntimeCapturesSharedSources(t *testing.T) {
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(project, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(project, "config.yml")), Filesystem: &ck.FilesystemContext{Root: root}}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
runtime, err := NewRuntime(context.Background(), loaded, nil)
runtime, err := NewRuntime(context.Background(), loaded.Result, nil)
if err != nil {
t.Fatal(err)
}

View File

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

View File

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

View File

@@ -33,11 +33,11 @@ func TestRuntimeTracksCapturedConfigurationAndInheritedMessageFiles(t *testing.T
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, 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)
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,14 +3,31 @@ package promptcontext
import (
"encoding/json"
"fmt"
"strings"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/glossary"
)
// GlossaryVariables contains the glossary inputs shared by a stage's proposals.
type GlossaryVariables struct {
ContextJSON string
ProtectionJSON string
ContextJSON string
ProtectionJSON string
InstructionsBlock string
}
type GlossaryInstruction struct {
Collection string
Text string
}
func GlossaryInstructionsBlock(instructions []GlossaryInstruction) string {
var blocks []string
for _, instruction := range instructions {
if instruction.Text != "" {
blocks = append(blocks, instruction.Collection+":\n"+instruction.Text)
}
}
return strings.Join(blocks, "\n\n")
}
func PrepareGlossaryVariables(entries []glossary.Entry, terms []glossary.Term) (GlossaryVariables, error) {

View File

@@ -47,11 +47,11 @@ func TestRepairedProposalStillFacesDomainChecks(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte("profiles:\n - {id: base, endpoint: 'https://example.invalid/v1', model: local-model, api_key_required: false}\n"), 0600); err != nil {
t.Fatal(err)
}
loaded, _, err := appconfig.Load(context.Background(), 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)
}
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)
}

View File

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

View File

@@ -15,6 +15,7 @@ func buildProposalVariables(transcript *schema.Transcript, glossary promptcontex
return map[string]string{
"TranscriptDescriptionBlock": promptcontext.TranscriptDescriptionBlock(transcriptDescription),
"GlossaryJSON": glossary.ContextJSON,
"GlossaryInstructionsBlock": glossary.InstructionsBlock,
"ProtectedTermsJSON": glossary.ProtectionJSON,
"SectionJSON": string(sectionJSON),
}, nil

View File

@@ -16,11 +16,12 @@ func TestBuildProposalVariablesPreservesSectionGlossaryAndDescription(t *testing
if err != nil {
t.Fatal(err)
}
prepared.InstructionsBlock = "party: use this guidance"
variables, err := buildProposalVariables(transcript, prepared, 0, " Fantasy names ")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(variables["SectionJSON"], `"section_index": 0`) || !strings.Contains(variables["SectionJSON"], "gestures") || !strings.Contains(variables["GlossaryJSON"], "Jesters") || !strings.Contains(variables["TranscriptDescriptionBlock"], "Fantasy names") {
if !strings.Contains(variables["SectionJSON"], `"section_index": 0`) || !strings.Contains(variables["SectionJSON"], "gestures") || !strings.Contains(variables["GlossaryJSON"], "Jesters") || !strings.Contains(variables["TranscriptDescriptionBlock"], "Fantasy names") || variables["GlossaryInstructionsBlock"] != prepared.InstructionsBlock {
t.Fatalf("encoded variables incomplete: %+v", variables)
}
empty, err := buildProposalVariables(transcript, prepared, 0, " ")

View File

@@ -56,12 +56,12 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "prompts.yml"), []byte(resources), 0600); err != nil {
t.Fatal(err)
}
loaded, _, err := appconfig.Load(context.Background(), 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)
}
transport := &cancelTransport{entered: make(chan struct{}, 3)}
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)
}
@@ -165,9 +165,9 @@ func TestValidatorFailureCancelsActiveAndPendingProviderWork(t *testing.T) {
func TestCanceledEmptyPipelineReturnsCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
out, err := New(fakeFactory{}).Run(ctx, RunInput{
out, err := New(fakeFactory{}).Run(ctx, preparedTestInput(testRunInput{
Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 71, Text: "original"}}},
})
}))
if !errors.Is(err, context.Canceled) || out.FinalTranscript == nil || out.FinalTranscript.Segments[0].Text != "original" {
t.Fatalf("canceled entry: result=%+v error=%v", out, err)
}
@@ -205,11 +205,11 @@ func TestRunnerRetainsLaterProposalEvidenceWhenEarlierSectionFails(t *testing.T)
cfg := runnerTestConfig()
cfg.Chunking.MaxSectionTokens = 3
cfg.Chunking.MinSectionTokens = 0
out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, RunInput{
out, err := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}).Run(ctx, preparedTestInput(testRunInput{
Config: &cfg, Evidence: &EvidenceSelection{Reports: true, Debug: true},
Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 71, Text: "original text"}, {ID: 93, Text: "other text"}}},
ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}},
})
}))
if !errors.Is(err, origin) || len(out.Candidates) != 1 || len(out.WorkUnits) != 2 {
t.Fatalf("interrupted evidence: candidates=%+v work=%+v error=%v", out.Candidates, out.WorkUnits, err)
}
@@ -243,10 +243,10 @@ func TestRunnerCancellationAfterApprovalKeepsCommittedModuleText(t *testing.T) {
"first": fakeModule{key: "first", policy: proposals.ReplacementPolicyRequireUnique, proposeF: propose("teh", "the")},
"second": fakeModule{key: "second", policy: proposals.ReplacementPolicyRequireUnique, proposeF: propose("cat", "dog"), validators: []validators.Validator{last}},
}})
out, err := r.Run(ctx, RunInput{
out, err := r.Run(ctx, preparedTestInput(testRunInput{
Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "teh cat"}}},
ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "first", InstanceName: "first"}, {Index: 1, ModuleKey: "second", InstanceName: "second"}},
})
}))
var failure *ExecutionFailure
if !errors.Is(err, context.Canceled) || !errors.As(err, &failure) || failure.Origin == nil || *failure.Origin.StageIndex != 1 ||
len(out.ModuleResults) != 2 || out.ModuleResults[0].Status != ModuleStatusSuccess || out.ModuleResults[1].Status != ModuleStatusFailed ||

View File

@@ -50,9 +50,9 @@ func evidenceFixture(size int) (*Runner, RunInput) {
}, nil
},
}
return New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}), RunInput{
return New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}}), preparedTestInput(testRunInput{
Config: &cfg, Transcript: transcript, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar"}},
}
})
}
func TestEvidenceSelectionKeepsTotalsAndRequestedRecords(t *testing.T) {

View File

@@ -51,7 +51,7 @@ func TestOrderedWorkflowUsesIndependentSelectionsAndPriorEdits(t *testing.T) {
{Module: "grammar", Glossaries: []string{"party", "spells"}, ProtectedTerms: []string{"party", "spells"}},
}}}
seen := make(chan contracts.ProposalRequest, 3)
output, err := New(orderedFactory{seen: seen}).Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "party spell"}}}, ModuleSpecs: contracts.ResolveModuleRunSpecs(cfg)})
output, err := New(orderedFactory{seen: seen}).Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "party spell"}}}, ModuleSpecs: contracts.ResolveModuleRunSpecs(cfg)}))
if err != nil {
t.Fatal(err)
}

View File

@@ -0,0 +1,31 @@
package runner
import (
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
)
type testRunInput struct {
Config *config.Config
Transcript *schema.Transcript
ModuleSpecs []contracts.ModuleRunSpec
Interactions structuredoutput.InteractionSink
Evidence *EvidenceSelection
Progress func(Progress)
}
func preparedTestInput(input testRunInput) RunInput {
cfg := chunking.ChunkingConfig{MaxSectionTokens: int(^uint(0) >> 1)}
if input.Config != nil {
cfg = chunking.ChunkingConfig{MaxSectionTokens: input.Config.Chunking.MaxSectionTokens, MinSectionTokens: input.Config.Chunking.MinSectionTokens, TargetSections: input.Config.Chunking.TargetSections}
}
sections, err := chunking.NewChunker(cfg).ChunkTranscript(input.Transcript)
if err != nil {
panic(err)
}
return RunInput{Plan: &preflight.Plan{Sections: sections, Transcript: input.Transcript, Specs: input.ModuleSpecs, Config: input.Config}, Interactions: input.Interactions, Evidence: input.Evidence, Progress: input.Progress}
}

View File

@@ -219,13 +219,13 @@ func TestRunnerChecksRepairCapabilityBeforeSubmittingProposals(t *testing.T) {
return contracts.ProposalResult{}, nil
}}}
r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}})
out, err := r.Run(context.Background(), RunInput{
out, err := r.Run(context.Background(), preparedTestInput(testRunInput{
Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat"}}},
ModuleSpecs: []contracts.ModuleRunSpec{{
ModuleKey: "grammar", InstanceName: "grammar",
Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}},
}},
})
}))
var failure *structuredoutput.Failure
if !errors.As(err, &failure) || failure.Class != outcomes.FailureFatal || failure.Reason != outcomes.ReasonSetupFailure ||
calls != 0 || len(out.WorkUnits) != 1 || out.WorkUnits[0].State != outcomes.WorkNotStarted {
@@ -242,7 +242,7 @@ func TestRunnerAppliesRevisionsInOriginalOrder(t *testing.T) {
return contracts.ProposalResult{Proposals: candidates, SegmentReferences: []int{1, 1, 1}, Exchange: &structuredoutput.Exchange{}}, nil
}}}
runner := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}})
out, err := runner.Run(context.Background(), RunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client, Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}}}})
out, err := runner.Run(context.Background(), preparedTestInput(testRunInput{Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}}, ModuleSpecs: []contracts.ModuleRunSpec{{ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client, Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}}}}}))
if err != nil {
t.Fatal(err)
}
@@ -281,13 +281,13 @@ func TestRunnerAttributesApplicationFilteringToEachRepair(t *testing.T) {
},
}}
r := New(fakeFactory{modules: map[string]contracts.TranscriptModule{"grammar": module}})
out, err := r.Run(context.Background(), RunInput{
out, err := r.Run(context.Background(), preparedTestInput(testRunInput{
Transcript: &schema.Transcript{Segments: []schema.Segment{{ID: 1, Text: "cat and bird"}}},
ModuleSpecs: []contracts.ModuleRunSpec{{
ModuleKey: "grammar", InstanceName: "grammar", RepairCoordinator: client,
Settings: config.Stage{LLM: config.LLM{CorrectionRepairAttempts: 1}},
}},
})
}))
if err != nil {
t.Fatal(err)
}
@@ -488,13 +488,13 @@ func (c *repairClient) Coordinate(ctx context.Context, _ *structuredoutput.Excha
t.Fatal(err)
}
}
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, "")
loaded, _, err := appconfig.Load(context.Background(), ck.Input{Source: ck.File(filepath.Join(dir, "config.yml"))}, appconfig.Options{})
if err != nil {
t.Fatal(err)
}
var selected *structuredoutput.Request
initial := true
runtime, err := llm.NewRuntime(ctx, loaded, &http.Client{Transport: repairTransport(func(*http.Request) (*http.Response, error) {
runtime, err := llm.NewRuntime(ctx, loaded.Result, &http.Client{Transport: repairTransport(func(*http.Request) (*http.Response, error) {
content := `{"corrections":[]}`
if initial {
initial = false

View File

@@ -9,12 +9,12 @@ import (
"sync"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/chunking"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/config"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/glossary"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/modulecatalog"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/outcomes"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/preflight"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/promptcontext"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/proposals"
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
@@ -114,9 +114,7 @@ func selectEvidence(selection *EvidenceSelection) evidenceNeeds {
// RunInput is the deterministic runner input.
type RunInput struct {
Config *config.Config
Transcript *schema.Transcript
ModuleSpecs []contracts.ModuleRunSpec
Plan *preflight.Plan
Interactions structuredoutput.InteractionSink
Evidence *EvidenceSelection
Progress func(Progress)
@@ -139,20 +137,16 @@ func New(factory ModuleFactory) *Runner {
func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) {
if err := ctx.Err(); err != nil {
return RunOutput{FinalTranscript: input.Transcript.Clone()}, &ExecutionFailure{Phase: "processing", Cause: err}
return RunOutput{FinalTranscript: input.Plan.Transcript.Clone()}, &ExecutionFailure{Phase: "processing", Cause: err}
}
if r == nil || r.factory == nil {
return RunOutput{}, &ExecutionFailure{Phase: "setup", Cause: errors.New("runner module factory is required")}
}
working := input.Transcript.Clone()
results := make([]ModuleResult, 0, len(input.ModuleSpecs))
sections, err := chunkWorkingTranscript(input.Config, working)
if err != nil {
return RunOutput{FinalTranscript: working}, &ExecutionFailure{Phase: "chunking", Cause: fmt.Errorf("chunk normalized transcript: %w", err)}
}
results := make([]ModuleResult, 0, len(input.Plan.Specs))
sections := input.Plan.Sections
evidence := selectEvidence(input.Evidence)
totals := outcomes.WorkTotals{Total: len(input.ModuleSpecs) * len(sections)}
totals := outcomes.WorkTotals{Total: len(input.Plan.Specs) * len(sections)}
var inventory []contracts.SectionMetadata
var workUnits []WorkUnitOutcome
var candidates []proposals.EnrichedCorrectionProposal
@@ -162,7 +156,7 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) {
inventory[i] = contracts.SectionMetadataFromSection(section)
}
workUnits = make([]WorkUnitOutcome, 0, totals.Total)
for moduleIndex, spec := range input.ModuleSpecs {
for moduleIndex, spec := range input.Plan.Specs {
for _, section := range inventory {
workUnits = append(workUnits, newWorkUnit(spec, section, moduleIndex))
}
@@ -175,7 +169,7 @@ func (r *Runner) Run(ctx context.Context, input RunInput) (RunOutput, error) {
}
}
for moduleIndex, spec := range input.ModuleSpecs {
for moduleIndex, spec := range input.Plan.Specs {
progress := Progress{ModuleIndex: spec.Index, ModuleKey: spec.ModuleKey, ModuleID: spec.ID}
sectionCount := len(sections)
progress.emit(input.Progress, "started", nil, &sectionCount)
@@ -1031,41 +1025,6 @@ func reorderValidatorsForPipeline(in []validators.Validator) ([]validators.Valid
return ordered, order
}
func chunkWorkingTranscript(cfg *config.Config, transcript *schema.Transcript) ([]chunking.Section, error) {
if cfg == nil {
if transcript == nil || len(transcript.Segments) == 0 {
return []chunking.Section{}, nil
}
return []chunking.Section{
{
Index: 0,
EstimatedTokens: estimateTranscriptTokens(transcript),
Segments: append([]schema.Segment(nil), transcript.Segments...),
StartSegmentID: transcript.Segments[0].ID,
EndSegmentID: transcript.Segments[len(transcript.Segments)-1].ID,
},
}, nil
}
chunker := chunking.NewChunker(chunking.ChunkingConfig{
MaxSectionTokens: cfg.Chunking.MaxSectionTokens,
MinSectionTokens: cfg.Chunking.MinSectionTokens,
TargetSections: cfg.Chunking.TargetSections,
})
return chunker.ChunkTranscript(transcript)
}
func estimateTranscriptTokens(transcript *schema.Transcript) int {
if transcript == nil || len(transcript.Segments) == 0 {
return 0
}
estimator := chunking.NewSimpleTokenEstimator()
total := 0
for _, segment := range transcript.Segments {
total += estimator.EstimateTokens(segment.Text)
}
return total
}
func transcriptFromSection(section chunking.Section) *schema.Transcript {
segments := make([]schema.Segment, len(section.Segments))
copy(segments, section.Segments)

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